1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds 4 * 5 * Swap reorganised 29.12.95, Stephen Tweedie. 6 * kswapd added: 7.1.96 sct 7 * Removed kswapd_ctl limits, and swap out as many pages as needed 8 * to bring the system back to freepages.high: 2.4.97, Rik van Riel. 9 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com). 10 * Multiqueue VM started 5.8.00, Rik van Riel. 11 */ 12 13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 14 15 #include <linux/mm.h> 16 #include <linux/sched/mm.h> 17 #include <linux/module.h> 18 #include <linux/gfp.h> 19 #include <linux/kernel_stat.h> 20 #include <linux/swap.h> 21 #include <linux/pagemap.h> 22 #include <linux/init.h> 23 #include <linux/highmem.h> 24 #include <linux/vmpressure.h> 25 #include <linux/vmstat.h> 26 #include <linux/file.h> 27 #include <linux/writeback.h> 28 #include <linux/blkdev.h> 29 #include <linux/buffer_head.h> /* for buffer_heads_over_limit */ 30 #include <linux/mm_inline.h> 31 #include <linux/backing-dev.h> 32 #include <linux/rmap.h> 33 #include <linux/topology.h> 34 #include <linux/cpu.h> 35 #include <linux/cpuset.h> 36 #include <linux/compaction.h> 37 #include <linux/notifier.h> 38 #include <linux/rwsem.h> 39 #include <linux/delay.h> 40 #include <linux/kthread.h> 41 #include <linux/freezer.h> 42 #include <linux/memcontrol.h> 43 #include <linux/migrate.h> 44 #include <linux/delayacct.h> 45 #include <linux/sysctl.h> 46 #include <linux/oom.h> 47 #include <linux/pagevec.h> 48 #include <linux/prefetch.h> 49 #include <linux/printk.h> 50 #include <linux/dax.h> 51 #include <linux/psi.h> 52 #include <linux/pagewalk.h> 53 #include <linux/shmem_fs.h> 54 55 #include <asm/tlbflush.h> 56 #include <asm/div64.h> 57 58 #include <linux/swapops.h> 59 #include <linux/balloon_compaction.h> 60 #include <linux/sched/sysctl.h> 61 62 #include "internal.h" 63 #include "swap.h" 64 65 #define CREATE_TRACE_POINTS 66 #include <trace/events/vmscan.h> 67 68 struct scan_control { 69 /* How many pages shrink_list() should reclaim */ 70 unsigned long nr_to_reclaim; 71 72 /* 73 * Nodemask of nodes allowed by the caller. If NULL, all nodes 74 * are scanned. 75 */ 76 nodemask_t *nodemask; 77 78 /* 79 * The memory cgroup that hit its limit and as a result is the 80 * primary target of this reclaim invocation. 81 */ 82 struct mem_cgroup *target_mem_cgroup; 83 84 /* 85 * Scan pressure balancing between anon and file LRUs 86 */ 87 unsigned long anon_cost; 88 unsigned long file_cost; 89 90 /* Can active pages be deactivated as part of reclaim? */ 91 #define DEACTIVATE_ANON 1 92 #define DEACTIVATE_FILE 2 93 unsigned int may_deactivate:2; 94 unsigned int force_deactivate:1; 95 unsigned int skipped_deactivate:1; 96 97 /* Writepage batching in laptop mode; RECLAIM_WRITE */ 98 unsigned int may_writepage:1; 99 100 /* Can mapped pages be reclaimed? */ 101 unsigned int may_unmap:1; 102 103 /* Can pages be swapped as part of reclaim? */ 104 unsigned int may_swap:1; 105 106 /* Proactive reclaim invoked by userspace through memory.reclaim */ 107 unsigned int proactive:1; 108 109 /* 110 * Cgroup memory below memory.low is protected as long as we 111 * don't threaten to OOM. If any cgroup is reclaimed at 112 * reduced force or passed over entirely due to its memory.low 113 * setting (memcg_low_skipped), and nothing is reclaimed as a 114 * result, then go back for one more cycle that reclaims the protected 115 * memory (memcg_low_reclaim) to avert OOM. 116 */ 117 unsigned int memcg_low_reclaim:1; 118 unsigned int memcg_low_skipped:1; 119 120 unsigned int hibernation_mode:1; 121 122 /* One of the zones is ready for compaction */ 123 unsigned int compaction_ready:1; 124 125 /* There is easily reclaimable cold cache in the current node */ 126 unsigned int cache_trim_mode:1; 127 128 /* The file pages on the current node are dangerously low */ 129 unsigned int file_is_tiny:1; 130 131 /* Always discard instead of demoting to lower tier memory */ 132 unsigned int no_demotion:1; 133 134 /* Allocation order */ 135 s8 order; 136 137 /* Scan (total_size >> priority) pages at once */ 138 s8 priority; 139 140 /* The highest zone to isolate pages for reclaim from */ 141 s8 reclaim_idx; 142 143 /* This context's GFP mask */ 144 gfp_t gfp_mask; 145 146 /* Incremented by the number of inactive pages that were scanned */ 147 unsigned long nr_scanned; 148 149 /* Number of pages freed so far during a call to shrink_zones() */ 150 unsigned long nr_reclaimed; 151 152 struct { 153 unsigned int dirty; 154 unsigned int unqueued_dirty; 155 unsigned int congested; 156 unsigned int writeback; 157 unsigned int immediate; 158 unsigned int file_taken; 159 unsigned int taken; 160 } nr; 161 162 /* for recording the reclaimed slab by now */ 163 struct reclaim_state reclaim_state; 164 }; 165 166 #ifdef ARCH_HAS_PREFETCHW 167 #define prefetchw_prev_lru_folio(_folio, _base, _field) \ 168 do { \ 169 if ((_folio)->lru.prev != _base) { \ 170 struct folio *prev; \ 171 \ 172 prev = lru_to_folio(&(_folio->lru)); \ 173 prefetchw(&prev->_field); \ 174 } \ 175 } while (0) 176 #else 177 #define prefetchw_prev_lru_folio(_folio, _base, _field) do { } while (0) 178 #endif 179 180 /* 181 * From 0 .. 200. Higher means more swappy. 182 */ 183 int vm_swappiness = 60; 184 185 static void set_task_reclaim_state(struct task_struct *task, 186 struct reclaim_state *rs) 187 { 188 /* Check for an overwrite */ 189 WARN_ON_ONCE(rs && task->reclaim_state); 190 191 /* Check for the nulling of an already-nulled member */ 192 WARN_ON_ONCE(!rs && !task->reclaim_state); 193 194 task->reclaim_state = rs; 195 } 196 197 LIST_HEAD(shrinker_list); 198 DECLARE_RWSEM(shrinker_rwsem); 199 200 #ifdef CONFIG_MEMCG 201 static int shrinker_nr_max; 202 203 /* The shrinker_info is expanded in a batch of BITS_PER_LONG */ 204 static inline int shrinker_map_size(int nr_items) 205 { 206 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long)); 207 } 208 209 static inline int shrinker_defer_size(int nr_items) 210 { 211 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t)); 212 } 213 214 static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg, 215 int nid) 216 { 217 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info, 218 lockdep_is_held(&shrinker_rwsem)); 219 } 220 221 static int expand_one_shrinker_info(struct mem_cgroup *memcg, 222 int map_size, int defer_size, 223 int old_map_size, int old_defer_size) 224 { 225 struct shrinker_info *new, *old; 226 struct mem_cgroup_per_node *pn; 227 int nid; 228 int size = map_size + defer_size; 229 230 for_each_node(nid) { 231 pn = memcg->nodeinfo[nid]; 232 old = shrinker_info_protected(memcg, nid); 233 /* Not yet online memcg */ 234 if (!old) 235 return 0; 236 237 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid); 238 if (!new) 239 return -ENOMEM; 240 241 new->nr_deferred = (atomic_long_t *)(new + 1); 242 new->map = (void *)new->nr_deferred + defer_size; 243 244 /* map: set all old bits, clear all new bits */ 245 memset(new->map, (int)0xff, old_map_size); 246 memset((void *)new->map + old_map_size, 0, map_size - old_map_size); 247 /* nr_deferred: copy old values, clear all new values */ 248 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size); 249 memset((void *)new->nr_deferred + old_defer_size, 0, 250 defer_size - old_defer_size); 251 252 rcu_assign_pointer(pn->shrinker_info, new); 253 kvfree_rcu(old, rcu); 254 } 255 256 return 0; 257 } 258 259 void free_shrinker_info(struct mem_cgroup *memcg) 260 { 261 struct mem_cgroup_per_node *pn; 262 struct shrinker_info *info; 263 int nid; 264 265 for_each_node(nid) { 266 pn = memcg->nodeinfo[nid]; 267 info = rcu_dereference_protected(pn->shrinker_info, true); 268 kvfree(info); 269 rcu_assign_pointer(pn->shrinker_info, NULL); 270 } 271 } 272 273 int alloc_shrinker_info(struct mem_cgroup *memcg) 274 { 275 struct shrinker_info *info; 276 int nid, size, ret = 0; 277 int map_size, defer_size = 0; 278 279 down_write(&shrinker_rwsem); 280 map_size = shrinker_map_size(shrinker_nr_max); 281 defer_size = shrinker_defer_size(shrinker_nr_max); 282 size = map_size + defer_size; 283 for_each_node(nid) { 284 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid); 285 if (!info) { 286 free_shrinker_info(memcg); 287 ret = -ENOMEM; 288 break; 289 } 290 info->nr_deferred = (atomic_long_t *)(info + 1); 291 info->map = (void *)info->nr_deferred + defer_size; 292 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info); 293 } 294 up_write(&shrinker_rwsem); 295 296 return ret; 297 } 298 299 static inline bool need_expand(int nr_max) 300 { 301 return round_up(nr_max, BITS_PER_LONG) > 302 round_up(shrinker_nr_max, BITS_PER_LONG); 303 } 304 305 static int expand_shrinker_info(int new_id) 306 { 307 int ret = 0; 308 int new_nr_max = new_id + 1; 309 int map_size, defer_size = 0; 310 int old_map_size, old_defer_size = 0; 311 struct mem_cgroup *memcg; 312 313 if (!need_expand(new_nr_max)) 314 goto out; 315 316 if (!root_mem_cgroup) 317 goto out; 318 319 lockdep_assert_held(&shrinker_rwsem); 320 321 map_size = shrinker_map_size(new_nr_max); 322 defer_size = shrinker_defer_size(new_nr_max); 323 old_map_size = shrinker_map_size(shrinker_nr_max); 324 old_defer_size = shrinker_defer_size(shrinker_nr_max); 325 326 memcg = mem_cgroup_iter(NULL, NULL, NULL); 327 do { 328 ret = expand_one_shrinker_info(memcg, map_size, defer_size, 329 old_map_size, old_defer_size); 330 if (ret) { 331 mem_cgroup_iter_break(NULL, memcg); 332 goto out; 333 } 334 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL); 335 out: 336 if (!ret) 337 shrinker_nr_max = new_nr_max; 338 339 return ret; 340 } 341 342 void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id) 343 { 344 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) { 345 struct shrinker_info *info; 346 347 rcu_read_lock(); 348 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info); 349 /* Pairs with smp mb in shrink_slab() */ 350 smp_mb__before_atomic(); 351 set_bit(shrinker_id, info->map); 352 rcu_read_unlock(); 353 } 354 } 355 356 static DEFINE_IDR(shrinker_idr); 357 358 static int prealloc_memcg_shrinker(struct shrinker *shrinker) 359 { 360 int id, ret = -ENOMEM; 361 362 if (mem_cgroup_disabled()) 363 return -ENOSYS; 364 365 down_write(&shrinker_rwsem); 366 /* This may call shrinker, so it must use down_read_trylock() */ 367 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL); 368 if (id < 0) 369 goto unlock; 370 371 if (id >= shrinker_nr_max) { 372 if (expand_shrinker_info(id)) { 373 idr_remove(&shrinker_idr, id); 374 goto unlock; 375 } 376 } 377 shrinker->id = id; 378 ret = 0; 379 unlock: 380 up_write(&shrinker_rwsem); 381 return ret; 382 } 383 384 static void unregister_memcg_shrinker(struct shrinker *shrinker) 385 { 386 int id = shrinker->id; 387 388 BUG_ON(id < 0); 389 390 lockdep_assert_held(&shrinker_rwsem); 391 392 idr_remove(&shrinker_idr, id); 393 } 394 395 static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker, 396 struct mem_cgroup *memcg) 397 { 398 struct shrinker_info *info; 399 400 info = shrinker_info_protected(memcg, nid); 401 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0); 402 } 403 404 static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker, 405 struct mem_cgroup *memcg) 406 { 407 struct shrinker_info *info; 408 409 info = shrinker_info_protected(memcg, nid); 410 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]); 411 } 412 413 void reparent_shrinker_deferred(struct mem_cgroup *memcg) 414 { 415 int i, nid; 416 long nr; 417 struct mem_cgroup *parent; 418 struct shrinker_info *child_info, *parent_info; 419 420 parent = parent_mem_cgroup(memcg); 421 if (!parent) 422 parent = root_mem_cgroup; 423 424 /* Prevent from concurrent shrinker_info expand */ 425 down_read(&shrinker_rwsem); 426 for_each_node(nid) { 427 child_info = shrinker_info_protected(memcg, nid); 428 parent_info = shrinker_info_protected(parent, nid); 429 for (i = 0; i < shrinker_nr_max; i++) { 430 nr = atomic_long_read(&child_info->nr_deferred[i]); 431 atomic_long_add(nr, &parent_info->nr_deferred[i]); 432 } 433 } 434 up_read(&shrinker_rwsem); 435 } 436 437 static bool cgroup_reclaim(struct scan_control *sc) 438 { 439 return sc->target_mem_cgroup; 440 } 441 442 /** 443 * writeback_throttling_sane - is the usual dirty throttling mechanism available? 444 * @sc: scan_control in question 445 * 446 * The normal page dirty throttling mechanism in balance_dirty_pages() is 447 * completely broken with the legacy memcg and direct stalling in 448 * shrink_page_list() is used for throttling instead, which lacks all the 449 * niceties such as fairness, adaptive pausing, bandwidth proportional 450 * allocation and configurability. 451 * 452 * This function tests whether the vmscan currently in progress can assume 453 * that the normal dirty throttling mechanism is operational. 454 */ 455 static bool writeback_throttling_sane(struct scan_control *sc) 456 { 457 if (!cgroup_reclaim(sc)) 458 return true; 459 #ifdef CONFIG_CGROUP_WRITEBACK 460 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) 461 return true; 462 #endif 463 return false; 464 } 465 #else 466 static int prealloc_memcg_shrinker(struct shrinker *shrinker) 467 { 468 return -ENOSYS; 469 } 470 471 static void unregister_memcg_shrinker(struct shrinker *shrinker) 472 { 473 } 474 475 static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker, 476 struct mem_cgroup *memcg) 477 { 478 return 0; 479 } 480 481 static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker, 482 struct mem_cgroup *memcg) 483 { 484 return 0; 485 } 486 487 static bool cgroup_reclaim(struct scan_control *sc) 488 { 489 return false; 490 } 491 492 static bool writeback_throttling_sane(struct scan_control *sc) 493 { 494 return true; 495 } 496 #endif 497 498 static long xchg_nr_deferred(struct shrinker *shrinker, 499 struct shrink_control *sc) 500 { 501 int nid = sc->nid; 502 503 if (!(shrinker->flags & SHRINKER_NUMA_AWARE)) 504 nid = 0; 505 506 if (sc->memcg && 507 (shrinker->flags & SHRINKER_MEMCG_AWARE)) 508 return xchg_nr_deferred_memcg(nid, shrinker, 509 sc->memcg); 510 511 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0); 512 } 513 514 515 static long add_nr_deferred(long nr, struct shrinker *shrinker, 516 struct shrink_control *sc) 517 { 518 int nid = sc->nid; 519 520 if (!(shrinker->flags & SHRINKER_NUMA_AWARE)) 521 nid = 0; 522 523 if (sc->memcg && 524 (shrinker->flags & SHRINKER_MEMCG_AWARE)) 525 return add_nr_deferred_memcg(nr, nid, shrinker, 526 sc->memcg); 527 528 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]); 529 } 530 531 static bool can_demote(int nid, struct scan_control *sc) 532 { 533 if (!numa_demotion_enabled) 534 return false; 535 if (sc && sc->no_demotion) 536 return false; 537 if (next_demotion_node(nid) == NUMA_NO_NODE) 538 return false; 539 540 return true; 541 } 542 543 static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg, 544 int nid, 545 struct scan_control *sc) 546 { 547 if (memcg == NULL) { 548 /* 549 * For non-memcg reclaim, is there 550 * space in any swap device? 551 */ 552 if (get_nr_swap_pages() > 0) 553 return true; 554 } else { 555 /* Is the memcg below its swap limit? */ 556 if (mem_cgroup_get_nr_swap_pages(memcg) > 0) 557 return true; 558 } 559 560 /* 561 * The page can not be swapped. 562 * 563 * Can it be reclaimed from this node via demotion? 564 */ 565 return can_demote(nid, sc); 566 } 567 568 /* 569 * This misses isolated pages which are not accounted for to save counters. 570 * As the data only determines if reclaim or compaction continues, it is 571 * not expected that isolated pages will be a dominating factor. 572 */ 573 unsigned long zone_reclaimable_pages(struct zone *zone) 574 { 575 unsigned long nr; 576 577 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) + 578 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE); 579 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL)) 580 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) + 581 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON); 582 583 return nr; 584 } 585 586 /** 587 * lruvec_lru_size - Returns the number of pages on the given LRU list. 588 * @lruvec: lru vector 589 * @lru: lru to use 590 * @zone_idx: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list) 591 */ 592 static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, 593 int zone_idx) 594 { 595 unsigned long size = 0; 596 int zid; 597 598 for (zid = 0; zid <= zone_idx; zid++) { 599 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid]; 600 601 if (!managed_zone(zone)) 602 continue; 603 604 if (!mem_cgroup_disabled()) 605 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid); 606 else 607 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru); 608 } 609 return size; 610 } 611 612 /* 613 * Add a shrinker callback to be called from the vm. 614 */ 615 static int __prealloc_shrinker(struct shrinker *shrinker) 616 { 617 unsigned int size; 618 int err; 619 620 if (shrinker->flags & SHRINKER_MEMCG_AWARE) { 621 err = prealloc_memcg_shrinker(shrinker); 622 if (err != -ENOSYS) 623 return err; 624 625 shrinker->flags &= ~SHRINKER_MEMCG_AWARE; 626 } 627 628 size = sizeof(*shrinker->nr_deferred); 629 if (shrinker->flags & SHRINKER_NUMA_AWARE) 630 size *= nr_node_ids; 631 632 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL); 633 if (!shrinker->nr_deferred) 634 return -ENOMEM; 635 636 return 0; 637 } 638 639 #ifdef CONFIG_SHRINKER_DEBUG 640 int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...) 641 { 642 va_list ap; 643 int err; 644 645 va_start(ap, fmt); 646 shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap); 647 va_end(ap); 648 if (!shrinker->name) 649 return -ENOMEM; 650 651 err = __prealloc_shrinker(shrinker); 652 if (err) { 653 kfree_const(shrinker->name); 654 shrinker->name = NULL; 655 } 656 657 return err; 658 } 659 #else 660 int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...) 661 { 662 return __prealloc_shrinker(shrinker); 663 } 664 #endif 665 666 void free_prealloced_shrinker(struct shrinker *shrinker) 667 { 668 #ifdef CONFIG_SHRINKER_DEBUG 669 kfree_const(shrinker->name); 670 shrinker->name = NULL; 671 #endif 672 if (shrinker->flags & SHRINKER_MEMCG_AWARE) { 673 down_write(&shrinker_rwsem); 674 unregister_memcg_shrinker(shrinker); 675 up_write(&shrinker_rwsem); 676 return; 677 } 678 679 kfree(shrinker->nr_deferred); 680 shrinker->nr_deferred = NULL; 681 } 682 683 void register_shrinker_prepared(struct shrinker *shrinker) 684 { 685 down_write(&shrinker_rwsem); 686 list_add_tail(&shrinker->list, &shrinker_list); 687 shrinker->flags |= SHRINKER_REGISTERED; 688 shrinker_debugfs_add(shrinker); 689 up_write(&shrinker_rwsem); 690 } 691 692 static int __register_shrinker(struct shrinker *shrinker) 693 { 694 int err = __prealloc_shrinker(shrinker); 695 696 if (err) 697 return err; 698 register_shrinker_prepared(shrinker); 699 return 0; 700 } 701 702 #ifdef CONFIG_SHRINKER_DEBUG 703 int register_shrinker(struct shrinker *shrinker, const char *fmt, ...) 704 { 705 va_list ap; 706 int err; 707 708 va_start(ap, fmt); 709 shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap); 710 va_end(ap); 711 if (!shrinker->name) 712 return -ENOMEM; 713 714 err = __register_shrinker(shrinker); 715 if (err) { 716 kfree_const(shrinker->name); 717 shrinker->name = NULL; 718 } 719 return err; 720 } 721 #else 722 int register_shrinker(struct shrinker *shrinker, const char *fmt, ...) 723 { 724 return __register_shrinker(shrinker); 725 } 726 #endif 727 EXPORT_SYMBOL(register_shrinker); 728 729 /* 730 * Remove one 731 */ 732 void unregister_shrinker(struct shrinker *shrinker) 733 { 734 if (!(shrinker->flags & SHRINKER_REGISTERED)) 735 return; 736 737 down_write(&shrinker_rwsem); 738 list_del(&shrinker->list); 739 shrinker->flags &= ~SHRINKER_REGISTERED; 740 if (shrinker->flags & SHRINKER_MEMCG_AWARE) 741 unregister_memcg_shrinker(shrinker); 742 shrinker_debugfs_remove(shrinker); 743 up_write(&shrinker_rwsem); 744 745 kfree(shrinker->nr_deferred); 746 shrinker->nr_deferred = NULL; 747 } 748 EXPORT_SYMBOL(unregister_shrinker); 749 750 /** 751 * synchronize_shrinkers - Wait for all running shrinkers to complete. 752 * 753 * This is equivalent to calling unregister_shrink() and register_shrinker(), 754 * but atomically and with less overhead. This is useful to guarantee that all 755 * shrinker invocations have seen an update, before freeing memory, similar to 756 * rcu. 757 */ 758 void synchronize_shrinkers(void) 759 { 760 down_write(&shrinker_rwsem); 761 up_write(&shrinker_rwsem); 762 } 763 EXPORT_SYMBOL(synchronize_shrinkers); 764 765 #define SHRINK_BATCH 128 766 767 static unsigned long do_shrink_slab(struct shrink_control *shrinkctl, 768 struct shrinker *shrinker, int priority) 769 { 770 unsigned long freed = 0; 771 unsigned long long delta; 772 long total_scan; 773 long freeable; 774 long nr; 775 long new_nr; 776 long batch_size = shrinker->batch ? shrinker->batch 777 : SHRINK_BATCH; 778 long scanned = 0, next_deferred; 779 780 freeable = shrinker->count_objects(shrinker, shrinkctl); 781 if (freeable == 0 || freeable == SHRINK_EMPTY) 782 return freeable; 783 784 /* 785 * copy the current shrinker scan count into a local variable 786 * and zero it so that other concurrent shrinker invocations 787 * don't also do this scanning work. 788 */ 789 nr = xchg_nr_deferred(shrinker, shrinkctl); 790 791 if (shrinker->seeks) { 792 delta = freeable >> priority; 793 delta *= 4; 794 do_div(delta, shrinker->seeks); 795 } else { 796 /* 797 * These objects don't require any IO to create. Trim 798 * them aggressively under memory pressure to keep 799 * them from causing refetches in the IO caches. 800 */ 801 delta = freeable / 2; 802 } 803 804 total_scan = nr >> priority; 805 total_scan += delta; 806 total_scan = min(total_scan, (2 * freeable)); 807 808 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr, 809 freeable, delta, total_scan, priority); 810 811 /* 812 * Normally, we should not scan less than batch_size objects in one 813 * pass to avoid too frequent shrinker calls, but if the slab has less 814 * than batch_size objects in total and we are really tight on memory, 815 * we will try to reclaim all available objects, otherwise we can end 816 * up failing allocations although there are plenty of reclaimable 817 * objects spread over several slabs with usage less than the 818 * batch_size. 819 * 820 * We detect the "tight on memory" situations by looking at the total 821 * number of objects we want to scan (total_scan). If it is greater 822 * than the total number of objects on slab (freeable), we must be 823 * scanning at high prio and therefore should try to reclaim as much as 824 * possible. 825 */ 826 while (total_scan >= batch_size || 827 total_scan >= freeable) { 828 unsigned long ret; 829 unsigned long nr_to_scan = min(batch_size, total_scan); 830 831 shrinkctl->nr_to_scan = nr_to_scan; 832 shrinkctl->nr_scanned = nr_to_scan; 833 ret = shrinker->scan_objects(shrinker, shrinkctl); 834 if (ret == SHRINK_STOP) 835 break; 836 freed += ret; 837 838 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned); 839 total_scan -= shrinkctl->nr_scanned; 840 scanned += shrinkctl->nr_scanned; 841 842 cond_resched(); 843 } 844 845 /* 846 * The deferred work is increased by any new work (delta) that wasn't 847 * done, decreased by old deferred work that was done now. 848 * 849 * And it is capped to two times of the freeable items. 850 */ 851 next_deferred = max_t(long, (nr + delta - scanned), 0); 852 next_deferred = min(next_deferred, (2 * freeable)); 853 854 /* 855 * move the unused scan count back into the shrinker in a 856 * manner that handles concurrent updates. 857 */ 858 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl); 859 860 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan); 861 return freed; 862 } 863 864 #ifdef CONFIG_MEMCG 865 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid, 866 struct mem_cgroup *memcg, int priority) 867 { 868 struct shrinker_info *info; 869 unsigned long ret, freed = 0; 870 int i; 871 872 if (!mem_cgroup_online(memcg)) 873 return 0; 874 875 if (!down_read_trylock(&shrinker_rwsem)) 876 return 0; 877 878 info = shrinker_info_protected(memcg, nid); 879 if (unlikely(!info)) 880 goto unlock; 881 882 for_each_set_bit(i, info->map, shrinker_nr_max) { 883 struct shrink_control sc = { 884 .gfp_mask = gfp_mask, 885 .nid = nid, 886 .memcg = memcg, 887 }; 888 struct shrinker *shrinker; 889 890 shrinker = idr_find(&shrinker_idr, i); 891 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) { 892 if (!shrinker) 893 clear_bit(i, info->map); 894 continue; 895 } 896 897 /* Call non-slab shrinkers even though kmem is disabled */ 898 if (!memcg_kmem_enabled() && 899 !(shrinker->flags & SHRINKER_NONSLAB)) 900 continue; 901 902 ret = do_shrink_slab(&sc, shrinker, priority); 903 if (ret == SHRINK_EMPTY) { 904 clear_bit(i, info->map); 905 /* 906 * After the shrinker reported that it had no objects to 907 * free, but before we cleared the corresponding bit in 908 * the memcg shrinker map, a new object might have been 909 * added. To make sure, we have the bit set in this 910 * case, we invoke the shrinker one more time and reset 911 * the bit if it reports that it is not empty anymore. 912 * The memory barrier here pairs with the barrier in 913 * set_shrinker_bit(): 914 * 915 * list_lru_add() shrink_slab_memcg() 916 * list_add_tail() clear_bit() 917 * <MB> <MB> 918 * set_bit() do_shrink_slab() 919 */ 920 smp_mb__after_atomic(); 921 ret = do_shrink_slab(&sc, shrinker, priority); 922 if (ret == SHRINK_EMPTY) 923 ret = 0; 924 else 925 set_shrinker_bit(memcg, nid, i); 926 } 927 freed += ret; 928 929 if (rwsem_is_contended(&shrinker_rwsem)) { 930 freed = freed ? : 1; 931 break; 932 } 933 } 934 unlock: 935 up_read(&shrinker_rwsem); 936 return freed; 937 } 938 #else /* CONFIG_MEMCG */ 939 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid, 940 struct mem_cgroup *memcg, int priority) 941 { 942 return 0; 943 } 944 #endif /* CONFIG_MEMCG */ 945 946 /** 947 * shrink_slab - shrink slab caches 948 * @gfp_mask: allocation context 949 * @nid: node whose slab caches to target 950 * @memcg: memory cgroup whose slab caches to target 951 * @priority: the reclaim priority 952 * 953 * Call the shrink functions to age shrinkable caches. 954 * 955 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set, 956 * unaware shrinkers will receive a node id of 0 instead. 957 * 958 * @memcg specifies the memory cgroup to target. Unaware shrinkers 959 * are called only if it is the root cgroup. 960 * 961 * @priority is sc->priority, we take the number of objects and >> by priority 962 * in order to get the scan target. 963 * 964 * Returns the number of reclaimed slab objects. 965 */ 966 static unsigned long shrink_slab(gfp_t gfp_mask, int nid, 967 struct mem_cgroup *memcg, 968 int priority) 969 { 970 unsigned long ret, freed = 0; 971 struct shrinker *shrinker; 972 973 /* 974 * The root memcg might be allocated even though memcg is disabled 975 * via "cgroup_disable=memory" boot parameter. This could make 976 * mem_cgroup_is_root() return false, then just run memcg slab 977 * shrink, but skip global shrink. This may result in premature 978 * oom. 979 */ 980 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg)) 981 return shrink_slab_memcg(gfp_mask, nid, memcg, priority); 982 983 if (!down_read_trylock(&shrinker_rwsem)) 984 goto out; 985 986 list_for_each_entry(shrinker, &shrinker_list, list) { 987 struct shrink_control sc = { 988 .gfp_mask = gfp_mask, 989 .nid = nid, 990 .memcg = memcg, 991 }; 992 993 ret = do_shrink_slab(&sc, shrinker, priority); 994 if (ret == SHRINK_EMPTY) 995 ret = 0; 996 freed += ret; 997 /* 998 * Bail out if someone want to register a new shrinker to 999 * prevent the registration from being stalled for long periods 1000 * by parallel ongoing shrinking. 1001 */ 1002 if (rwsem_is_contended(&shrinker_rwsem)) { 1003 freed = freed ? : 1; 1004 break; 1005 } 1006 } 1007 1008 up_read(&shrinker_rwsem); 1009 out: 1010 cond_resched(); 1011 return freed; 1012 } 1013 1014 static void drop_slab_node(int nid) 1015 { 1016 unsigned long freed; 1017 int shift = 0; 1018 1019 do { 1020 struct mem_cgroup *memcg = NULL; 1021 1022 if (fatal_signal_pending(current)) 1023 return; 1024 1025 freed = 0; 1026 memcg = mem_cgroup_iter(NULL, NULL, NULL); 1027 do { 1028 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0); 1029 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL); 1030 } while ((freed >> shift++) > 1); 1031 } 1032 1033 void drop_slab(void) 1034 { 1035 int nid; 1036 1037 for_each_online_node(nid) 1038 drop_slab_node(nid); 1039 } 1040 1041 static inline int is_page_cache_freeable(struct folio *folio) 1042 { 1043 /* 1044 * A freeable page cache page is referenced only by the caller 1045 * that isolated the page, the page cache and optional buffer 1046 * heads at page->private. 1047 */ 1048 return folio_ref_count(folio) - folio_test_private(folio) == 1049 1 + folio_nr_pages(folio); 1050 } 1051 1052 /* 1053 * We detected a synchronous write error writing a folio out. Probably 1054 * -ENOSPC. We need to propagate that into the address_space for a subsequent 1055 * fsync(), msync() or close(). 1056 * 1057 * The tricky part is that after writepage we cannot touch the mapping: nothing 1058 * prevents it from being freed up. But we have a ref on the folio and once 1059 * that folio is locked, the mapping is pinned. 1060 * 1061 * We're allowed to run sleeping folio_lock() here because we know the caller has 1062 * __GFP_FS. 1063 */ 1064 static void handle_write_error(struct address_space *mapping, 1065 struct folio *folio, int error) 1066 { 1067 folio_lock(folio); 1068 if (folio_mapping(folio) == mapping) 1069 mapping_set_error(mapping, error); 1070 folio_unlock(folio); 1071 } 1072 1073 static bool skip_throttle_noprogress(pg_data_t *pgdat) 1074 { 1075 int reclaimable = 0, write_pending = 0; 1076 int i; 1077 1078 /* 1079 * If kswapd is disabled, reschedule if necessary but do not 1080 * throttle as the system is likely near OOM. 1081 */ 1082 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES) 1083 return true; 1084 1085 /* 1086 * If there are a lot of dirty/writeback pages then do not 1087 * throttle as throttling will occur when the pages cycle 1088 * towards the end of the LRU if still under writeback. 1089 */ 1090 for (i = 0; i < MAX_NR_ZONES; i++) { 1091 struct zone *zone = pgdat->node_zones + i; 1092 1093 if (!managed_zone(zone)) 1094 continue; 1095 1096 reclaimable += zone_reclaimable_pages(zone); 1097 write_pending += zone_page_state_snapshot(zone, 1098 NR_ZONE_WRITE_PENDING); 1099 } 1100 if (2 * write_pending <= reclaimable) 1101 return true; 1102 1103 return false; 1104 } 1105 1106 void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason) 1107 { 1108 wait_queue_head_t *wqh = &pgdat->reclaim_wait[reason]; 1109 long timeout, ret; 1110 DEFINE_WAIT(wait); 1111 1112 /* 1113 * Do not throttle IO workers, kthreads other than kswapd or 1114 * workqueues. They may be required for reclaim to make 1115 * forward progress (e.g. journalling workqueues or kthreads). 1116 */ 1117 if (!current_is_kswapd() && 1118 current->flags & (PF_IO_WORKER|PF_KTHREAD)) { 1119 cond_resched(); 1120 return; 1121 } 1122 1123 /* 1124 * These figures are pulled out of thin air. 1125 * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many 1126 * parallel reclaimers which is a short-lived event so the timeout is 1127 * short. Failing to make progress or waiting on writeback are 1128 * potentially long-lived events so use a longer timeout. This is shaky 1129 * logic as a failure to make progress could be due to anything from 1130 * writeback to a slow device to excessive references pages at the tail 1131 * of the inactive LRU. 1132 */ 1133 switch(reason) { 1134 case VMSCAN_THROTTLE_WRITEBACK: 1135 timeout = HZ/10; 1136 1137 if (atomic_inc_return(&pgdat->nr_writeback_throttled) == 1) { 1138 WRITE_ONCE(pgdat->nr_reclaim_start, 1139 node_page_state(pgdat, NR_THROTTLED_WRITTEN)); 1140 } 1141 1142 break; 1143 case VMSCAN_THROTTLE_CONGESTED: 1144 fallthrough; 1145 case VMSCAN_THROTTLE_NOPROGRESS: 1146 if (skip_throttle_noprogress(pgdat)) { 1147 cond_resched(); 1148 return; 1149 } 1150 1151 timeout = 1; 1152 1153 break; 1154 case VMSCAN_THROTTLE_ISOLATED: 1155 timeout = HZ/50; 1156 break; 1157 default: 1158 WARN_ON_ONCE(1); 1159 timeout = HZ; 1160 break; 1161 } 1162 1163 prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE); 1164 ret = schedule_timeout(timeout); 1165 finish_wait(wqh, &wait); 1166 1167 if (reason == VMSCAN_THROTTLE_WRITEBACK) 1168 atomic_dec(&pgdat->nr_writeback_throttled); 1169 1170 trace_mm_vmscan_throttled(pgdat->node_id, jiffies_to_usecs(timeout), 1171 jiffies_to_usecs(timeout - ret), 1172 reason); 1173 } 1174 1175 /* 1176 * Account for pages written if tasks are throttled waiting on dirty 1177 * pages to clean. If enough pages have been cleaned since throttling 1178 * started then wakeup the throttled tasks. 1179 */ 1180 void __acct_reclaim_writeback(pg_data_t *pgdat, struct folio *folio, 1181 int nr_throttled) 1182 { 1183 unsigned long nr_written; 1184 1185 node_stat_add_folio(folio, NR_THROTTLED_WRITTEN); 1186 1187 /* 1188 * This is an inaccurate read as the per-cpu deltas may not 1189 * be synchronised. However, given that the system is 1190 * writeback throttled, it is not worth taking the penalty 1191 * of getting an accurate count. At worst, the throttle 1192 * timeout guarantees forward progress. 1193 */ 1194 nr_written = node_page_state(pgdat, NR_THROTTLED_WRITTEN) - 1195 READ_ONCE(pgdat->nr_reclaim_start); 1196 1197 if (nr_written > SWAP_CLUSTER_MAX * nr_throttled) 1198 wake_up(&pgdat->reclaim_wait[VMSCAN_THROTTLE_WRITEBACK]); 1199 } 1200 1201 /* possible outcome of pageout() */ 1202 typedef enum { 1203 /* failed to write page out, page is locked */ 1204 PAGE_KEEP, 1205 /* move page to the active list, page is locked */ 1206 PAGE_ACTIVATE, 1207 /* page has been sent to the disk successfully, page is unlocked */ 1208 PAGE_SUCCESS, 1209 /* page is clean and locked */ 1210 PAGE_CLEAN, 1211 } pageout_t; 1212 1213 /* 1214 * pageout is called by shrink_page_list() for each dirty page. 1215 * Calls ->writepage(). 1216 */ 1217 static pageout_t pageout(struct folio *folio, struct address_space *mapping, 1218 struct swap_iocb **plug) 1219 { 1220 /* 1221 * If the folio is dirty, only perform writeback if that write 1222 * will be non-blocking. To prevent this allocation from being 1223 * stalled by pagecache activity. But note that there may be 1224 * stalls if we need to run get_block(). We could test 1225 * PagePrivate for that. 1226 * 1227 * If this process is currently in __generic_file_write_iter() against 1228 * this folio's queue, we can perform writeback even if that 1229 * will block. 1230 * 1231 * If the folio is swapcache, write it back even if that would 1232 * block, for some throttling. This happens by accident, because 1233 * swap_backing_dev_info is bust: it doesn't reflect the 1234 * congestion state of the swapdevs. Easy to fix, if needed. 1235 */ 1236 if (!is_page_cache_freeable(folio)) 1237 return PAGE_KEEP; 1238 if (!mapping) { 1239 /* 1240 * Some data journaling orphaned folios can have 1241 * folio->mapping == NULL while being dirty with clean buffers. 1242 */ 1243 if (folio_test_private(folio)) { 1244 if (try_to_free_buffers(folio)) { 1245 folio_clear_dirty(folio); 1246 pr_info("%s: orphaned folio\n", __func__); 1247 return PAGE_CLEAN; 1248 } 1249 } 1250 return PAGE_KEEP; 1251 } 1252 if (mapping->a_ops->writepage == NULL) 1253 return PAGE_ACTIVATE; 1254 1255 if (folio_clear_dirty_for_io(folio)) { 1256 int res; 1257 struct writeback_control wbc = { 1258 .sync_mode = WB_SYNC_NONE, 1259 .nr_to_write = SWAP_CLUSTER_MAX, 1260 .range_start = 0, 1261 .range_end = LLONG_MAX, 1262 .for_reclaim = 1, 1263 .swap_plug = plug, 1264 }; 1265 1266 folio_set_reclaim(folio); 1267 res = mapping->a_ops->writepage(&folio->page, &wbc); 1268 if (res < 0) 1269 handle_write_error(mapping, folio, res); 1270 if (res == AOP_WRITEPAGE_ACTIVATE) { 1271 folio_clear_reclaim(folio); 1272 return PAGE_ACTIVATE; 1273 } 1274 1275 if (!folio_test_writeback(folio)) { 1276 /* synchronous write or broken a_ops? */ 1277 folio_clear_reclaim(folio); 1278 } 1279 trace_mm_vmscan_write_folio(folio); 1280 node_stat_add_folio(folio, NR_VMSCAN_WRITE); 1281 return PAGE_SUCCESS; 1282 } 1283 1284 return PAGE_CLEAN; 1285 } 1286 1287 /* 1288 * Same as remove_mapping, but if the page is removed from the mapping, it 1289 * gets returned with a refcount of 0. 1290 */ 1291 static int __remove_mapping(struct address_space *mapping, struct folio *folio, 1292 bool reclaimed, struct mem_cgroup *target_memcg) 1293 { 1294 int refcount; 1295 void *shadow = NULL; 1296 1297 BUG_ON(!folio_test_locked(folio)); 1298 BUG_ON(mapping != folio_mapping(folio)); 1299 1300 if (!folio_test_swapcache(folio)) 1301 spin_lock(&mapping->host->i_lock); 1302 xa_lock_irq(&mapping->i_pages); 1303 /* 1304 * The non racy check for a busy page. 1305 * 1306 * Must be careful with the order of the tests. When someone has 1307 * a ref to the page, it may be possible that they dirty it then 1308 * drop the reference. So if PageDirty is tested before page_count 1309 * here, then the following race may occur: 1310 * 1311 * get_user_pages(&page); 1312 * [user mapping goes away] 1313 * write_to(page); 1314 * !PageDirty(page) [good] 1315 * SetPageDirty(page); 1316 * put_page(page); 1317 * !page_count(page) [good, discard it] 1318 * 1319 * [oops, our write_to data is lost] 1320 * 1321 * Reversing the order of the tests ensures such a situation cannot 1322 * escape unnoticed. The smp_rmb is needed to ensure the page->flags 1323 * load is not satisfied before that of page->_refcount. 1324 * 1325 * Note that if SetPageDirty is always performed via set_page_dirty, 1326 * and thus under the i_pages lock, then this ordering is not required. 1327 */ 1328 refcount = 1 + folio_nr_pages(folio); 1329 if (!folio_ref_freeze(folio, refcount)) 1330 goto cannot_free; 1331 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */ 1332 if (unlikely(folio_test_dirty(folio))) { 1333 folio_ref_unfreeze(folio, refcount); 1334 goto cannot_free; 1335 } 1336 1337 if (folio_test_swapcache(folio)) { 1338 swp_entry_t swap = folio_swap_entry(folio); 1339 1340 /* get a shadow entry before mem_cgroup_swapout() clears folio_memcg() */ 1341 if (reclaimed && !mapping_exiting(mapping)) 1342 shadow = workingset_eviction(folio, target_memcg); 1343 mem_cgroup_swapout(folio, swap); 1344 __delete_from_swap_cache(folio, swap, shadow); 1345 xa_unlock_irq(&mapping->i_pages); 1346 put_swap_page(&folio->page, swap); 1347 } else { 1348 void (*free_folio)(struct folio *); 1349 1350 free_folio = mapping->a_ops->free_folio; 1351 /* 1352 * Remember a shadow entry for reclaimed file cache in 1353 * order to detect refaults, thus thrashing, later on. 1354 * 1355 * But don't store shadows in an address space that is 1356 * already exiting. This is not just an optimization, 1357 * inode reclaim needs to empty out the radix tree or 1358 * the nodes are lost. Don't plant shadows behind its 1359 * back. 1360 * 1361 * We also don't store shadows for DAX mappings because the 1362 * only page cache pages found in these are zero pages 1363 * covering holes, and because we don't want to mix DAX 1364 * exceptional entries and shadow exceptional entries in the 1365 * same address_space. 1366 */ 1367 if (reclaimed && folio_is_file_lru(folio) && 1368 !mapping_exiting(mapping) && !dax_mapping(mapping)) 1369 shadow = workingset_eviction(folio, target_memcg); 1370 __filemap_remove_folio(folio, shadow); 1371 xa_unlock_irq(&mapping->i_pages); 1372 if (mapping_shrinkable(mapping)) 1373 inode_add_lru(mapping->host); 1374 spin_unlock(&mapping->host->i_lock); 1375 1376 if (free_folio) 1377 free_folio(folio); 1378 } 1379 1380 return 1; 1381 1382 cannot_free: 1383 xa_unlock_irq(&mapping->i_pages); 1384 if (!folio_test_swapcache(folio)) 1385 spin_unlock(&mapping->host->i_lock); 1386 return 0; 1387 } 1388 1389 /** 1390 * remove_mapping() - Attempt to remove a folio from its mapping. 1391 * @mapping: The address space. 1392 * @folio: The folio to remove. 1393 * 1394 * If the folio is dirty, under writeback or if someone else has a ref 1395 * on it, removal will fail. 1396 * Return: The number of pages removed from the mapping. 0 if the folio 1397 * could not be removed. 1398 * Context: The caller should have a single refcount on the folio and 1399 * hold its lock. 1400 */ 1401 long remove_mapping(struct address_space *mapping, struct folio *folio) 1402 { 1403 if (__remove_mapping(mapping, folio, false, NULL)) { 1404 /* 1405 * Unfreezing the refcount with 1 effectively 1406 * drops the pagecache ref for us without requiring another 1407 * atomic operation. 1408 */ 1409 folio_ref_unfreeze(folio, 1); 1410 return folio_nr_pages(folio); 1411 } 1412 return 0; 1413 } 1414 1415 /** 1416 * folio_putback_lru - Put previously isolated folio onto appropriate LRU list. 1417 * @folio: Folio to be returned to an LRU list. 1418 * 1419 * Add previously isolated @folio to appropriate LRU list. 1420 * The folio may still be unevictable for other reasons. 1421 * 1422 * Context: lru_lock must not be held, interrupts must be enabled. 1423 */ 1424 void folio_putback_lru(struct folio *folio) 1425 { 1426 folio_add_lru(folio); 1427 folio_put(folio); /* drop ref from isolate */ 1428 } 1429 1430 enum page_references { 1431 PAGEREF_RECLAIM, 1432 PAGEREF_RECLAIM_CLEAN, 1433 PAGEREF_KEEP, 1434 PAGEREF_ACTIVATE, 1435 }; 1436 1437 static enum page_references folio_check_references(struct folio *folio, 1438 struct scan_control *sc) 1439 { 1440 int referenced_ptes, referenced_folio; 1441 unsigned long vm_flags; 1442 1443 referenced_ptes = folio_referenced(folio, 1, sc->target_mem_cgroup, 1444 &vm_flags); 1445 referenced_folio = folio_test_clear_referenced(folio); 1446 1447 /* 1448 * The supposedly reclaimable folio was found to be in a VM_LOCKED vma. 1449 * Let the folio, now marked Mlocked, be moved to the unevictable list. 1450 */ 1451 if (vm_flags & VM_LOCKED) 1452 return PAGEREF_ACTIVATE; 1453 1454 /* rmap lock contention: rotate */ 1455 if (referenced_ptes == -1) 1456 return PAGEREF_KEEP; 1457 1458 if (referenced_ptes) { 1459 /* 1460 * All mapped folios start out with page table 1461 * references from the instantiating fault, so we need 1462 * to look twice if a mapped file/anon folio is used more 1463 * than once. 1464 * 1465 * Mark it and spare it for another trip around the 1466 * inactive list. Another page table reference will 1467 * lead to its activation. 1468 * 1469 * Note: the mark is set for activated folios as well 1470 * so that recently deactivated but used folios are 1471 * quickly recovered. 1472 */ 1473 folio_set_referenced(folio); 1474 1475 if (referenced_folio || referenced_ptes > 1) 1476 return PAGEREF_ACTIVATE; 1477 1478 /* 1479 * Activate file-backed executable folios after first usage. 1480 */ 1481 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio)) 1482 return PAGEREF_ACTIVATE; 1483 1484 return PAGEREF_KEEP; 1485 } 1486 1487 /* Reclaim if clean, defer dirty folios to writeback */ 1488 if (referenced_folio && folio_is_file_lru(folio)) 1489 return PAGEREF_RECLAIM_CLEAN; 1490 1491 return PAGEREF_RECLAIM; 1492 } 1493 1494 /* Check if a page is dirty or under writeback */ 1495 static void folio_check_dirty_writeback(struct folio *folio, 1496 bool *dirty, bool *writeback) 1497 { 1498 struct address_space *mapping; 1499 1500 /* 1501 * Anonymous pages are not handled by flushers and must be written 1502 * from reclaim context. Do not stall reclaim based on them. 1503 * MADV_FREE anonymous pages are put into inactive file list too. 1504 * They could be mistakenly treated as file lru. So further anon 1505 * test is needed. 1506 */ 1507 if (!folio_is_file_lru(folio) || 1508 (folio_test_anon(folio) && !folio_test_swapbacked(folio))) { 1509 *dirty = false; 1510 *writeback = false; 1511 return; 1512 } 1513 1514 /* By default assume that the folio flags are accurate */ 1515 *dirty = folio_test_dirty(folio); 1516 *writeback = folio_test_writeback(folio); 1517 1518 /* Verify dirty/writeback state if the filesystem supports it */ 1519 if (!folio_test_private(folio)) 1520 return; 1521 1522 mapping = folio_mapping(folio); 1523 if (mapping && mapping->a_ops->is_dirty_writeback) 1524 mapping->a_ops->is_dirty_writeback(folio, dirty, writeback); 1525 } 1526 1527 static struct page *alloc_demote_page(struct page *page, unsigned long node) 1528 { 1529 struct migration_target_control mtc = { 1530 /* 1531 * Allocate from 'node', or fail quickly and quietly. 1532 * When this happens, 'page' will likely just be discarded 1533 * instead of migrated. 1534 */ 1535 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) | 1536 __GFP_THISNODE | __GFP_NOWARN | 1537 __GFP_NOMEMALLOC | GFP_NOWAIT, 1538 .nid = node 1539 }; 1540 1541 return alloc_migration_target(page, (unsigned long)&mtc); 1542 } 1543 1544 /* 1545 * Take pages on @demote_list and attempt to demote them to 1546 * another node. Pages which are not demoted are left on 1547 * @demote_pages. 1548 */ 1549 static unsigned int demote_page_list(struct list_head *demote_pages, 1550 struct pglist_data *pgdat) 1551 { 1552 int target_nid = next_demotion_node(pgdat->node_id); 1553 unsigned int nr_succeeded; 1554 1555 if (list_empty(demote_pages)) 1556 return 0; 1557 1558 if (target_nid == NUMA_NO_NODE) 1559 return 0; 1560 1561 /* Demotion ignores all cpuset and mempolicy settings */ 1562 migrate_pages(demote_pages, alloc_demote_page, NULL, 1563 target_nid, MIGRATE_ASYNC, MR_DEMOTION, 1564 &nr_succeeded); 1565 1566 if (current_is_kswapd()) 1567 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded); 1568 else 1569 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded); 1570 1571 return nr_succeeded; 1572 } 1573 1574 static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask) 1575 { 1576 if (gfp_mask & __GFP_FS) 1577 return true; 1578 if (!folio_test_swapcache(folio) || !(gfp_mask & __GFP_IO)) 1579 return false; 1580 /* 1581 * We can "enter_fs" for swap-cache with only __GFP_IO 1582 * providing this isn't SWP_FS_OPS. 1583 * ->flags can be updated non-atomicially (scan_swap_map_slots), 1584 * but that will never affect SWP_FS_OPS, so the data_race 1585 * is safe. 1586 */ 1587 return !data_race(folio_swap_flags(folio) & SWP_FS_OPS); 1588 } 1589 1590 /* 1591 * shrink_page_list() returns the number of reclaimed pages 1592 */ 1593 static unsigned int shrink_page_list(struct list_head *page_list, 1594 struct pglist_data *pgdat, 1595 struct scan_control *sc, 1596 struct reclaim_stat *stat, 1597 bool ignore_references) 1598 { 1599 LIST_HEAD(ret_pages); 1600 LIST_HEAD(free_pages); 1601 LIST_HEAD(demote_pages); 1602 unsigned int nr_reclaimed = 0; 1603 unsigned int pgactivate = 0; 1604 bool do_demote_pass; 1605 struct swap_iocb *plug = NULL; 1606 1607 memset(stat, 0, sizeof(*stat)); 1608 cond_resched(); 1609 do_demote_pass = can_demote(pgdat->node_id, sc); 1610 1611 retry: 1612 while (!list_empty(page_list)) { 1613 struct address_space *mapping; 1614 struct folio *folio; 1615 enum page_references references = PAGEREF_RECLAIM; 1616 bool dirty, writeback; 1617 unsigned int nr_pages; 1618 1619 cond_resched(); 1620 1621 folio = lru_to_folio(page_list); 1622 list_del(&folio->lru); 1623 1624 if (!folio_trylock(folio)) 1625 goto keep; 1626 1627 VM_BUG_ON_FOLIO(folio_test_active(folio), folio); 1628 1629 nr_pages = folio_nr_pages(folio); 1630 1631 /* Account the number of base pages */ 1632 sc->nr_scanned += nr_pages; 1633 1634 if (unlikely(!folio_evictable(folio))) 1635 goto activate_locked; 1636 1637 if (!sc->may_unmap && folio_mapped(folio)) 1638 goto keep_locked; 1639 1640 /* folio_update_gen() tried to promote this page? */ 1641 if (lru_gen_enabled() && !ignore_references && 1642 folio_mapped(folio) && folio_test_referenced(folio)) 1643 goto keep_locked; 1644 1645 /* 1646 * The number of dirty pages determines if a node is marked 1647 * reclaim_congested. kswapd will stall and start writing 1648 * folios if the tail of the LRU is all dirty unqueued folios. 1649 */ 1650 folio_check_dirty_writeback(folio, &dirty, &writeback); 1651 if (dirty || writeback) 1652 stat->nr_dirty += nr_pages; 1653 1654 if (dirty && !writeback) 1655 stat->nr_unqueued_dirty += nr_pages; 1656 1657 /* 1658 * Treat this folio as congested if folios are cycling 1659 * through the LRU so quickly that the folios marked 1660 * for immediate reclaim are making it to the end of 1661 * the LRU a second time. 1662 */ 1663 if (writeback && folio_test_reclaim(folio)) 1664 stat->nr_congested += nr_pages; 1665 1666 /* 1667 * If a folio at the tail of the LRU is under writeback, there 1668 * are three cases to consider. 1669 * 1670 * 1) If reclaim is encountering an excessive number 1671 * of folios under writeback and this folio has both 1672 * the writeback and reclaim flags set, then it 1673 * indicates that folios are being queued for I/O but 1674 * are being recycled through the LRU before the I/O 1675 * can complete. Waiting on the folio itself risks an 1676 * indefinite stall if it is impossible to writeback 1677 * the folio due to I/O error or disconnected storage 1678 * so instead note that the LRU is being scanned too 1679 * quickly and the caller can stall after the folio 1680 * list has been processed. 1681 * 1682 * 2) Global or new memcg reclaim encounters a folio that is 1683 * not marked for immediate reclaim, or the caller does not 1684 * have __GFP_FS (or __GFP_IO if it's simply going to swap, 1685 * not to fs). In this case mark the folio for immediate 1686 * reclaim and continue scanning. 1687 * 1688 * Require may_enter_fs() because we would wait on fs, which 1689 * may not have submitted I/O yet. And the loop driver might 1690 * enter reclaim, and deadlock if it waits on a folio for 1691 * which it is needed to do the write (loop masks off 1692 * __GFP_IO|__GFP_FS for this reason); but more thought 1693 * would probably show more reasons. 1694 * 1695 * 3) Legacy memcg encounters a folio that already has the 1696 * reclaim flag set. memcg does not have any dirty folio 1697 * throttling so we could easily OOM just because too many 1698 * folios are in writeback and there is nothing else to 1699 * reclaim. Wait for the writeback to complete. 1700 * 1701 * In cases 1) and 2) we activate the folios to get them out of 1702 * the way while we continue scanning for clean folios on the 1703 * inactive list and refilling from the active list. The 1704 * observation here is that waiting for disk writes is more 1705 * expensive than potentially causing reloads down the line. 1706 * Since they're marked for immediate reclaim, they won't put 1707 * memory pressure on the cache working set any longer than it 1708 * takes to write them to disk. 1709 */ 1710 if (folio_test_writeback(folio)) { 1711 /* Case 1 above */ 1712 if (current_is_kswapd() && 1713 folio_test_reclaim(folio) && 1714 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) { 1715 stat->nr_immediate += nr_pages; 1716 goto activate_locked; 1717 1718 /* Case 2 above */ 1719 } else if (writeback_throttling_sane(sc) || 1720 !folio_test_reclaim(folio) || 1721 !may_enter_fs(folio, sc->gfp_mask)) { 1722 /* 1723 * This is slightly racy - 1724 * folio_end_writeback() might have 1725 * just cleared the reclaim flag, then 1726 * setting the reclaim flag here ends up 1727 * interpreted as the readahead flag - but 1728 * that does not matter enough to care. 1729 * What we do want is for this folio to 1730 * have the reclaim flag set next time 1731 * memcg reclaim reaches the tests above, 1732 * so it will then wait for writeback to 1733 * avoid OOM; and it's also appropriate 1734 * in global reclaim. 1735 */ 1736 folio_set_reclaim(folio); 1737 stat->nr_writeback += nr_pages; 1738 goto activate_locked; 1739 1740 /* Case 3 above */ 1741 } else { 1742 folio_unlock(folio); 1743 folio_wait_writeback(folio); 1744 /* then go back and try same folio again */ 1745 list_add_tail(&folio->lru, page_list); 1746 continue; 1747 } 1748 } 1749 1750 if (!ignore_references) 1751 references = folio_check_references(folio, sc); 1752 1753 switch (references) { 1754 case PAGEREF_ACTIVATE: 1755 goto activate_locked; 1756 case PAGEREF_KEEP: 1757 stat->nr_ref_keep += nr_pages; 1758 goto keep_locked; 1759 case PAGEREF_RECLAIM: 1760 case PAGEREF_RECLAIM_CLEAN: 1761 ; /* try to reclaim the folio below */ 1762 } 1763 1764 /* 1765 * Before reclaiming the folio, try to relocate 1766 * its contents to another node. 1767 */ 1768 if (do_demote_pass && 1769 (thp_migration_supported() || !folio_test_large(folio))) { 1770 list_add(&folio->lru, &demote_pages); 1771 folio_unlock(folio); 1772 continue; 1773 } 1774 1775 /* 1776 * Anonymous process memory has backing store? 1777 * Try to allocate it some swap space here. 1778 * Lazyfree folio could be freed directly 1779 */ 1780 if (folio_test_anon(folio) && folio_test_swapbacked(folio)) { 1781 if (!folio_test_swapcache(folio)) { 1782 if (!(sc->gfp_mask & __GFP_IO)) 1783 goto keep_locked; 1784 if (folio_maybe_dma_pinned(folio)) 1785 goto keep_locked; 1786 if (folio_test_large(folio)) { 1787 /* cannot split folio, skip it */ 1788 if (!can_split_folio(folio, NULL)) 1789 goto activate_locked; 1790 /* 1791 * Split folios without a PMD map right 1792 * away. Chances are some or all of the 1793 * tail pages can be freed without IO. 1794 */ 1795 if (!folio_entire_mapcount(folio) && 1796 split_folio_to_list(folio, 1797 page_list)) 1798 goto activate_locked; 1799 } 1800 if (!add_to_swap(folio)) { 1801 if (!folio_test_large(folio)) 1802 goto activate_locked_split; 1803 /* Fallback to swap normal pages */ 1804 if (split_folio_to_list(folio, 1805 page_list)) 1806 goto activate_locked; 1807 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 1808 count_vm_event(THP_SWPOUT_FALLBACK); 1809 #endif 1810 if (!add_to_swap(folio)) 1811 goto activate_locked_split; 1812 } 1813 } 1814 } else if (folio_test_swapbacked(folio) && 1815 folio_test_large(folio)) { 1816 /* Split shmem folio */ 1817 if (split_folio_to_list(folio, page_list)) 1818 goto keep_locked; 1819 } 1820 1821 /* 1822 * If the folio was split above, the tail pages will make 1823 * their own pass through this function and be accounted 1824 * then. 1825 */ 1826 if ((nr_pages > 1) && !folio_test_large(folio)) { 1827 sc->nr_scanned -= (nr_pages - 1); 1828 nr_pages = 1; 1829 } 1830 1831 /* 1832 * The folio is mapped into the page tables of one or more 1833 * processes. Try to unmap it here. 1834 */ 1835 if (folio_mapped(folio)) { 1836 enum ttu_flags flags = TTU_BATCH_FLUSH; 1837 bool was_swapbacked = folio_test_swapbacked(folio); 1838 1839 if (folio_test_pmd_mappable(folio)) 1840 flags |= TTU_SPLIT_HUGE_PMD; 1841 1842 try_to_unmap(folio, flags); 1843 if (folio_mapped(folio)) { 1844 stat->nr_unmap_fail += nr_pages; 1845 if (!was_swapbacked && 1846 folio_test_swapbacked(folio)) 1847 stat->nr_lazyfree_fail += nr_pages; 1848 goto activate_locked; 1849 } 1850 } 1851 1852 mapping = folio_mapping(folio); 1853 if (folio_test_dirty(folio)) { 1854 /* 1855 * Only kswapd can writeback filesystem folios 1856 * to avoid risk of stack overflow. But avoid 1857 * injecting inefficient single-folio I/O into 1858 * flusher writeback as much as possible: only 1859 * write folios when we've encountered many 1860 * dirty folios, and when we've already scanned 1861 * the rest of the LRU for clean folios and see 1862 * the same dirty folios again (with the reclaim 1863 * flag set). 1864 */ 1865 if (folio_is_file_lru(folio) && 1866 (!current_is_kswapd() || 1867 !folio_test_reclaim(folio) || 1868 !test_bit(PGDAT_DIRTY, &pgdat->flags))) { 1869 /* 1870 * Immediately reclaim when written back. 1871 * Similar in principle to deactivate_page() 1872 * except we already have the folio isolated 1873 * and know it's dirty 1874 */ 1875 node_stat_mod_folio(folio, NR_VMSCAN_IMMEDIATE, 1876 nr_pages); 1877 folio_set_reclaim(folio); 1878 1879 goto activate_locked; 1880 } 1881 1882 if (references == PAGEREF_RECLAIM_CLEAN) 1883 goto keep_locked; 1884 if (!may_enter_fs(folio, sc->gfp_mask)) 1885 goto keep_locked; 1886 if (!sc->may_writepage) 1887 goto keep_locked; 1888 1889 /* 1890 * Folio is dirty. Flush the TLB if a writable entry 1891 * potentially exists to avoid CPU writes after I/O 1892 * starts and then write it out here. 1893 */ 1894 try_to_unmap_flush_dirty(); 1895 switch (pageout(folio, mapping, &plug)) { 1896 case PAGE_KEEP: 1897 goto keep_locked; 1898 case PAGE_ACTIVATE: 1899 goto activate_locked; 1900 case PAGE_SUCCESS: 1901 stat->nr_pageout += nr_pages; 1902 1903 if (folio_test_writeback(folio)) 1904 goto keep; 1905 if (folio_test_dirty(folio)) 1906 goto keep; 1907 1908 /* 1909 * A synchronous write - probably a ramdisk. Go 1910 * ahead and try to reclaim the folio. 1911 */ 1912 if (!folio_trylock(folio)) 1913 goto keep; 1914 if (folio_test_dirty(folio) || 1915 folio_test_writeback(folio)) 1916 goto keep_locked; 1917 mapping = folio_mapping(folio); 1918 fallthrough; 1919 case PAGE_CLEAN: 1920 ; /* try to free the folio below */ 1921 } 1922 } 1923 1924 /* 1925 * If the folio has buffers, try to free the buffer 1926 * mappings associated with this folio. If we succeed 1927 * we try to free the folio as well. 1928 * 1929 * We do this even if the folio is dirty. 1930 * filemap_release_folio() does not perform I/O, but it 1931 * is possible for a folio to have the dirty flag set, 1932 * but it is actually clean (all its buffers are clean). 1933 * This happens if the buffers were written out directly, 1934 * with submit_bh(). ext3 will do this, as well as 1935 * the blockdev mapping. filemap_release_folio() will 1936 * discover that cleanness and will drop the buffers 1937 * and mark the folio clean - it can be freed. 1938 * 1939 * Rarely, folios can have buffers and no ->mapping. 1940 * These are the folios which were not successfully 1941 * invalidated in truncate_cleanup_folio(). We try to 1942 * drop those buffers here and if that worked, and the 1943 * folio is no longer mapped into process address space 1944 * (refcount == 1) it can be freed. Otherwise, leave 1945 * the folio on the LRU so it is swappable. 1946 */ 1947 if (folio_has_private(folio)) { 1948 if (!filemap_release_folio(folio, sc->gfp_mask)) 1949 goto activate_locked; 1950 if (!mapping && folio_ref_count(folio) == 1) { 1951 folio_unlock(folio); 1952 if (folio_put_testzero(folio)) 1953 goto free_it; 1954 else { 1955 /* 1956 * rare race with speculative reference. 1957 * the speculative reference will free 1958 * this folio shortly, so we may 1959 * increment nr_reclaimed here (and 1960 * leave it off the LRU). 1961 */ 1962 nr_reclaimed += nr_pages; 1963 continue; 1964 } 1965 } 1966 } 1967 1968 if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) { 1969 /* follow __remove_mapping for reference */ 1970 if (!folio_ref_freeze(folio, 1)) 1971 goto keep_locked; 1972 /* 1973 * The folio has only one reference left, which is 1974 * from the isolation. After the caller puts the 1975 * folio back on the lru and drops the reference, the 1976 * folio will be freed anyway. It doesn't matter 1977 * which lru it goes on. So we don't bother checking 1978 * the dirty flag here. 1979 */ 1980 count_vm_events(PGLAZYFREED, nr_pages); 1981 count_memcg_folio_events(folio, PGLAZYFREED, nr_pages); 1982 } else if (!mapping || !__remove_mapping(mapping, folio, true, 1983 sc->target_mem_cgroup)) 1984 goto keep_locked; 1985 1986 folio_unlock(folio); 1987 free_it: 1988 /* 1989 * Folio may get swapped out as a whole, need to account 1990 * all pages in it. 1991 */ 1992 nr_reclaimed += nr_pages; 1993 1994 /* 1995 * Is there need to periodically free_page_list? It would 1996 * appear not as the counts should be low 1997 */ 1998 if (unlikely(folio_test_large(folio))) 1999 destroy_large_folio(folio); 2000 else 2001 list_add(&folio->lru, &free_pages); 2002 continue; 2003 2004 activate_locked_split: 2005 /* 2006 * The tail pages that are failed to add into swap cache 2007 * reach here. Fixup nr_scanned and nr_pages. 2008 */ 2009 if (nr_pages > 1) { 2010 sc->nr_scanned -= (nr_pages - 1); 2011 nr_pages = 1; 2012 } 2013 activate_locked: 2014 /* Not a candidate for swapping, so reclaim swap space. */ 2015 if (folio_test_swapcache(folio) && 2016 (mem_cgroup_swap_full(&folio->page) || 2017 folio_test_mlocked(folio))) 2018 try_to_free_swap(&folio->page); 2019 VM_BUG_ON_FOLIO(folio_test_active(folio), folio); 2020 if (!folio_test_mlocked(folio)) { 2021 int type = folio_is_file_lru(folio); 2022 folio_set_active(folio); 2023 stat->nr_activate[type] += nr_pages; 2024 count_memcg_folio_events(folio, PGACTIVATE, nr_pages); 2025 } 2026 keep_locked: 2027 folio_unlock(folio); 2028 keep: 2029 list_add(&folio->lru, &ret_pages); 2030 VM_BUG_ON_FOLIO(folio_test_lru(folio) || 2031 folio_test_unevictable(folio), folio); 2032 } 2033 /* 'page_list' is always empty here */ 2034 2035 /* Migrate folios selected for demotion */ 2036 nr_reclaimed += demote_page_list(&demote_pages, pgdat); 2037 /* Folios that could not be demoted are still in @demote_pages */ 2038 if (!list_empty(&demote_pages)) { 2039 /* Folios which weren't demoted go back on @page_list for retry: */ 2040 list_splice_init(&demote_pages, page_list); 2041 do_demote_pass = false; 2042 goto retry; 2043 } 2044 2045 pgactivate = stat->nr_activate[0] + stat->nr_activate[1]; 2046 2047 mem_cgroup_uncharge_list(&free_pages); 2048 try_to_unmap_flush(); 2049 free_unref_page_list(&free_pages); 2050 2051 list_splice(&ret_pages, page_list); 2052 count_vm_events(PGACTIVATE, pgactivate); 2053 2054 if (plug) 2055 swap_write_unplug(plug); 2056 return nr_reclaimed; 2057 } 2058 2059 unsigned int reclaim_clean_pages_from_list(struct zone *zone, 2060 struct list_head *folio_list) 2061 { 2062 struct scan_control sc = { 2063 .gfp_mask = GFP_KERNEL, 2064 .may_unmap = 1, 2065 }; 2066 struct reclaim_stat stat; 2067 unsigned int nr_reclaimed; 2068 struct folio *folio, *next; 2069 LIST_HEAD(clean_folios); 2070 unsigned int noreclaim_flag; 2071 2072 list_for_each_entry_safe(folio, next, folio_list, lru) { 2073 if (!folio_test_hugetlb(folio) && folio_is_file_lru(folio) && 2074 !folio_test_dirty(folio) && !__folio_test_movable(folio) && 2075 !folio_test_unevictable(folio)) { 2076 folio_clear_active(folio); 2077 list_move(&folio->lru, &clean_folios); 2078 } 2079 } 2080 2081 /* 2082 * We should be safe here since we are only dealing with file pages and 2083 * we are not kswapd and therefore cannot write dirty file pages. But 2084 * call memalloc_noreclaim_save() anyway, just in case these conditions 2085 * change in the future. 2086 */ 2087 noreclaim_flag = memalloc_noreclaim_save(); 2088 nr_reclaimed = shrink_page_list(&clean_folios, zone->zone_pgdat, &sc, 2089 &stat, true); 2090 memalloc_noreclaim_restore(noreclaim_flag); 2091 2092 list_splice(&clean_folios, folio_list); 2093 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, 2094 -(long)nr_reclaimed); 2095 /* 2096 * Since lazyfree pages are isolated from file LRU from the beginning, 2097 * they will rotate back to anonymous LRU in the end if it failed to 2098 * discard so isolated count will be mismatched. 2099 * Compensate the isolated count for both LRU lists. 2100 */ 2101 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON, 2102 stat.nr_lazyfree_fail); 2103 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, 2104 -(long)stat.nr_lazyfree_fail); 2105 return nr_reclaimed; 2106 } 2107 2108 /* 2109 * Update LRU sizes after isolating pages. The LRU size updates must 2110 * be complete before mem_cgroup_update_lru_size due to a sanity check. 2111 */ 2112 static __always_inline void update_lru_sizes(struct lruvec *lruvec, 2113 enum lru_list lru, unsigned long *nr_zone_taken) 2114 { 2115 int zid; 2116 2117 for (zid = 0; zid < MAX_NR_ZONES; zid++) { 2118 if (!nr_zone_taken[zid]) 2119 continue; 2120 2121 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]); 2122 } 2123 2124 } 2125 2126 /* 2127 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times. 2128 * 2129 * lruvec->lru_lock is heavily contended. Some of the functions that 2130 * shrink the lists perform better by taking out a batch of pages 2131 * and working on them outside the LRU lock. 2132 * 2133 * For pagecache intensive workloads, this function is the hottest 2134 * spot in the kernel (apart from copy_*_user functions). 2135 * 2136 * Lru_lock must be held before calling this function. 2137 * 2138 * @nr_to_scan: The number of eligible pages to look through on the list. 2139 * @lruvec: The LRU vector to pull pages from. 2140 * @dst: The temp list to put pages on to. 2141 * @nr_scanned: The number of pages that were scanned. 2142 * @sc: The scan_control struct for this reclaim session 2143 * @lru: LRU list id for isolating 2144 * 2145 * returns how many pages were moved onto *@dst. 2146 */ 2147 static unsigned long isolate_lru_pages(unsigned long nr_to_scan, 2148 struct lruvec *lruvec, struct list_head *dst, 2149 unsigned long *nr_scanned, struct scan_control *sc, 2150 enum lru_list lru) 2151 { 2152 struct list_head *src = &lruvec->lists[lru]; 2153 unsigned long nr_taken = 0; 2154 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 }; 2155 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, }; 2156 unsigned long skipped = 0; 2157 unsigned long scan, total_scan, nr_pages; 2158 LIST_HEAD(folios_skipped); 2159 2160 total_scan = 0; 2161 scan = 0; 2162 while (scan < nr_to_scan && !list_empty(src)) { 2163 struct list_head *move_to = src; 2164 struct folio *folio; 2165 2166 folio = lru_to_folio(src); 2167 prefetchw_prev_lru_folio(folio, src, flags); 2168 2169 nr_pages = folio_nr_pages(folio); 2170 total_scan += nr_pages; 2171 2172 if (folio_zonenum(folio) > sc->reclaim_idx) { 2173 nr_skipped[folio_zonenum(folio)] += nr_pages; 2174 move_to = &folios_skipped; 2175 goto move; 2176 } 2177 2178 /* 2179 * Do not count skipped folios because that makes the function 2180 * return with no isolated folios if the LRU mostly contains 2181 * ineligible folios. This causes the VM to not reclaim any 2182 * folios, triggering a premature OOM. 2183 * Account all pages in a folio. 2184 */ 2185 scan += nr_pages; 2186 2187 if (!folio_test_lru(folio)) 2188 goto move; 2189 if (!sc->may_unmap && folio_mapped(folio)) 2190 goto move; 2191 2192 /* 2193 * Be careful not to clear the lru flag until after we're 2194 * sure the folio is not being freed elsewhere -- the 2195 * folio release code relies on it. 2196 */ 2197 if (unlikely(!folio_try_get(folio))) 2198 goto move; 2199 2200 if (!folio_test_clear_lru(folio)) { 2201 /* Another thread is already isolating this folio */ 2202 folio_put(folio); 2203 goto move; 2204 } 2205 2206 nr_taken += nr_pages; 2207 nr_zone_taken[folio_zonenum(folio)] += nr_pages; 2208 move_to = dst; 2209 move: 2210 list_move(&folio->lru, move_to); 2211 } 2212 2213 /* 2214 * Splice any skipped folios to the start of the LRU list. Note that 2215 * this disrupts the LRU order when reclaiming for lower zones but 2216 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX 2217 * scanning would soon rescan the same folios to skip and waste lots 2218 * of cpu cycles. 2219 */ 2220 if (!list_empty(&folios_skipped)) { 2221 int zid; 2222 2223 list_splice(&folios_skipped, src); 2224 for (zid = 0; zid < MAX_NR_ZONES; zid++) { 2225 if (!nr_skipped[zid]) 2226 continue; 2227 2228 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]); 2229 skipped += nr_skipped[zid]; 2230 } 2231 } 2232 *nr_scanned = total_scan; 2233 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan, 2234 total_scan, skipped, nr_taken, 2235 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru); 2236 update_lru_sizes(lruvec, lru, nr_zone_taken); 2237 return nr_taken; 2238 } 2239 2240 /** 2241 * folio_isolate_lru() - Try to isolate a folio from its LRU list. 2242 * @folio: Folio to isolate from its LRU list. 2243 * 2244 * Isolate a @folio from an LRU list and adjust the vmstat statistic 2245 * corresponding to whatever LRU list the folio was on. 2246 * 2247 * The folio will have its LRU flag cleared. If it was found on the 2248 * active list, it will have the Active flag set. If it was found on the 2249 * unevictable list, it will have the Unevictable flag set. These flags 2250 * may need to be cleared by the caller before letting the page go. 2251 * 2252 * Context: 2253 * 2254 * (1) Must be called with an elevated refcount on the page. This is a 2255 * fundamental difference from isolate_lru_pages() (which is called 2256 * without a stable reference). 2257 * (2) The lru_lock must not be held. 2258 * (3) Interrupts must be enabled. 2259 * 2260 * Return: 0 if the folio was removed from an LRU list. 2261 * -EBUSY if the folio was not on an LRU list. 2262 */ 2263 int folio_isolate_lru(struct folio *folio) 2264 { 2265 int ret = -EBUSY; 2266 2267 VM_BUG_ON_FOLIO(!folio_ref_count(folio), folio); 2268 2269 if (folio_test_clear_lru(folio)) { 2270 struct lruvec *lruvec; 2271 2272 folio_get(folio); 2273 lruvec = folio_lruvec_lock_irq(folio); 2274 lruvec_del_folio(lruvec, folio); 2275 unlock_page_lruvec_irq(lruvec); 2276 ret = 0; 2277 } 2278 2279 return ret; 2280 } 2281 2282 /* 2283 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and 2284 * then get rescheduled. When there are massive number of tasks doing page 2285 * allocation, such sleeping direct reclaimers may keep piling up on each CPU, 2286 * the LRU list will go small and be scanned faster than necessary, leading to 2287 * unnecessary swapping, thrashing and OOM. 2288 */ 2289 static int too_many_isolated(struct pglist_data *pgdat, int file, 2290 struct scan_control *sc) 2291 { 2292 unsigned long inactive, isolated; 2293 bool too_many; 2294 2295 if (current_is_kswapd()) 2296 return 0; 2297 2298 if (!writeback_throttling_sane(sc)) 2299 return 0; 2300 2301 if (file) { 2302 inactive = node_page_state(pgdat, NR_INACTIVE_FILE); 2303 isolated = node_page_state(pgdat, NR_ISOLATED_FILE); 2304 } else { 2305 inactive = node_page_state(pgdat, NR_INACTIVE_ANON); 2306 isolated = node_page_state(pgdat, NR_ISOLATED_ANON); 2307 } 2308 2309 /* 2310 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they 2311 * won't get blocked by normal direct-reclaimers, forming a circular 2312 * deadlock. 2313 */ 2314 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS)) 2315 inactive >>= 3; 2316 2317 too_many = isolated > inactive; 2318 2319 /* Wake up tasks throttled due to too_many_isolated. */ 2320 if (!too_many) 2321 wake_throttle_isolated(pgdat); 2322 2323 return too_many; 2324 } 2325 2326 /* 2327 * move_pages_to_lru() moves folios from private @list to appropriate LRU list. 2328 * On return, @list is reused as a list of folios to be freed by the caller. 2329 * 2330 * Returns the number of pages moved to the given lruvec. 2331 */ 2332 static unsigned int move_pages_to_lru(struct lruvec *lruvec, 2333 struct list_head *list) 2334 { 2335 int nr_pages, nr_moved = 0; 2336 LIST_HEAD(folios_to_free); 2337 2338 while (!list_empty(list)) { 2339 struct folio *folio = lru_to_folio(list); 2340 2341 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio); 2342 list_del(&folio->lru); 2343 if (unlikely(!folio_evictable(folio))) { 2344 spin_unlock_irq(&lruvec->lru_lock); 2345 folio_putback_lru(folio); 2346 spin_lock_irq(&lruvec->lru_lock); 2347 continue; 2348 } 2349 2350 /* 2351 * The folio_set_lru needs to be kept here for list integrity. 2352 * Otherwise: 2353 * #0 move_pages_to_lru #1 release_pages 2354 * if (!folio_put_testzero()) 2355 * if (folio_put_testzero()) 2356 * !lru //skip lru_lock 2357 * folio_set_lru() 2358 * list_add(&folio->lru,) 2359 * list_add(&folio->lru,) 2360 */ 2361 folio_set_lru(folio); 2362 2363 if (unlikely(folio_put_testzero(folio))) { 2364 __folio_clear_lru_flags(folio); 2365 2366 if (unlikely(folio_test_large(folio))) { 2367 spin_unlock_irq(&lruvec->lru_lock); 2368 destroy_large_folio(folio); 2369 spin_lock_irq(&lruvec->lru_lock); 2370 } else 2371 list_add(&folio->lru, &folios_to_free); 2372 2373 continue; 2374 } 2375 2376 /* 2377 * All pages were isolated from the same lruvec (and isolation 2378 * inhibits memcg migration). 2379 */ 2380 VM_BUG_ON_FOLIO(!folio_matches_lruvec(folio, lruvec), folio); 2381 lruvec_add_folio(lruvec, folio); 2382 nr_pages = folio_nr_pages(folio); 2383 nr_moved += nr_pages; 2384 if (folio_test_active(folio)) 2385 workingset_age_nonresident(lruvec, nr_pages); 2386 } 2387 2388 /* 2389 * To save our caller's stack, now use input list for pages to free. 2390 */ 2391 list_splice(&folios_to_free, list); 2392 2393 return nr_moved; 2394 } 2395 2396 /* 2397 * If a kernel thread (such as nfsd for loop-back mounts) services a backing 2398 * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case 2399 * we should not throttle. Otherwise it is safe to do so. 2400 */ 2401 static int current_may_throttle(void) 2402 { 2403 return !(current->flags & PF_LOCAL_THROTTLE); 2404 } 2405 2406 /* 2407 * shrink_inactive_list() is a helper for shrink_node(). It returns the number 2408 * of reclaimed pages 2409 */ 2410 static unsigned long 2411 shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec, 2412 struct scan_control *sc, enum lru_list lru) 2413 { 2414 LIST_HEAD(page_list); 2415 unsigned long nr_scanned; 2416 unsigned int nr_reclaimed = 0; 2417 unsigned long nr_taken; 2418 struct reclaim_stat stat; 2419 bool file = is_file_lru(lru); 2420 enum vm_event_item item; 2421 struct pglist_data *pgdat = lruvec_pgdat(lruvec); 2422 bool stalled = false; 2423 2424 while (unlikely(too_many_isolated(pgdat, file, sc))) { 2425 if (stalled) 2426 return 0; 2427 2428 /* wait a bit for the reclaimer. */ 2429 stalled = true; 2430 reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED); 2431 2432 /* We are about to die and free our memory. Return now. */ 2433 if (fatal_signal_pending(current)) 2434 return SWAP_CLUSTER_MAX; 2435 } 2436 2437 lru_add_drain(); 2438 2439 spin_lock_irq(&lruvec->lru_lock); 2440 2441 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list, 2442 &nr_scanned, sc, lru); 2443 2444 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken); 2445 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT; 2446 if (!cgroup_reclaim(sc)) 2447 __count_vm_events(item, nr_scanned); 2448 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned); 2449 __count_vm_events(PGSCAN_ANON + file, nr_scanned); 2450 2451 spin_unlock_irq(&lruvec->lru_lock); 2452 2453 if (nr_taken == 0) 2454 return 0; 2455 2456 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false); 2457 2458 spin_lock_irq(&lruvec->lru_lock); 2459 move_pages_to_lru(lruvec, &page_list); 2460 2461 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken); 2462 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT; 2463 if (!cgroup_reclaim(sc)) 2464 __count_vm_events(item, nr_reclaimed); 2465 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed); 2466 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed); 2467 spin_unlock_irq(&lruvec->lru_lock); 2468 2469 lru_note_cost(lruvec, file, stat.nr_pageout); 2470 mem_cgroup_uncharge_list(&page_list); 2471 free_unref_page_list(&page_list); 2472 2473 /* 2474 * If dirty pages are scanned that are not queued for IO, it 2475 * implies that flushers are not doing their job. This can 2476 * happen when memory pressure pushes dirty pages to the end of 2477 * the LRU before the dirty limits are breached and the dirty 2478 * data has expired. It can also happen when the proportion of 2479 * dirty pages grows not through writes but through memory 2480 * pressure reclaiming all the clean cache. And in some cases, 2481 * the flushers simply cannot keep up with the allocation 2482 * rate. Nudge the flusher threads in case they are asleep. 2483 */ 2484 if (stat.nr_unqueued_dirty == nr_taken) 2485 wakeup_flusher_threads(WB_REASON_VMSCAN); 2486 2487 sc->nr.dirty += stat.nr_dirty; 2488 sc->nr.congested += stat.nr_congested; 2489 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty; 2490 sc->nr.writeback += stat.nr_writeback; 2491 sc->nr.immediate += stat.nr_immediate; 2492 sc->nr.taken += nr_taken; 2493 if (file) 2494 sc->nr.file_taken += nr_taken; 2495 2496 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id, 2497 nr_scanned, nr_reclaimed, &stat, sc->priority, file); 2498 return nr_reclaimed; 2499 } 2500 2501 /* 2502 * shrink_active_list() moves folios from the active LRU to the inactive LRU. 2503 * 2504 * We move them the other way if the folio is referenced by one or more 2505 * processes. 2506 * 2507 * If the folios are mostly unmapped, the processing is fast and it is 2508 * appropriate to hold lru_lock across the whole operation. But if 2509 * the folios are mapped, the processing is slow (folio_referenced()), so 2510 * we should drop lru_lock around each folio. It's impossible to balance 2511 * this, so instead we remove the folios from the LRU while processing them. 2512 * It is safe to rely on the active flag against the non-LRU folios in here 2513 * because nobody will play with that bit on a non-LRU folio. 2514 * 2515 * The downside is that we have to touch folio->_refcount against each folio. 2516 * But we had to alter folio->flags anyway. 2517 */ 2518 static void shrink_active_list(unsigned long nr_to_scan, 2519 struct lruvec *lruvec, 2520 struct scan_control *sc, 2521 enum lru_list lru) 2522 { 2523 unsigned long nr_taken; 2524 unsigned long nr_scanned; 2525 unsigned long vm_flags; 2526 LIST_HEAD(l_hold); /* The folios which were snipped off */ 2527 LIST_HEAD(l_active); 2528 LIST_HEAD(l_inactive); 2529 unsigned nr_deactivate, nr_activate; 2530 unsigned nr_rotated = 0; 2531 int file = is_file_lru(lru); 2532 struct pglist_data *pgdat = lruvec_pgdat(lruvec); 2533 2534 lru_add_drain(); 2535 2536 spin_lock_irq(&lruvec->lru_lock); 2537 2538 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold, 2539 &nr_scanned, sc, lru); 2540 2541 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken); 2542 2543 if (!cgroup_reclaim(sc)) 2544 __count_vm_events(PGREFILL, nr_scanned); 2545 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned); 2546 2547 spin_unlock_irq(&lruvec->lru_lock); 2548 2549 while (!list_empty(&l_hold)) { 2550 struct folio *folio; 2551 2552 cond_resched(); 2553 folio = lru_to_folio(&l_hold); 2554 list_del(&folio->lru); 2555 2556 if (unlikely(!folio_evictable(folio))) { 2557 folio_putback_lru(folio); 2558 continue; 2559 } 2560 2561 if (unlikely(buffer_heads_over_limit)) { 2562 if (folio_test_private(folio) && folio_trylock(folio)) { 2563 if (folio_test_private(folio)) 2564 filemap_release_folio(folio, 0); 2565 folio_unlock(folio); 2566 } 2567 } 2568 2569 /* Referenced or rmap lock contention: rotate */ 2570 if (folio_referenced(folio, 0, sc->target_mem_cgroup, 2571 &vm_flags) != 0) { 2572 /* 2573 * Identify referenced, file-backed active folios and 2574 * give them one more trip around the active list. So 2575 * that executable code get better chances to stay in 2576 * memory under moderate memory pressure. Anon folios 2577 * are not likely to be evicted by use-once streaming 2578 * IO, plus JVM can create lots of anon VM_EXEC folios, 2579 * so we ignore them here. 2580 */ 2581 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio)) { 2582 nr_rotated += folio_nr_pages(folio); 2583 list_add(&folio->lru, &l_active); 2584 continue; 2585 } 2586 } 2587 2588 folio_clear_active(folio); /* we are de-activating */ 2589 folio_set_workingset(folio); 2590 list_add(&folio->lru, &l_inactive); 2591 } 2592 2593 /* 2594 * Move folios back to the lru list. 2595 */ 2596 spin_lock_irq(&lruvec->lru_lock); 2597 2598 nr_activate = move_pages_to_lru(lruvec, &l_active); 2599 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive); 2600 /* Keep all free folios in l_active list */ 2601 list_splice(&l_inactive, &l_active); 2602 2603 __count_vm_events(PGDEACTIVATE, nr_deactivate); 2604 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate); 2605 2606 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken); 2607 spin_unlock_irq(&lruvec->lru_lock); 2608 2609 mem_cgroup_uncharge_list(&l_active); 2610 free_unref_page_list(&l_active); 2611 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate, 2612 nr_deactivate, nr_rotated, sc->priority, file); 2613 } 2614 2615 static unsigned int reclaim_page_list(struct list_head *page_list, 2616 struct pglist_data *pgdat) 2617 { 2618 struct reclaim_stat dummy_stat; 2619 unsigned int nr_reclaimed; 2620 struct folio *folio; 2621 struct scan_control sc = { 2622 .gfp_mask = GFP_KERNEL, 2623 .may_writepage = 1, 2624 .may_unmap = 1, 2625 .may_swap = 1, 2626 .no_demotion = 1, 2627 }; 2628 2629 nr_reclaimed = shrink_page_list(page_list, pgdat, &sc, &dummy_stat, false); 2630 while (!list_empty(page_list)) { 2631 folio = lru_to_folio(page_list); 2632 list_del(&folio->lru); 2633 folio_putback_lru(folio); 2634 } 2635 2636 return nr_reclaimed; 2637 } 2638 2639 unsigned long reclaim_pages(struct list_head *folio_list) 2640 { 2641 int nid; 2642 unsigned int nr_reclaimed = 0; 2643 LIST_HEAD(node_folio_list); 2644 unsigned int noreclaim_flag; 2645 2646 if (list_empty(folio_list)) 2647 return nr_reclaimed; 2648 2649 noreclaim_flag = memalloc_noreclaim_save(); 2650 2651 nid = folio_nid(lru_to_folio(folio_list)); 2652 do { 2653 struct folio *folio = lru_to_folio(folio_list); 2654 2655 if (nid == folio_nid(folio)) { 2656 folio_clear_active(folio); 2657 list_move(&folio->lru, &node_folio_list); 2658 continue; 2659 } 2660 2661 nr_reclaimed += reclaim_page_list(&node_folio_list, NODE_DATA(nid)); 2662 nid = folio_nid(lru_to_folio(folio_list)); 2663 } while (!list_empty(folio_list)); 2664 2665 nr_reclaimed += reclaim_page_list(&node_folio_list, NODE_DATA(nid)); 2666 2667 memalloc_noreclaim_restore(noreclaim_flag); 2668 2669 return nr_reclaimed; 2670 } 2671 2672 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan, 2673 struct lruvec *lruvec, struct scan_control *sc) 2674 { 2675 if (is_active_lru(lru)) { 2676 if (sc->may_deactivate & (1 << is_file_lru(lru))) 2677 shrink_active_list(nr_to_scan, lruvec, sc, lru); 2678 else 2679 sc->skipped_deactivate = 1; 2680 return 0; 2681 } 2682 2683 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru); 2684 } 2685 2686 /* 2687 * The inactive anon list should be small enough that the VM never has 2688 * to do too much work. 2689 * 2690 * The inactive file list should be small enough to leave most memory 2691 * to the established workingset on the scan-resistant active list, 2692 * but large enough to avoid thrashing the aggregate readahead window. 2693 * 2694 * Both inactive lists should also be large enough that each inactive 2695 * page has a chance to be referenced again before it is reclaimed. 2696 * 2697 * If that fails and refaulting is observed, the inactive list grows. 2698 * 2699 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages 2700 * on this LRU, maintained by the pageout code. An inactive_ratio 2701 * of 3 means 3:1 or 25% of the pages are kept on the inactive list. 2702 * 2703 * total target max 2704 * memory ratio inactive 2705 * ------------------------------------- 2706 * 10MB 1 5MB 2707 * 100MB 1 50MB 2708 * 1GB 3 250MB 2709 * 10GB 10 0.9GB 2710 * 100GB 31 3GB 2711 * 1TB 101 10GB 2712 * 10TB 320 32GB 2713 */ 2714 static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru) 2715 { 2716 enum lru_list active_lru = inactive_lru + LRU_ACTIVE; 2717 unsigned long inactive, active; 2718 unsigned long inactive_ratio; 2719 unsigned long gb; 2720 2721 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru); 2722 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru); 2723 2724 gb = (inactive + active) >> (30 - PAGE_SHIFT); 2725 if (gb) 2726 inactive_ratio = int_sqrt(10 * gb); 2727 else 2728 inactive_ratio = 1; 2729 2730 return inactive * inactive_ratio < active; 2731 } 2732 2733 enum scan_balance { 2734 SCAN_EQUAL, 2735 SCAN_FRACT, 2736 SCAN_ANON, 2737 SCAN_FILE, 2738 }; 2739 2740 static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc) 2741 { 2742 unsigned long file; 2743 struct lruvec *target_lruvec; 2744 2745 if (lru_gen_enabled()) 2746 return; 2747 2748 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat); 2749 2750 /* 2751 * Flush the memory cgroup stats, so that we read accurate per-memcg 2752 * lruvec stats for heuristics. 2753 */ 2754 mem_cgroup_flush_stats(); 2755 2756 /* 2757 * Determine the scan balance between anon and file LRUs. 2758 */ 2759 spin_lock_irq(&target_lruvec->lru_lock); 2760 sc->anon_cost = target_lruvec->anon_cost; 2761 sc->file_cost = target_lruvec->file_cost; 2762 spin_unlock_irq(&target_lruvec->lru_lock); 2763 2764 /* 2765 * Target desirable inactive:active list ratios for the anon 2766 * and file LRU lists. 2767 */ 2768 if (!sc->force_deactivate) { 2769 unsigned long refaults; 2770 2771 /* 2772 * When refaults are being observed, it means a new 2773 * workingset is being established. Deactivate to get 2774 * rid of any stale active pages quickly. 2775 */ 2776 refaults = lruvec_page_state(target_lruvec, 2777 WORKINGSET_ACTIVATE_ANON); 2778 if (refaults != target_lruvec->refaults[WORKINGSET_ANON] || 2779 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON)) 2780 sc->may_deactivate |= DEACTIVATE_ANON; 2781 else 2782 sc->may_deactivate &= ~DEACTIVATE_ANON; 2783 2784 refaults = lruvec_page_state(target_lruvec, 2785 WORKINGSET_ACTIVATE_FILE); 2786 if (refaults != target_lruvec->refaults[WORKINGSET_FILE] || 2787 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE)) 2788 sc->may_deactivate |= DEACTIVATE_FILE; 2789 else 2790 sc->may_deactivate &= ~DEACTIVATE_FILE; 2791 } else 2792 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE; 2793 2794 /* 2795 * If we have plenty of inactive file pages that aren't 2796 * thrashing, try to reclaim those first before touching 2797 * anonymous pages. 2798 */ 2799 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE); 2800 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE)) 2801 sc->cache_trim_mode = 1; 2802 else 2803 sc->cache_trim_mode = 0; 2804 2805 /* 2806 * Prevent the reclaimer from falling into the cache trap: as 2807 * cache pages start out inactive, every cache fault will tip 2808 * the scan balance towards the file LRU. And as the file LRU 2809 * shrinks, so does the window for rotation from references. 2810 * This means we have a runaway feedback loop where a tiny 2811 * thrashing file LRU becomes infinitely more attractive than 2812 * anon pages. Try to detect this based on file LRU size. 2813 */ 2814 if (!cgroup_reclaim(sc)) { 2815 unsigned long total_high_wmark = 0; 2816 unsigned long free, anon; 2817 int z; 2818 2819 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES); 2820 file = node_page_state(pgdat, NR_ACTIVE_FILE) + 2821 node_page_state(pgdat, NR_INACTIVE_FILE); 2822 2823 for (z = 0; z < MAX_NR_ZONES; z++) { 2824 struct zone *zone = &pgdat->node_zones[z]; 2825 2826 if (!managed_zone(zone)) 2827 continue; 2828 2829 total_high_wmark += high_wmark_pages(zone); 2830 } 2831 2832 /* 2833 * Consider anon: if that's low too, this isn't a 2834 * runaway file reclaim problem, but rather just 2835 * extreme pressure. Reclaim as per usual then. 2836 */ 2837 anon = node_page_state(pgdat, NR_INACTIVE_ANON); 2838 2839 sc->file_is_tiny = 2840 file + free <= total_high_wmark && 2841 !(sc->may_deactivate & DEACTIVATE_ANON) && 2842 anon >> sc->priority; 2843 } 2844 } 2845 2846 /* 2847 * Determine how aggressively the anon and file LRU lists should be 2848 * scanned. 2849 * 2850 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan 2851 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan 2852 */ 2853 static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc, 2854 unsigned long *nr) 2855 { 2856 struct pglist_data *pgdat = lruvec_pgdat(lruvec); 2857 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 2858 unsigned long anon_cost, file_cost, total_cost; 2859 int swappiness = mem_cgroup_swappiness(memcg); 2860 u64 fraction[ANON_AND_FILE]; 2861 u64 denominator = 0; /* gcc */ 2862 enum scan_balance scan_balance; 2863 unsigned long ap, fp; 2864 enum lru_list lru; 2865 2866 /* If we have no swap space, do not bother scanning anon pages. */ 2867 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) { 2868 scan_balance = SCAN_FILE; 2869 goto out; 2870 } 2871 2872 /* 2873 * Global reclaim will swap to prevent OOM even with no 2874 * swappiness, but memcg users want to use this knob to 2875 * disable swapping for individual groups completely when 2876 * using the memory controller's swap limit feature would be 2877 * too expensive. 2878 */ 2879 if (cgroup_reclaim(sc) && !swappiness) { 2880 scan_balance = SCAN_FILE; 2881 goto out; 2882 } 2883 2884 /* 2885 * Do not apply any pressure balancing cleverness when the 2886 * system is close to OOM, scan both anon and file equally 2887 * (unless the swappiness setting disagrees with swapping). 2888 */ 2889 if (!sc->priority && swappiness) { 2890 scan_balance = SCAN_EQUAL; 2891 goto out; 2892 } 2893 2894 /* 2895 * If the system is almost out of file pages, force-scan anon. 2896 */ 2897 if (sc->file_is_tiny) { 2898 scan_balance = SCAN_ANON; 2899 goto out; 2900 } 2901 2902 /* 2903 * If there is enough inactive page cache, we do not reclaim 2904 * anything from the anonymous working right now. 2905 */ 2906 if (sc->cache_trim_mode) { 2907 scan_balance = SCAN_FILE; 2908 goto out; 2909 } 2910 2911 scan_balance = SCAN_FRACT; 2912 /* 2913 * Calculate the pressure balance between anon and file pages. 2914 * 2915 * The amount of pressure we put on each LRU is inversely 2916 * proportional to the cost of reclaiming each list, as 2917 * determined by the share of pages that are refaulting, times 2918 * the relative IO cost of bringing back a swapped out 2919 * anonymous page vs reloading a filesystem page (swappiness). 2920 * 2921 * Although we limit that influence to ensure no list gets 2922 * left behind completely: at least a third of the pressure is 2923 * applied, before swappiness. 2924 * 2925 * With swappiness at 100, anon and file have equal IO cost. 2926 */ 2927 total_cost = sc->anon_cost + sc->file_cost; 2928 anon_cost = total_cost + sc->anon_cost; 2929 file_cost = total_cost + sc->file_cost; 2930 total_cost = anon_cost + file_cost; 2931 2932 ap = swappiness * (total_cost + 1); 2933 ap /= anon_cost + 1; 2934 2935 fp = (200 - swappiness) * (total_cost + 1); 2936 fp /= file_cost + 1; 2937 2938 fraction[0] = ap; 2939 fraction[1] = fp; 2940 denominator = ap + fp; 2941 out: 2942 for_each_evictable_lru(lru) { 2943 int file = is_file_lru(lru); 2944 unsigned long lruvec_size; 2945 unsigned long low, min; 2946 unsigned long scan; 2947 2948 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx); 2949 mem_cgroup_protection(sc->target_mem_cgroup, memcg, 2950 &min, &low); 2951 2952 if (min || low) { 2953 /* 2954 * Scale a cgroup's reclaim pressure by proportioning 2955 * its current usage to its memory.low or memory.min 2956 * setting. 2957 * 2958 * This is important, as otherwise scanning aggression 2959 * becomes extremely binary -- from nothing as we 2960 * approach the memory protection threshold, to totally 2961 * nominal as we exceed it. This results in requiring 2962 * setting extremely liberal protection thresholds. It 2963 * also means we simply get no protection at all if we 2964 * set it too low, which is not ideal. 2965 * 2966 * If there is any protection in place, we reduce scan 2967 * pressure by how much of the total memory used is 2968 * within protection thresholds. 2969 * 2970 * There is one special case: in the first reclaim pass, 2971 * we skip over all groups that are within their low 2972 * protection. If that fails to reclaim enough pages to 2973 * satisfy the reclaim goal, we come back and override 2974 * the best-effort low protection. However, we still 2975 * ideally want to honor how well-behaved groups are in 2976 * that case instead of simply punishing them all 2977 * equally. As such, we reclaim them based on how much 2978 * memory they are using, reducing the scan pressure 2979 * again by how much of the total memory used is under 2980 * hard protection. 2981 */ 2982 unsigned long cgroup_size = mem_cgroup_size(memcg); 2983 unsigned long protection; 2984 2985 /* memory.low scaling, make sure we retry before OOM */ 2986 if (!sc->memcg_low_reclaim && low > min) { 2987 protection = low; 2988 sc->memcg_low_skipped = 1; 2989 } else { 2990 protection = min; 2991 } 2992 2993 /* Avoid TOCTOU with earlier protection check */ 2994 cgroup_size = max(cgroup_size, protection); 2995 2996 scan = lruvec_size - lruvec_size * protection / 2997 (cgroup_size + 1); 2998 2999 /* 3000 * Minimally target SWAP_CLUSTER_MAX pages to keep 3001 * reclaim moving forwards, avoiding decrementing 3002 * sc->priority further than desirable. 3003 */ 3004 scan = max(scan, SWAP_CLUSTER_MAX); 3005 } else { 3006 scan = lruvec_size; 3007 } 3008 3009 scan >>= sc->priority; 3010 3011 /* 3012 * If the cgroup's already been deleted, make sure to 3013 * scrape out the remaining cache. 3014 */ 3015 if (!scan && !mem_cgroup_online(memcg)) 3016 scan = min(lruvec_size, SWAP_CLUSTER_MAX); 3017 3018 switch (scan_balance) { 3019 case SCAN_EQUAL: 3020 /* Scan lists relative to size */ 3021 break; 3022 case SCAN_FRACT: 3023 /* 3024 * Scan types proportional to swappiness and 3025 * their relative recent reclaim efficiency. 3026 * Make sure we don't miss the last page on 3027 * the offlined memory cgroups because of a 3028 * round-off error. 3029 */ 3030 scan = mem_cgroup_online(memcg) ? 3031 div64_u64(scan * fraction[file], denominator) : 3032 DIV64_U64_ROUND_UP(scan * fraction[file], 3033 denominator); 3034 break; 3035 case SCAN_FILE: 3036 case SCAN_ANON: 3037 /* Scan one type exclusively */ 3038 if ((scan_balance == SCAN_FILE) != file) 3039 scan = 0; 3040 break; 3041 default: 3042 /* Look ma, no brain */ 3043 BUG(); 3044 } 3045 3046 nr[lru] = scan; 3047 } 3048 } 3049 3050 /* 3051 * Anonymous LRU management is a waste if there is 3052 * ultimately no way to reclaim the memory. 3053 */ 3054 static bool can_age_anon_pages(struct pglist_data *pgdat, 3055 struct scan_control *sc) 3056 { 3057 /* Aging the anon LRU is valuable if swap is present: */ 3058 if (total_swap_pages > 0) 3059 return true; 3060 3061 /* Also valuable if anon pages can be demoted: */ 3062 return can_demote(pgdat->node_id, sc); 3063 } 3064 3065 #ifdef CONFIG_LRU_GEN 3066 3067 /****************************************************************************** 3068 * shorthand helpers 3069 ******************************************************************************/ 3070 3071 #define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset)) 3072 3073 #define DEFINE_MAX_SEQ(lruvec) \ 3074 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq) 3075 3076 #define DEFINE_MIN_SEQ(lruvec) \ 3077 unsigned long min_seq[ANON_AND_FILE] = { \ 3078 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \ 3079 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \ 3080 } 3081 3082 #define for_each_gen_type_zone(gen, type, zone) \ 3083 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \ 3084 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \ 3085 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++) 3086 3087 static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid) 3088 { 3089 struct pglist_data *pgdat = NODE_DATA(nid); 3090 3091 #ifdef CONFIG_MEMCG 3092 if (memcg) { 3093 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec; 3094 3095 /* for hotadd_new_pgdat() */ 3096 if (!lruvec->pgdat) 3097 lruvec->pgdat = pgdat; 3098 3099 return lruvec; 3100 } 3101 #endif 3102 VM_WARN_ON_ONCE(!mem_cgroup_disabled()); 3103 3104 return pgdat ? &pgdat->__lruvec : NULL; 3105 } 3106 3107 static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc) 3108 { 3109 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 3110 struct pglist_data *pgdat = lruvec_pgdat(lruvec); 3111 3112 if (!can_demote(pgdat->node_id, sc) && 3113 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH) 3114 return 0; 3115 3116 return mem_cgroup_swappiness(memcg); 3117 } 3118 3119 static int get_nr_gens(struct lruvec *lruvec, int type) 3120 { 3121 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1; 3122 } 3123 3124 static bool __maybe_unused seq_is_valid(struct lruvec *lruvec) 3125 { 3126 /* see the comment on lru_gen_struct */ 3127 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS && 3128 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) && 3129 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS; 3130 } 3131 3132 /****************************************************************************** 3133 * mm_struct list 3134 ******************************************************************************/ 3135 3136 static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg) 3137 { 3138 static struct lru_gen_mm_list mm_list = { 3139 .fifo = LIST_HEAD_INIT(mm_list.fifo), 3140 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock), 3141 }; 3142 3143 #ifdef CONFIG_MEMCG 3144 if (memcg) 3145 return &memcg->mm_list; 3146 #endif 3147 VM_WARN_ON_ONCE(!mem_cgroup_disabled()); 3148 3149 return &mm_list; 3150 } 3151 3152 void lru_gen_add_mm(struct mm_struct *mm) 3153 { 3154 int nid; 3155 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm); 3156 struct lru_gen_mm_list *mm_list = get_mm_list(memcg); 3157 3158 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list)); 3159 #ifdef CONFIG_MEMCG 3160 VM_WARN_ON_ONCE(mm->lru_gen.memcg); 3161 mm->lru_gen.memcg = memcg; 3162 #endif 3163 spin_lock(&mm_list->lock); 3164 3165 for_each_node_state(nid, N_MEMORY) { 3166 struct lruvec *lruvec = get_lruvec(memcg, nid); 3167 3168 if (!lruvec) 3169 continue; 3170 3171 /* the first addition since the last iteration */ 3172 if (lruvec->mm_state.tail == &mm_list->fifo) 3173 lruvec->mm_state.tail = &mm->lru_gen.list; 3174 } 3175 3176 list_add_tail(&mm->lru_gen.list, &mm_list->fifo); 3177 3178 spin_unlock(&mm_list->lock); 3179 } 3180 3181 void lru_gen_del_mm(struct mm_struct *mm) 3182 { 3183 int nid; 3184 struct lru_gen_mm_list *mm_list; 3185 struct mem_cgroup *memcg = NULL; 3186 3187 if (list_empty(&mm->lru_gen.list)) 3188 return; 3189 3190 #ifdef CONFIG_MEMCG 3191 memcg = mm->lru_gen.memcg; 3192 #endif 3193 mm_list = get_mm_list(memcg); 3194 3195 spin_lock(&mm_list->lock); 3196 3197 for_each_node(nid) { 3198 struct lruvec *lruvec = get_lruvec(memcg, nid); 3199 3200 if (!lruvec) 3201 continue; 3202 3203 /* where the last iteration ended (exclusive) */ 3204 if (lruvec->mm_state.tail == &mm->lru_gen.list) 3205 lruvec->mm_state.tail = lruvec->mm_state.tail->next; 3206 3207 /* where the current iteration continues (inclusive) */ 3208 if (lruvec->mm_state.head != &mm->lru_gen.list) 3209 continue; 3210 3211 lruvec->mm_state.head = lruvec->mm_state.head->next; 3212 /* the deletion ends the current iteration */ 3213 if (lruvec->mm_state.head == &mm_list->fifo) 3214 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1); 3215 } 3216 3217 list_del_init(&mm->lru_gen.list); 3218 3219 spin_unlock(&mm_list->lock); 3220 3221 #ifdef CONFIG_MEMCG 3222 mem_cgroup_put(mm->lru_gen.memcg); 3223 mm->lru_gen.memcg = NULL; 3224 #endif 3225 } 3226 3227 #ifdef CONFIG_MEMCG 3228 void lru_gen_migrate_mm(struct mm_struct *mm) 3229 { 3230 struct mem_cgroup *memcg; 3231 struct task_struct *task = rcu_dereference_protected(mm->owner, true); 3232 3233 VM_WARN_ON_ONCE(task->mm != mm); 3234 lockdep_assert_held(&task->alloc_lock); 3235 3236 /* for mm_update_next_owner() */ 3237 if (mem_cgroup_disabled()) 3238 return; 3239 3240 rcu_read_lock(); 3241 memcg = mem_cgroup_from_task(task); 3242 rcu_read_unlock(); 3243 if (memcg == mm->lru_gen.memcg) 3244 return; 3245 3246 VM_WARN_ON_ONCE(!mm->lru_gen.memcg); 3247 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list)); 3248 3249 lru_gen_del_mm(mm); 3250 lru_gen_add_mm(mm); 3251 } 3252 #endif 3253 3254 /* 3255 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when 3256 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of 3257 * bits in a bitmap, k is the number of hash functions and n is the number of 3258 * inserted items. 3259 * 3260 * Page table walkers use one of the two filters to reduce their search space. 3261 * To get rid of non-leaf entries that no longer have enough leaf entries, the 3262 * aging uses the double-buffering technique to flip to the other filter each 3263 * time it produces a new generation. For non-leaf entries that have enough 3264 * leaf entries, the aging carries them over to the next generation in 3265 * walk_pmd_range(); the eviction also report them when walking the rmap 3266 * in lru_gen_look_around(). 3267 * 3268 * For future optimizations: 3269 * 1. It's not necessary to keep both filters all the time. The spare one can be 3270 * freed after the RCU grace period and reallocated if needed again. 3271 * 2. And when reallocating, it's worth scaling its size according to the number 3272 * of inserted entries in the other filter, to reduce the memory overhead on 3273 * small systems and false positives on large systems. 3274 * 3. Jenkins' hash function is an alternative to Knuth's. 3275 */ 3276 #define BLOOM_FILTER_SHIFT 15 3277 3278 static inline int filter_gen_from_seq(unsigned long seq) 3279 { 3280 return seq % NR_BLOOM_FILTERS; 3281 } 3282 3283 static void get_item_key(void *item, int *key) 3284 { 3285 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2); 3286 3287 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32)); 3288 3289 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1); 3290 key[1] = hash >> BLOOM_FILTER_SHIFT; 3291 } 3292 3293 static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq) 3294 { 3295 unsigned long *filter; 3296 int gen = filter_gen_from_seq(seq); 3297 3298 filter = lruvec->mm_state.filters[gen]; 3299 if (filter) { 3300 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT)); 3301 return; 3302 } 3303 3304 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT), 3305 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN); 3306 WRITE_ONCE(lruvec->mm_state.filters[gen], filter); 3307 } 3308 3309 static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item) 3310 { 3311 int key[2]; 3312 unsigned long *filter; 3313 int gen = filter_gen_from_seq(seq); 3314 3315 filter = READ_ONCE(lruvec->mm_state.filters[gen]); 3316 if (!filter) 3317 return; 3318 3319 get_item_key(item, key); 3320 3321 if (!test_bit(key[0], filter)) 3322 set_bit(key[0], filter); 3323 if (!test_bit(key[1], filter)) 3324 set_bit(key[1], filter); 3325 } 3326 3327 static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item) 3328 { 3329 int key[2]; 3330 unsigned long *filter; 3331 int gen = filter_gen_from_seq(seq); 3332 3333 filter = READ_ONCE(lruvec->mm_state.filters[gen]); 3334 if (!filter) 3335 return true; 3336 3337 get_item_key(item, key); 3338 3339 return test_bit(key[0], filter) && test_bit(key[1], filter); 3340 } 3341 3342 static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last) 3343 { 3344 int i; 3345 int hist; 3346 3347 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock); 3348 3349 if (walk) { 3350 hist = lru_hist_from_seq(walk->max_seq); 3351 3352 for (i = 0; i < NR_MM_STATS; i++) { 3353 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 3354 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]); 3355 walk->mm_stats[i] = 0; 3356 } 3357 } 3358 3359 if (NR_HIST_GENS > 1 && last) { 3360 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1); 3361 3362 for (i = 0; i < NR_MM_STATS; i++) 3363 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0); 3364 } 3365 } 3366 3367 static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk) 3368 { 3369 int type; 3370 unsigned long size = 0; 3371 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec); 3372 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap); 3373 3374 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap)) 3375 return true; 3376 3377 clear_bit(key, &mm->lru_gen.bitmap); 3378 3379 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) { 3380 size += type ? get_mm_counter(mm, MM_FILEPAGES) : 3381 get_mm_counter(mm, MM_ANONPAGES) + 3382 get_mm_counter(mm, MM_SHMEMPAGES); 3383 } 3384 3385 if (size < MIN_LRU_BATCH) 3386 return true; 3387 3388 return !mmget_not_zero(mm); 3389 } 3390 3391 static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, 3392 struct mm_struct **iter) 3393 { 3394 bool first = false; 3395 bool last = true; 3396 struct mm_struct *mm = NULL; 3397 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 3398 struct lru_gen_mm_list *mm_list = get_mm_list(memcg); 3399 struct lru_gen_mm_state *mm_state = &lruvec->mm_state; 3400 3401 /* 3402 * There are four interesting cases for this page table walker: 3403 * 1. It tries to start a new iteration of mm_list with a stale max_seq; 3404 * there is nothing left to do. 3405 * 2. It's the first of the current generation, and it needs to reset 3406 * the Bloom filter for the next generation. 3407 * 3. It reaches the end of mm_list, and it needs to increment 3408 * mm_state->seq; the iteration is done. 3409 * 4. It's the last of the current generation, and it needs to reset the 3410 * mm stats counters for the next generation. 3411 */ 3412 spin_lock(&mm_list->lock); 3413 3414 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq); 3415 VM_WARN_ON_ONCE(*iter && mm_state->seq > walk->max_seq); 3416 VM_WARN_ON_ONCE(*iter && !mm_state->nr_walkers); 3417 3418 if (walk->max_seq <= mm_state->seq) { 3419 if (!*iter) 3420 last = false; 3421 goto done; 3422 } 3423 3424 if (!mm_state->nr_walkers) { 3425 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo); 3426 3427 mm_state->head = mm_list->fifo.next; 3428 first = true; 3429 } 3430 3431 while (!mm && mm_state->head != &mm_list->fifo) { 3432 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list); 3433 3434 mm_state->head = mm_state->head->next; 3435 3436 /* force scan for those added after the last iteration */ 3437 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) { 3438 mm_state->tail = mm_state->head; 3439 walk->force_scan = true; 3440 } 3441 3442 if (should_skip_mm(mm, walk)) 3443 mm = NULL; 3444 } 3445 3446 if (mm_state->head == &mm_list->fifo) 3447 WRITE_ONCE(mm_state->seq, mm_state->seq + 1); 3448 done: 3449 if (*iter && !mm) 3450 mm_state->nr_walkers--; 3451 if (!*iter && mm) 3452 mm_state->nr_walkers++; 3453 3454 if (mm_state->nr_walkers) 3455 last = false; 3456 3457 if (*iter || last) 3458 reset_mm_stats(lruvec, walk, last); 3459 3460 spin_unlock(&mm_list->lock); 3461 3462 if (mm && first) 3463 reset_bloom_filter(lruvec, walk->max_seq + 1); 3464 3465 if (*iter) 3466 mmput_async(*iter); 3467 3468 *iter = mm; 3469 3470 return last; 3471 } 3472 3473 static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq) 3474 { 3475 bool success = false; 3476 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 3477 struct lru_gen_mm_list *mm_list = get_mm_list(memcg); 3478 struct lru_gen_mm_state *mm_state = &lruvec->mm_state; 3479 3480 spin_lock(&mm_list->lock); 3481 3482 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq); 3483 3484 if (max_seq > mm_state->seq && !mm_state->nr_walkers) { 3485 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo); 3486 3487 WRITE_ONCE(mm_state->seq, mm_state->seq + 1); 3488 reset_mm_stats(lruvec, NULL, true); 3489 success = true; 3490 } 3491 3492 spin_unlock(&mm_list->lock); 3493 3494 return success; 3495 } 3496 3497 /****************************************************************************** 3498 * refault feedback loop 3499 ******************************************************************************/ 3500 3501 /* 3502 * A feedback loop based on Proportional-Integral-Derivative (PID) controller. 3503 * 3504 * The P term is refaulted/(evicted+protected) from a tier in the generation 3505 * currently being evicted; the I term is the exponential moving average of the 3506 * P term over the generations previously evicted, using the smoothing factor 3507 * 1/2; the D term isn't supported. 3508 * 3509 * The setpoint (SP) is always the first tier of one type; the process variable 3510 * (PV) is either any tier of the other type or any other tier of the same 3511 * type. 3512 * 3513 * The error is the difference between the SP and the PV; the correction is to 3514 * turn off protection when SP>PV or turn on protection when SP<PV. 3515 * 3516 * For future optimizations: 3517 * 1. The D term may discount the other two terms over time so that long-lived 3518 * generations can resist stale information. 3519 */ 3520 struct ctrl_pos { 3521 unsigned long refaulted; 3522 unsigned long total; 3523 int gain; 3524 }; 3525 3526 static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain, 3527 struct ctrl_pos *pos) 3528 { 3529 struct lru_gen_struct *lrugen = &lruvec->lrugen; 3530 int hist = lru_hist_from_seq(lrugen->min_seq[type]); 3531 3532 pos->refaulted = lrugen->avg_refaulted[type][tier] + 3533 atomic_long_read(&lrugen->refaulted[hist][type][tier]); 3534 pos->total = lrugen->avg_total[type][tier] + 3535 atomic_long_read(&lrugen->evicted[hist][type][tier]); 3536 if (tier) 3537 pos->total += lrugen->protected[hist][type][tier - 1]; 3538 pos->gain = gain; 3539 } 3540 3541 static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover) 3542 { 3543 int hist, tier; 3544 struct lru_gen_struct *lrugen = &lruvec->lrugen; 3545 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1; 3546 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1; 3547 3548 lockdep_assert_held(&lruvec->lru_lock); 3549 3550 if (!carryover && !clear) 3551 return; 3552 3553 hist = lru_hist_from_seq(seq); 3554 3555 for (tier = 0; tier < MAX_NR_TIERS; tier++) { 3556 if (carryover) { 3557 unsigned long sum; 3558 3559 sum = lrugen->avg_refaulted[type][tier] + 3560 atomic_long_read(&lrugen->refaulted[hist][type][tier]); 3561 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2); 3562 3563 sum = lrugen->avg_total[type][tier] + 3564 atomic_long_read(&lrugen->evicted[hist][type][tier]); 3565 if (tier) 3566 sum += lrugen->protected[hist][type][tier - 1]; 3567 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2); 3568 } 3569 3570 if (clear) { 3571 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0); 3572 atomic_long_set(&lrugen->evicted[hist][type][tier], 0); 3573 if (tier) 3574 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0); 3575 } 3576 } 3577 } 3578 3579 static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv) 3580 { 3581 /* 3582 * Return true if the PV has a limited number of refaults or a lower 3583 * refaulted/total than the SP. 3584 */ 3585 return pv->refaulted < MIN_LRU_BATCH || 3586 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <= 3587 (sp->refaulted + 1) * pv->total * pv->gain; 3588 } 3589 3590 /****************************************************************************** 3591 * the aging 3592 ******************************************************************************/ 3593 3594 /* promote pages accessed through page tables */ 3595 static int folio_update_gen(struct folio *folio, int gen) 3596 { 3597 unsigned long new_flags, old_flags = READ_ONCE(folio->flags); 3598 3599 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS); 3600 VM_WARN_ON_ONCE(!rcu_read_lock_held()); 3601 3602 do { 3603 /* lru_gen_del_folio() has isolated this page? */ 3604 if (!(old_flags & LRU_GEN_MASK)) { 3605 /* for shrink_page_list() */ 3606 new_flags = old_flags | BIT(PG_referenced); 3607 continue; 3608 } 3609 3610 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS); 3611 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF; 3612 } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags)); 3613 3614 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1; 3615 } 3616 3617 /* protect pages accessed multiple times through file descriptors */ 3618 static int folio_inc_gen(struct lruvec *lruvec, struct folio *folio, bool reclaiming) 3619 { 3620 int type = folio_is_file_lru(folio); 3621 struct lru_gen_struct *lrugen = &lruvec->lrugen; 3622 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]); 3623 unsigned long new_flags, old_flags = READ_ONCE(folio->flags); 3624 3625 VM_WARN_ON_ONCE_FOLIO(!(old_flags & LRU_GEN_MASK), folio); 3626 3627 do { 3628 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1; 3629 /* folio_update_gen() has promoted this page? */ 3630 if (new_gen >= 0 && new_gen != old_gen) 3631 return new_gen; 3632 3633 new_gen = (old_gen + 1) % MAX_NR_GENS; 3634 3635 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS); 3636 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF; 3637 /* for folio_end_writeback() */ 3638 if (reclaiming) 3639 new_flags |= BIT(PG_reclaim); 3640 } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags)); 3641 3642 lru_gen_update_size(lruvec, folio, old_gen, new_gen); 3643 3644 return new_gen; 3645 } 3646 3647 static void update_batch_size(struct lru_gen_mm_walk *walk, struct folio *folio, 3648 int old_gen, int new_gen) 3649 { 3650 int type = folio_is_file_lru(folio); 3651 int zone = folio_zonenum(folio); 3652 int delta = folio_nr_pages(folio); 3653 3654 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS); 3655 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS); 3656 3657 walk->batched++; 3658 3659 walk->nr_pages[old_gen][type][zone] -= delta; 3660 walk->nr_pages[new_gen][type][zone] += delta; 3661 } 3662 3663 static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk) 3664 { 3665 int gen, type, zone; 3666 struct lru_gen_struct *lrugen = &lruvec->lrugen; 3667 3668 walk->batched = 0; 3669 3670 for_each_gen_type_zone(gen, type, zone) { 3671 enum lru_list lru = type * LRU_INACTIVE_FILE; 3672 int delta = walk->nr_pages[gen][type][zone]; 3673 3674 if (!delta) 3675 continue; 3676 3677 walk->nr_pages[gen][type][zone] = 0; 3678 WRITE_ONCE(lrugen->nr_pages[gen][type][zone], 3679 lrugen->nr_pages[gen][type][zone] + delta); 3680 3681 if (lru_gen_is_active(lruvec, gen)) 3682 lru += LRU_ACTIVE; 3683 __update_lru_size(lruvec, lru, zone, delta); 3684 } 3685 } 3686 3687 static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args) 3688 { 3689 struct address_space *mapping; 3690 struct vm_area_struct *vma = args->vma; 3691 struct lru_gen_mm_walk *walk = args->private; 3692 3693 if (!vma_is_accessible(vma)) 3694 return true; 3695 3696 if (is_vm_hugetlb_page(vma)) 3697 return true; 3698 3699 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ)) 3700 return true; 3701 3702 if (vma == get_gate_vma(vma->vm_mm)) 3703 return true; 3704 3705 if (vma_is_anonymous(vma)) 3706 return !walk->can_swap; 3707 3708 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping)) 3709 return true; 3710 3711 mapping = vma->vm_file->f_mapping; 3712 if (mapping_unevictable(mapping)) 3713 return true; 3714 3715 if (shmem_mapping(mapping)) 3716 return !walk->can_swap; 3717 3718 /* to exclude special mappings like dax, etc. */ 3719 return !mapping->a_ops->read_folio; 3720 } 3721 3722 /* 3723 * Some userspace memory allocators map many single-page VMAs. Instead of 3724 * returning back to the PGD table for each of such VMAs, finish an entire PMD 3725 * table to reduce zigzags and improve cache performance. 3726 */ 3727 static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args, 3728 unsigned long *vm_start, unsigned long *vm_end) 3729 { 3730 unsigned long start = round_up(*vm_end, size); 3731 unsigned long end = (start | ~mask) + 1; 3732 3733 VM_WARN_ON_ONCE(mask & size); 3734 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask)); 3735 3736 while (args->vma) { 3737 if (start >= args->vma->vm_end) { 3738 args->vma = args->vma->vm_next; 3739 continue; 3740 } 3741 3742 if (end && end <= args->vma->vm_start) 3743 return false; 3744 3745 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) { 3746 args->vma = args->vma->vm_next; 3747 continue; 3748 } 3749 3750 *vm_start = max(start, args->vma->vm_start); 3751 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1; 3752 3753 return true; 3754 } 3755 3756 return false; 3757 } 3758 3759 static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr) 3760 { 3761 unsigned long pfn = pte_pfn(pte); 3762 3763 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end); 3764 3765 if (!pte_present(pte) || is_zero_pfn(pfn)) 3766 return -1; 3767 3768 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte))) 3769 return -1; 3770 3771 if (WARN_ON_ONCE(!pfn_valid(pfn))) 3772 return -1; 3773 3774 return pfn; 3775 } 3776 3777 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) 3778 static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr) 3779 { 3780 unsigned long pfn = pmd_pfn(pmd); 3781 3782 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end); 3783 3784 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd)) 3785 return -1; 3786 3787 if (WARN_ON_ONCE(pmd_devmap(pmd))) 3788 return -1; 3789 3790 if (WARN_ON_ONCE(!pfn_valid(pfn))) 3791 return -1; 3792 3793 return pfn; 3794 } 3795 #endif 3796 3797 static struct folio *get_pfn_folio(unsigned long pfn, struct mem_cgroup *memcg, 3798 struct pglist_data *pgdat, bool can_swap) 3799 { 3800 struct folio *folio; 3801 3802 /* try to avoid unnecessary memory loads */ 3803 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat)) 3804 return NULL; 3805 3806 folio = pfn_folio(pfn); 3807 if (folio_nid(folio) != pgdat->node_id) 3808 return NULL; 3809 3810 if (folio_memcg_rcu(folio) != memcg) 3811 return NULL; 3812 3813 /* file VMAs can contain anon pages from COW */ 3814 if (!folio_is_file_lru(folio) && !can_swap) 3815 return NULL; 3816 3817 return folio; 3818 } 3819 3820 static bool suitable_to_scan(int total, int young) 3821 { 3822 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8); 3823 3824 /* suitable if the average number of young PTEs per cacheline is >=1 */ 3825 return young * n >= total; 3826 } 3827 3828 static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end, 3829 struct mm_walk *args) 3830 { 3831 int i; 3832 pte_t *pte; 3833 spinlock_t *ptl; 3834 unsigned long addr; 3835 int total = 0; 3836 int young = 0; 3837 struct lru_gen_mm_walk *walk = args->private; 3838 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec); 3839 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec); 3840 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq); 3841 3842 VM_WARN_ON_ONCE(pmd_leaf(*pmd)); 3843 3844 ptl = pte_lockptr(args->mm, pmd); 3845 if (!spin_trylock(ptl)) 3846 return false; 3847 3848 arch_enter_lazy_mmu_mode(); 3849 3850 pte = pte_offset_map(pmd, start & PMD_MASK); 3851 restart: 3852 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) { 3853 unsigned long pfn; 3854 struct folio *folio; 3855 3856 total++; 3857 walk->mm_stats[MM_LEAF_TOTAL]++; 3858 3859 pfn = get_pte_pfn(pte[i], args->vma, addr); 3860 if (pfn == -1) 3861 continue; 3862 3863 if (!pte_young(pte[i])) { 3864 walk->mm_stats[MM_LEAF_OLD]++; 3865 continue; 3866 } 3867 3868 folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap); 3869 if (!folio) 3870 continue; 3871 3872 if (!ptep_test_and_clear_young(args->vma, addr, pte + i)) 3873 VM_WARN_ON_ONCE(true); 3874 3875 young++; 3876 walk->mm_stats[MM_LEAF_YOUNG]++; 3877 3878 if (pte_dirty(pte[i]) && !folio_test_dirty(folio) && 3879 !(folio_test_anon(folio) && folio_test_swapbacked(folio) && 3880 !folio_test_swapcache(folio))) 3881 folio_mark_dirty(folio); 3882 3883 old_gen = folio_update_gen(folio, new_gen); 3884 if (old_gen >= 0 && old_gen != new_gen) 3885 update_batch_size(walk, folio, old_gen, new_gen); 3886 } 3887 3888 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end)) 3889 goto restart; 3890 3891 pte_unmap(pte); 3892 3893 arch_leave_lazy_mmu_mode(); 3894 spin_unlock(ptl); 3895 3896 return suitable_to_scan(total, young); 3897 } 3898 3899 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) 3900 static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma, 3901 struct mm_walk *args, unsigned long *bitmap, unsigned long *start) 3902 { 3903 int i; 3904 pmd_t *pmd; 3905 spinlock_t *ptl; 3906 struct lru_gen_mm_walk *walk = args->private; 3907 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec); 3908 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec); 3909 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq); 3910 3911 VM_WARN_ON_ONCE(pud_leaf(*pud)); 3912 3913 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */ 3914 if (*start == -1) { 3915 *start = next; 3916 return; 3917 } 3918 3919 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start); 3920 if (i && i <= MIN_LRU_BATCH) { 3921 __set_bit(i - 1, bitmap); 3922 return; 3923 } 3924 3925 pmd = pmd_offset(pud, *start); 3926 3927 ptl = pmd_lockptr(args->mm, pmd); 3928 if (!spin_trylock(ptl)) 3929 goto done; 3930 3931 arch_enter_lazy_mmu_mode(); 3932 3933 do { 3934 unsigned long pfn; 3935 struct folio *folio; 3936 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start; 3937 3938 pfn = get_pmd_pfn(pmd[i], vma, addr); 3939 if (pfn == -1) 3940 goto next; 3941 3942 if (!pmd_trans_huge(pmd[i])) { 3943 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)) 3944 pmdp_test_and_clear_young(vma, addr, pmd + i); 3945 goto next; 3946 } 3947 3948 folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap); 3949 if (!folio) 3950 goto next; 3951 3952 if (!pmdp_test_and_clear_young(vma, addr, pmd + i)) 3953 goto next; 3954 3955 walk->mm_stats[MM_LEAF_YOUNG]++; 3956 3957 if (pmd_dirty(pmd[i]) && !folio_test_dirty(folio) && 3958 !(folio_test_anon(folio) && folio_test_swapbacked(folio) && 3959 !folio_test_swapcache(folio))) 3960 folio_mark_dirty(folio); 3961 3962 old_gen = folio_update_gen(folio, new_gen); 3963 if (old_gen >= 0 && old_gen != new_gen) 3964 update_batch_size(walk, folio, old_gen, new_gen); 3965 next: 3966 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1; 3967 } while (i <= MIN_LRU_BATCH); 3968 3969 arch_leave_lazy_mmu_mode(); 3970 spin_unlock(ptl); 3971 done: 3972 *start = -1; 3973 bitmap_zero(bitmap, MIN_LRU_BATCH); 3974 } 3975 #else 3976 static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma, 3977 struct mm_walk *args, unsigned long *bitmap, unsigned long *start) 3978 { 3979 } 3980 #endif 3981 3982 static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end, 3983 struct mm_walk *args) 3984 { 3985 int i; 3986 pmd_t *pmd; 3987 unsigned long next; 3988 unsigned long addr; 3989 struct vm_area_struct *vma; 3990 unsigned long pos = -1; 3991 struct lru_gen_mm_walk *walk = args->private; 3992 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {}; 3993 3994 VM_WARN_ON_ONCE(pud_leaf(*pud)); 3995 3996 /* 3997 * Finish an entire PMD in two passes: the first only reaches to PTE 3998 * tables to avoid taking the PMD lock; the second, if necessary, takes 3999 * the PMD lock to clear the accessed bit in PMD entries. 4000 */ 4001 pmd = pmd_offset(pud, start & PUD_MASK); 4002 restart: 4003 /* walk_pte_range() may call get_next_vma() */ 4004 vma = args->vma; 4005 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) { 4006 pmd_t val = pmd_read_atomic(pmd + i); 4007 4008 /* for pmd_read_atomic() */ 4009 barrier(); 4010 4011 next = pmd_addr_end(addr, end); 4012 4013 if (!pmd_present(val) || is_huge_zero_pmd(val)) { 4014 walk->mm_stats[MM_LEAF_TOTAL]++; 4015 continue; 4016 } 4017 4018 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 4019 if (pmd_trans_huge(val)) { 4020 unsigned long pfn = pmd_pfn(val); 4021 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec); 4022 4023 walk->mm_stats[MM_LEAF_TOTAL]++; 4024 4025 if (!pmd_young(val)) { 4026 walk->mm_stats[MM_LEAF_OLD]++; 4027 continue; 4028 } 4029 4030 /* try to avoid unnecessary memory loads */ 4031 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat)) 4032 continue; 4033 4034 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos); 4035 continue; 4036 } 4037 #endif 4038 walk->mm_stats[MM_NONLEAF_TOTAL]++; 4039 4040 #ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG 4041 if (!pmd_young(val)) 4042 continue; 4043 4044 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos); 4045 #endif 4046 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i)) 4047 continue; 4048 4049 walk->mm_stats[MM_NONLEAF_FOUND]++; 4050 4051 if (!walk_pte_range(&val, addr, next, args)) 4052 continue; 4053 4054 walk->mm_stats[MM_NONLEAF_ADDED]++; 4055 4056 /* carry over to the next generation */ 4057 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i); 4058 } 4059 4060 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos); 4061 4062 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end)) 4063 goto restart; 4064 } 4065 4066 static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end, 4067 struct mm_walk *args) 4068 { 4069 int i; 4070 pud_t *pud; 4071 unsigned long addr; 4072 unsigned long next; 4073 struct lru_gen_mm_walk *walk = args->private; 4074 4075 VM_WARN_ON_ONCE(p4d_leaf(*p4d)); 4076 4077 pud = pud_offset(p4d, start & P4D_MASK); 4078 restart: 4079 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) { 4080 pud_t val = READ_ONCE(pud[i]); 4081 4082 next = pud_addr_end(addr, end); 4083 4084 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val))) 4085 continue; 4086 4087 walk_pmd_range(&val, addr, next, args); 4088 4089 /* a racy check to curtail the waiting time */ 4090 if (wq_has_sleeper(&walk->lruvec->mm_state.wait)) 4091 return 1; 4092 4093 if (need_resched() || walk->batched >= MAX_LRU_BATCH) { 4094 end = (addr | ~PUD_MASK) + 1; 4095 goto done; 4096 } 4097 } 4098 4099 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end)) 4100 goto restart; 4101 4102 end = round_up(end, P4D_SIZE); 4103 done: 4104 if (!end || !args->vma) 4105 return 1; 4106 4107 walk->next_addr = max(end, args->vma->vm_start); 4108 4109 return -EAGAIN; 4110 } 4111 4112 static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk) 4113 { 4114 static const struct mm_walk_ops mm_walk_ops = { 4115 .test_walk = should_skip_vma, 4116 .p4d_entry = walk_pud_range, 4117 }; 4118 4119 int err; 4120 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 4121 4122 walk->next_addr = FIRST_USER_ADDRESS; 4123 4124 do { 4125 err = -EBUSY; 4126 4127 /* folio_update_gen() requires stable folio_memcg() */ 4128 if (!mem_cgroup_trylock_pages(memcg)) 4129 break; 4130 4131 /* the caller might be holding the lock for write */ 4132 if (mmap_read_trylock(mm)) { 4133 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk); 4134 4135 mmap_read_unlock(mm); 4136 } 4137 4138 mem_cgroup_unlock_pages(); 4139 4140 if (walk->batched) { 4141 spin_lock_irq(&lruvec->lru_lock); 4142 reset_batch_size(lruvec, walk); 4143 spin_unlock_irq(&lruvec->lru_lock); 4144 } 4145 4146 cond_resched(); 4147 } while (err == -EAGAIN); 4148 } 4149 4150 static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat) 4151 { 4152 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk; 4153 4154 if (pgdat && current_is_kswapd()) { 4155 VM_WARN_ON_ONCE(walk); 4156 4157 walk = &pgdat->mm_walk; 4158 } else if (!pgdat && !walk) { 4159 VM_WARN_ON_ONCE(current_is_kswapd()); 4160 4161 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN); 4162 } 4163 4164 current->reclaim_state->mm_walk = walk; 4165 4166 return walk; 4167 } 4168 4169 static void clear_mm_walk(void) 4170 { 4171 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk; 4172 4173 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages))); 4174 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats))); 4175 4176 current->reclaim_state->mm_walk = NULL; 4177 4178 if (!current_is_kswapd()) 4179 kfree(walk); 4180 } 4181 4182 static void inc_min_seq(struct lruvec *lruvec, int type) 4183 { 4184 struct lru_gen_struct *lrugen = &lruvec->lrugen; 4185 4186 reset_ctrl_pos(lruvec, type, true); 4187 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1); 4188 } 4189 4190 static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap) 4191 { 4192 int gen, type, zone; 4193 bool success = false; 4194 struct lru_gen_struct *lrugen = &lruvec->lrugen; 4195 DEFINE_MIN_SEQ(lruvec); 4196 4197 VM_WARN_ON_ONCE(!seq_is_valid(lruvec)); 4198 4199 /* find the oldest populated generation */ 4200 for (type = !can_swap; type < ANON_AND_FILE; type++) { 4201 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) { 4202 gen = lru_gen_from_seq(min_seq[type]); 4203 4204 for (zone = 0; zone < MAX_NR_ZONES; zone++) { 4205 if (!list_empty(&lrugen->lists[gen][type][zone])) 4206 goto next; 4207 } 4208 4209 min_seq[type]++; 4210 } 4211 next: 4212 ; 4213 } 4214 4215 /* see the comment on lru_gen_struct */ 4216 if (can_swap) { 4217 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]); 4218 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]); 4219 } 4220 4221 for (type = !can_swap; type < ANON_AND_FILE; type++) { 4222 if (min_seq[type] == lrugen->min_seq[type]) 4223 continue; 4224 4225 reset_ctrl_pos(lruvec, type, true); 4226 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]); 4227 success = true; 4228 } 4229 4230 return success; 4231 } 4232 4233 static void inc_max_seq(struct lruvec *lruvec, bool can_swap) 4234 { 4235 int prev, next; 4236 int type, zone; 4237 struct lru_gen_struct *lrugen = &lruvec->lrugen; 4238 4239 spin_lock_irq(&lruvec->lru_lock); 4240 4241 VM_WARN_ON_ONCE(!seq_is_valid(lruvec)); 4242 4243 for (type = ANON_AND_FILE - 1; type >= 0; type--) { 4244 if (get_nr_gens(lruvec, type) != MAX_NR_GENS) 4245 continue; 4246 4247 VM_WARN_ON_ONCE(type == LRU_GEN_FILE || can_swap); 4248 4249 inc_min_seq(lruvec, type); 4250 } 4251 4252 /* 4253 * Update the active/inactive LRU sizes for compatibility. Both sides of 4254 * the current max_seq need to be covered, since max_seq+1 can overlap 4255 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do 4256 * overlap, cold/hot inversion happens. 4257 */ 4258 prev = lru_gen_from_seq(lrugen->max_seq - 1); 4259 next = lru_gen_from_seq(lrugen->max_seq + 1); 4260 4261 for (type = 0; type < ANON_AND_FILE; type++) { 4262 for (zone = 0; zone < MAX_NR_ZONES; zone++) { 4263 enum lru_list lru = type * LRU_INACTIVE_FILE; 4264 long delta = lrugen->nr_pages[prev][type][zone] - 4265 lrugen->nr_pages[next][type][zone]; 4266 4267 if (!delta) 4268 continue; 4269 4270 __update_lru_size(lruvec, lru, zone, delta); 4271 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta); 4272 } 4273 } 4274 4275 for (type = 0; type < ANON_AND_FILE; type++) 4276 reset_ctrl_pos(lruvec, type, false); 4277 4278 /* make sure preceding modifications appear */ 4279 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1); 4280 4281 spin_unlock_irq(&lruvec->lru_lock); 4282 } 4283 4284 static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq, 4285 struct scan_control *sc, bool can_swap) 4286 { 4287 bool success; 4288 struct lru_gen_mm_walk *walk; 4289 struct mm_struct *mm = NULL; 4290 struct lru_gen_struct *lrugen = &lruvec->lrugen; 4291 4292 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq)); 4293 4294 /* see the comment in iterate_mm_list() */ 4295 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) { 4296 success = false; 4297 goto done; 4298 } 4299 4300 /* 4301 * If the hardware doesn't automatically set the accessed bit, fallback 4302 * to lru_gen_look_around(), which only clears the accessed bit in a 4303 * handful of PTEs. Spreading the work out over a period of time usually 4304 * is less efficient, but it avoids bursty page faults. 4305 */ 4306 if (!arch_has_hw_pte_young()) { 4307 success = iterate_mm_list_nowalk(lruvec, max_seq); 4308 goto done; 4309 } 4310 4311 walk = set_mm_walk(NULL); 4312 if (!walk) { 4313 success = iterate_mm_list_nowalk(lruvec, max_seq); 4314 goto done; 4315 } 4316 4317 walk->lruvec = lruvec; 4318 walk->max_seq = max_seq; 4319 walk->can_swap = can_swap; 4320 walk->force_scan = false; 4321 4322 do { 4323 success = iterate_mm_list(lruvec, walk, &mm); 4324 if (mm) 4325 walk_mm(lruvec, mm, walk); 4326 4327 cond_resched(); 4328 } while (mm); 4329 done: 4330 if (!success) { 4331 if (sc->priority <= DEF_PRIORITY - 2) 4332 wait_event_killable(lruvec->mm_state.wait, 4333 max_seq < READ_ONCE(lrugen->max_seq)); 4334 4335 return max_seq < READ_ONCE(lrugen->max_seq); 4336 } 4337 4338 VM_WARN_ON_ONCE(max_seq != READ_ONCE(lrugen->max_seq)); 4339 4340 inc_max_seq(lruvec, can_swap); 4341 /* either this sees any waiters or they will see updated max_seq */ 4342 if (wq_has_sleeper(&lruvec->mm_state.wait)) 4343 wake_up_all(&lruvec->mm_state.wait); 4344 4345 wakeup_flusher_threads(WB_REASON_VMSCAN); 4346 4347 return true; 4348 } 4349 4350 static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, unsigned long *min_seq, 4351 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan) 4352 { 4353 int gen, type, zone; 4354 unsigned long old = 0; 4355 unsigned long young = 0; 4356 unsigned long total = 0; 4357 struct lru_gen_struct *lrugen = &lruvec->lrugen; 4358 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 4359 4360 for (type = !can_swap; type < ANON_AND_FILE; type++) { 4361 unsigned long seq; 4362 4363 for (seq = min_seq[type]; seq <= max_seq; seq++) { 4364 unsigned long size = 0; 4365 4366 gen = lru_gen_from_seq(seq); 4367 4368 for (zone = 0; zone < MAX_NR_ZONES; zone++) 4369 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L); 4370 4371 total += size; 4372 if (seq == max_seq) 4373 young += size; 4374 else if (seq + MIN_NR_GENS == max_seq) 4375 old += size; 4376 } 4377 } 4378 4379 /* try to scrape all its memory if this memcg was deleted */ 4380 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total; 4381 4382 /* 4383 * The aging tries to be lazy to reduce the overhead, while the eviction 4384 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the 4385 * ideal number of generations is MIN_NR_GENS+1. 4386 */ 4387 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq) 4388 return true; 4389 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq) 4390 return false; 4391 4392 /* 4393 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1) 4394 * of the total number of pages for each generation. A reasonable range 4395 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The 4396 * aging cares about the upper bound of hot pages, while the eviction 4397 * cares about the lower bound of cold pages. 4398 */ 4399 if (young * MIN_NR_GENS > total) 4400 return true; 4401 if (old * (MIN_NR_GENS + 2) < total) 4402 return true; 4403 4404 return false; 4405 } 4406 4407 static void age_lruvec(struct lruvec *lruvec, struct scan_control *sc) 4408 { 4409 bool need_aging; 4410 unsigned long nr_to_scan; 4411 int swappiness = get_swappiness(lruvec, sc); 4412 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 4413 DEFINE_MAX_SEQ(lruvec); 4414 DEFINE_MIN_SEQ(lruvec); 4415 4416 VM_WARN_ON_ONCE(sc->memcg_low_reclaim); 4417 4418 mem_cgroup_calculate_protection(NULL, memcg); 4419 4420 if (mem_cgroup_below_min(memcg)) 4421 return; 4422 4423 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, swappiness, &nr_to_scan); 4424 if (need_aging) 4425 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness); 4426 } 4427 4428 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc) 4429 { 4430 struct mem_cgroup *memcg; 4431 4432 VM_WARN_ON_ONCE(!current_is_kswapd()); 4433 4434 set_mm_walk(pgdat); 4435 4436 memcg = mem_cgroup_iter(NULL, NULL, NULL); 4437 do { 4438 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat); 4439 4440 age_lruvec(lruvec, sc); 4441 4442 cond_resched(); 4443 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL))); 4444 4445 clear_mm_walk(); 4446 } 4447 4448 /* 4449 * This function exploits spatial locality when shrink_page_list() walks the 4450 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If 4451 * the scan was done cacheline efficiently, it adds the PMD entry pointing to 4452 * the PTE table to the Bloom filter. This forms a feedback loop between the 4453 * eviction and the aging. 4454 */ 4455 void lru_gen_look_around(struct page_vma_mapped_walk *pvmw) 4456 { 4457 int i; 4458 pte_t *pte; 4459 unsigned long start; 4460 unsigned long end; 4461 unsigned long addr; 4462 struct lru_gen_mm_walk *walk; 4463 int young = 0; 4464 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {}; 4465 struct folio *folio = pfn_folio(pvmw->pfn); 4466 struct mem_cgroup *memcg = folio_memcg(folio); 4467 struct pglist_data *pgdat = folio_pgdat(folio); 4468 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat); 4469 DEFINE_MAX_SEQ(lruvec); 4470 int old_gen, new_gen = lru_gen_from_seq(max_seq); 4471 4472 lockdep_assert_held(pvmw->ptl); 4473 VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio); 4474 4475 if (spin_is_contended(pvmw->ptl)) 4476 return; 4477 4478 /* avoid taking the LRU lock under the PTL when possible */ 4479 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL; 4480 4481 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start); 4482 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1; 4483 4484 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) { 4485 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2) 4486 end = start + MIN_LRU_BATCH * PAGE_SIZE; 4487 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2) 4488 start = end - MIN_LRU_BATCH * PAGE_SIZE; 4489 else { 4490 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2; 4491 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2; 4492 } 4493 } 4494 4495 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE; 4496 4497 rcu_read_lock(); 4498 arch_enter_lazy_mmu_mode(); 4499 4500 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) { 4501 unsigned long pfn; 4502 4503 pfn = get_pte_pfn(pte[i], pvmw->vma, addr); 4504 if (pfn == -1) 4505 continue; 4506 4507 if (!pte_young(pte[i])) 4508 continue; 4509 4510 folio = get_pfn_folio(pfn, memcg, pgdat, !walk || walk->can_swap); 4511 if (!folio) 4512 continue; 4513 4514 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i)) 4515 VM_WARN_ON_ONCE(true); 4516 4517 young++; 4518 4519 if (pte_dirty(pte[i]) && !folio_test_dirty(folio) && 4520 !(folio_test_anon(folio) && folio_test_swapbacked(folio) && 4521 !folio_test_swapcache(folio))) 4522 folio_mark_dirty(folio); 4523 4524 old_gen = folio_lru_gen(folio); 4525 if (old_gen < 0) 4526 folio_set_referenced(folio); 4527 else if (old_gen != new_gen) 4528 __set_bit(i, bitmap); 4529 } 4530 4531 arch_leave_lazy_mmu_mode(); 4532 rcu_read_unlock(); 4533 4534 /* feedback from rmap walkers to page table walkers */ 4535 if (suitable_to_scan(i, young)) 4536 update_bloom_filter(lruvec, max_seq, pvmw->pmd); 4537 4538 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) { 4539 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) { 4540 folio = pfn_folio(pte_pfn(pte[i])); 4541 folio_activate(folio); 4542 } 4543 return; 4544 } 4545 4546 /* folio_update_gen() requires stable folio_memcg() */ 4547 if (!mem_cgroup_trylock_pages(memcg)) 4548 return; 4549 4550 if (!walk) { 4551 spin_lock_irq(&lruvec->lru_lock); 4552 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq); 4553 } 4554 4555 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) { 4556 folio = pfn_folio(pte_pfn(pte[i])); 4557 if (folio_memcg_rcu(folio) != memcg) 4558 continue; 4559 4560 old_gen = folio_update_gen(folio, new_gen); 4561 if (old_gen < 0 || old_gen == new_gen) 4562 continue; 4563 4564 if (walk) 4565 update_batch_size(walk, folio, old_gen, new_gen); 4566 else 4567 lru_gen_update_size(lruvec, folio, old_gen, new_gen); 4568 } 4569 4570 if (!walk) 4571 spin_unlock_irq(&lruvec->lru_lock); 4572 4573 mem_cgroup_unlock_pages(); 4574 } 4575 4576 /****************************************************************************** 4577 * the eviction 4578 ******************************************************************************/ 4579 4580 static bool sort_folio(struct lruvec *lruvec, struct folio *folio, int tier_idx) 4581 { 4582 bool success; 4583 int gen = folio_lru_gen(folio); 4584 int type = folio_is_file_lru(folio); 4585 int zone = folio_zonenum(folio); 4586 int delta = folio_nr_pages(folio); 4587 int refs = folio_lru_refs(folio); 4588 int tier = lru_tier_from_refs(refs); 4589 struct lru_gen_struct *lrugen = &lruvec->lrugen; 4590 4591 VM_WARN_ON_ONCE_FOLIO(gen >= MAX_NR_GENS, folio); 4592 4593 /* unevictable */ 4594 if (!folio_evictable(folio)) { 4595 success = lru_gen_del_folio(lruvec, folio, true); 4596 VM_WARN_ON_ONCE_FOLIO(!success, folio); 4597 folio_set_unevictable(folio); 4598 lruvec_add_folio(lruvec, folio); 4599 __count_vm_events(UNEVICTABLE_PGCULLED, delta); 4600 return true; 4601 } 4602 4603 /* dirty lazyfree */ 4604 if (type == LRU_GEN_FILE && folio_test_anon(folio) && folio_test_dirty(folio)) { 4605 success = lru_gen_del_folio(lruvec, folio, true); 4606 VM_WARN_ON_ONCE_FOLIO(!success, folio); 4607 folio_set_swapbacked(folio); 4608 lruvec_add_folio_tail(lruvec, folio); 4609 return true; 4610 } 4611 4612 /* promoted */ 4613 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) { 4614 list_move(&folio->lru, &lrugen->lists[gen][type][zone]); 4615 return true; 4616 } 4617 4618 /* protected */ 4619 if (tier > tier_idx) { 4620 int hist = lru_hist_from_seq(lrugen->min_seq[type]); 4621 4622 gen = folio_inc_gen(lruvec, folio, false); 4623 list_move_tail(&folio->lru, &lrugen->lists[gen][type][zone]); 4624 4625 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 4626 lrugen->protected[hist][type][tier - 1] + delta); 4627 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta); 4628 return true; 4629 } 4630 4631 /* waiting for writeback */ 4632 if (folio_test_locked(folio) || folio_test_writeback(folio) || 4633 (type == LRU_GEN_FILE && folio_test_dirty(folio))) { 4634 gen = folio_inc_gen(lruvec, folio, true); 4635 list_move(&folio->lru, &lrugen->lists[gen][type][zone]); 4636 return true; 4637 } 4638 4639 return false; 4640 } 4641 4642 static bool isolate_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc) 4643 { 4644 bool success; 4645 4646 /* unmapping inhibited */ 4647 if (!sc->may_unmap && folio_mapped(folio)) 4648 return false; 4649 4650 /* swapping inhibited */ 4651 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) && 4652 (folio_test_dirty(folio) || 4653 (folio_test_anon(folio) && !folio_test_swapcache(folio)))) 4654 return false; 4655 4656 /* raced with release_pages() */ 4657 if (!folio_try_get(folio)) 4658 return false; 4659 4660 /* raced with another isolation */ 4661 if (!folio_test_clear_lru(folio)) { 4662 folio_put(folio); 4663 return false; 4664 } 4665 4666 /* see the comment on MAX_NR_TIERS */ 4667 if (!folio_test_referenced(folio)) 4668 set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0); 4669 4670 /* for shrink_page_list() */ 4671 folio_clear_reclaim(folio); 4672 folio_clear_referenced(folio); 4673 4674 success = lru_gen_del_folio(lruvec, folio, true); 4675 VM_WARN_ON_ONCE_FOLIO(!success, folio); 4676 4677 return true; 4678 } 4679 4680 static int scan_folios(struct lruvec *lruvec, struct scan_control *sc, 4681 int type, int tier, struct list_head *list) 4682 { 4683 int gen, zone; 4684 enum vm_event_item item; 4685 int sorted = 0; 4686 int scanned = 0; 4687 int isolated = 0; 4688 int remaining = MAX_LRU_BATCH; 4689 struct lru_gen_struct *lrugen = &lruvec->lrugen; 4690 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 4691 4692 VM_WARN_ON_ONCE(!list_empty(list)); 4693 4694 if (get_nr_gens(lruvec, type) == MIN_NR_GENS) 4695 return 0; 4696 4697 gen = lru_gen_from_seq(lrugen->min_seq[type]); 4698 4699 for (zone = sc->reclaim_idx; zone >= 0; zone--) { 4700 LIST_HEAD(moved); 4701 int skipped = 0; 4702 struct list_head *head = &lrugen->lists[gen][type][zone]; 4703 4704 while (!list_empty(head)) { 4705 struct folio *folio = lru_to_folio(head); 4706 int delta = folio_nr_pages(folio); 4707 4708 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio); 4709 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio); 4710 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio); 4711 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio); 4712 4713 scanned += delta; 4714 4715 if (sort_folio(lruvec, folio, tier)) 4716 sorted += delta; 4717 else if (isolate_folio(lruvec, folio, sc)) { 4718 list_add(&folio->lru, list); 4719 isolated += delta; 4720 } else { 4721 list_move(&folio->lru, &moved); 4722 skipped += delta; 4723 } 4724 4725 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH) 4726 break; 4727 } 4728 4729 if (skipped) { 4730 list_splice(&moved, head); 4731 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped); 4732 } 4733 4734 if (!remaining || isolated >= MIN_LRU_BATCH) 4735 break; 4736 } 4737 4738 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT; 4739 if (!cgroup_reclaim(sc)) { 4740 __count_vm_events(item, isolated); 4741 __count_vm_events(PGREFILL, sorted); 4742 } 4743 __count_memcg_events(memcg, item, isolated); 4744 __count_memcg_events(memcg, PGREFILL, sorted); 4745 __count_vm_events(PGSCAN_ANON + type, isolated); 4746 4747 /* 4748 * There might not be eligible pages due to reclaim_idx, may_unmap and 4749 * may_writepage. Check the remaining to prevent livelock if it's not 4750 * making progress. 4751 */ 4752 return isolated || !remaining ? scanned : 0; 4753 } 4754 4755 static int get_tier_idx(struct lruvec *lruvec, int type) 4756 { 4757 int tier; 4758 struct ctrl_pos sp, pv; 4759 4760 /* 4761 * To leave a margin for fluctuations, use a larger gain factor (1:2). 4762 * This value is chosen because any other tier would have at least twice 4763 * as many refaults as the first tier. 4764 */ 4765 read_ctrl_pos(lruvec, type, 0, 1, &sp); 4766 for (tier = 1; tier < MAX_NR_TIERS; tier++) { 4767 read_ctrl_pos(lruvec, type, tier, 2, &pv); 4768 if (!positive_ctrl_err(&sp, &pv)) 4769 break; 4770 } 4771 4772 return tier - 1; 4773 } 4774 4775 static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx) 4776 { 4777 int type, tier; 4778 struct ctrl_pos sp, pv; 4779 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness }; 4780 4781 /* 4782 * Compare the first tier of anon with that of file to determine which 4783 * type to scan. Also need to compare other tiers of the selected type 4784 * with the first tier of the other type to determine the last tier (of 4785 * the selected type) to evict. 4786 */ 4787 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp); 4788 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv); 4789 type = positive_ctrl_err(&sp, &pv); 4790 4791 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp); 4792 for (tier = 1; tier < MAX_NR_TIERS; tier++) { 4793 read_ctrl_pos(lruvec, type, tier, gain[type], &pv); 4794 if (!positive_ctrl_err(&sp, &pv)) 4795 break; 4796 } 4797 4798 *tier_idx = tier - 1; 4799 4800 return type; 4801 } 4802 4803 static int isolate_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness, 4804 int *type_scanned, struct list_head *list) 4805 { 4806 int i; 4807 int type; 4808 int scanned; 4809 int tier = -1; 4810 DEFINE_MIN_SEQ(lruvec); 4811 4812 /* 4813 * Try to make the obvious choice first. When anon and file are both 4814 * available from the same generation, interpret swappiness 1 as file 4815 * first and 200 as anon first. 4816 */ 4817 if (!swappiness) 4818 type = LRU_GEN_FILE; 4819 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE]) 4820 type = LRU_GEN_ANON; 4821 else if (swappiness == 1) 4822 type = LRU_GEN_FILE; 4823 else if (swappiness == 200) 4824 type = LRU_GEN_ANON; 4825 else 4826 type = get_type_to_scan(lruvec, swappiness, &tier); 4827 4828 for (i = !swappiness; i < ANON_AND_FILE; i++) { 4829 if (tier < 0) 4830 tier = get_tier_idx(lruvec, type); 4831 4832 scanned = scan_folios(lruvec, sc, type, tier, list); 4833 if (scanned) 4834 break; 4835 4836 type = !type; 4837 tier = -1; 4838 } 4839 4840 *type_scanned = type; 4841 4842 return scanned; 4843 } 4844 4845 static int evict_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness) 4846 { 4847 int type; 4848 int scanned; 4849 int reclaimed; 4850 LIST_HEAD(list); 4851 struct folio *folio; 4852 enum vm_event_item item; 4853 struct reclaim_stat stat; 4854 struct lru_gen_mm_walk *walk; 4855 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 4856 struct pglist_data *pgdat = lruvec_pgdat(lruvec); 4857 4858 spin_lock_irq(&lruvec->lru_lock); 4859 4860 scanned = isolate_folios(lruvec, sc, swappiness, &type, &list); 4861 4862 scanned += try_to_inc_min_seq(lruvec, swappiness); 4863 4864 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS) 4865 scanned = 0; 4866 4867 spin_unlock_irq(&lruvec->lru_lock); 4868 4869 if (list_empty(&list)) 4870 return scanned; 4871 4872 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false); 4873 4874 list_for_each_entry(folio, &list, lru) { 4875 /* restore LRU_REFS_FLAGS cleared by isolate_folio() */ 4876 if (folio_test_workingset(folio)) 4877 folio_set_referenced(folio); 4878 4879 /* don't add rejected pages to the oldest generation */ 4880 if (folio_test_reclaim(folio) && 4881 (folio_test_dirty(folio) || folio_test_writeback(folio))) 4882 folio_clear_active(folio); 4883 else 4884 folio_set_active(folio); 4885 } 4886 4887 spin_lock_irq(&lruvec->lru_lock); 4888 4889 move_pages_to_lru(lruvec, &list); 4890 4891 walk = current->reclaim_state->mm_walk; 4892 if (walk && walk->batched) 4893 reset_batch_size(lruvec, walk); 4894 4895 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT; 4896 if (!cgroup_reclaim(sc)) 4897 __count_vm_events(item, reclaimed); 4898 __count_memcg_events(memcg, item, reclaimed); 4899 __count_vm_events(PGSTEAL_ANON + type, reclaimed); 4900 4901 spin_unlock_irq(&lruvec->lru_lock); 4902 4903 mem_cgroup_uncharge_list(&list); 4904 free_unref_page_list(&list); 4905 4906 sc->nr_reclaimed += reclaimed; 4907 4908 return scanned; 4909 } 4910 4911 /* 4912 * For future optimizations: 4913 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg 4914 * reclaim. 4915 */ 4916 static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, 4917 bool can_swap) 4918 { 4919 bool need_aging; 4920 unsigned long nr_to_scan; 4921 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 4922 DEFINE_MAX_SEQ(lruvec); 4923 DEFINE_MIN_SEQ(lruvec); 4924 4925 if (mem_cgroup_below_min(memcg) || 4926 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim)) 4927 return 0; 4928 4929 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, can_swap, &nr_to_scan); 4930 if (!need_aging) 4931 return nr_to_scan; 4932 4933 /* skip the aging path at the default priority */ 4934 if (sc->priority == DEF_PRIORITY) 4935 goto done; 4936 4937 /* leave the work to lru_gen_age_node() */ 4938 if (current_is_kswapd()) 4939 return 0; 4940 4941 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap)) 4942 return nr_to_scan; 4943 done: 4944 return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0; 4945 } 4946 4947 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc) 4948 { 4949 struct blk_plug plug; 4950 unsigned long scanned = 0; 4951 4952 lru_add_drain(); 4953 4954 blk_start_plug(&plug); 4955 4956 set_mm_walk(lruvec_pgdat(lruvec)); 4957 4958 while (true) { 4959 int delta; 4960 int swappiness; 4961 unsigned long nr_to_scan; 4962 4963 if (sc->may_swap) 4964 swappiness = get_swappiness(lruvec, sc); 4965 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc)) 4966 swappiness = 1; 4967 else 4968 swappiness = 0; 4969 4970 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness); 4971 if (!nr_to_scan) 4972 break; 4973 4974 delta = evict_folios(lruvec, sc, swappiness); 4975 if (!delta) 4976 break; 4977 4978 scanned += delta; 4979 if (scanned >= nr_to_scan) 4980 break; 4981 4982 cond_resched(); 4983 } 4984 4985 clear_mm_walk(); 4986 4987 blk_finish_plug(&plug); 4988 } 4989 4990 /****************************************************************************** 4991 * initialization 4992 ******************************************************************************/ 4993 4994 void lru_gen_init_lruvec(struct lruvec *lruvec) 4995 { 4996 int gen, type, zone; 4997 struct lru_gen_struct *lrugen = &lruvec->lrugen; 4998 4999 lrugen->max_seq = MIN_NR_GENS + 1; 5000 5001 for_each_gen_type_zone(gen, type, zone) 5002 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]); 5003 5004 lruvec->mm_state.seq = MIN_NR_GENS; 5005 init_waitqueue_head(&lruvec->mm_state.wait); 5006 } 5007 5008 #ifdef CONFIG_MEMCG 5009 void lru_gen_init_memcg(struct mem_cgroup *memcg) 5010 { 5011 INIT_LIST_HEAD(&memcg->mm_list.fifo); 5012 spin_lock_init(&memcg->mm_list.lock); 5013 } 5014 5015 void lru_gen_exit_memcg(struct mem_cgroup *memcg) 5016 { 5017 int i; 5018 int nid; 5019 5020 for_each_node(nid) { 5021 struct lruvec *lruvec = get_lruvec(memcg, nid); 5022 5023 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0, 5024 sizeof(lruvec->lrugen.nr_pages))); 5025 5026 for (i = 0; i < NR_BLOOM_FILTERS; i++) { 5027 bitmap_free(lruvec->mm_state.filters[i]); 5028 lruvec->mm_state.filters[i] = NULL; 5029 } 5030 } 5031 } 5032 #endif 5033 5034 static int __init init_lru_gen(void) 5035 { 5036 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS); 5037 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS); 5038 5039 return 0; 5040 }; 5041 late_initcall(init_lru_gen); 5042 5043 #else /* !CONFIG_LRU_GEN */ 5044 5045 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc) 5046 { 5047 } 5048 5049 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc) 5050 { 5051 } 5052 5053 #endif /* CONFIG_LRU_GEN */ 5054 5055 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc) 5056 { 5057 unsigned long nr[NR_LRU_LISTS]; 5058 unsigned long targets[NR_LRU_LISTS]; 5059 unsigned long nr_to_scan; 5060 enum lru_list lru; 5061 unsigned long nr_reclaimed = 0; 5062 unsigned long nr_to_reclaim = sc->nr_to_reclaim; 5063 struct blk_plug plug; 5064 bool scan_adjusted; 5065 5066 if (lru_gen_enabled()) { 5067 lru_gen_shrink_lruvec(lruvec, sc); 5068 return; 5069 } 5070 5071 get_scan_count(lruvec, sc, nr); 5072 5073 /* Record the original scan target for proportional adjustments later */ 5074 memcpy(targets, nr, sizeof(nr)); 5075 5076 /* 5077 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal 5078 * event that can occur when there is little memory pressure e.g. 5079 * multiple streaming readers/writers. Hence, we do not abort scanning 5080 * when the requested number of pages are reclaimed when scanning at 5081 * DEF_PRIORITY on the assumption that the fact we are direct 5082 * reclaiming implies that kswapd is not keeping up and it is best to 5083 * do a batch of work at once. For memcg reclaim one check is made to 5084 * abort proportional reclaim if either the file or anon lru has already 5085 * dropped to zero at the first pass. 5086 */ 5087 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() && 5088 sc->priority == DEF_PRIORITY); 5089 5090 blk_start_plug(&plug); 5091 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] || 5092 nr[LRU_INACTIVE_FILE]) { 5093 unsigned long nr_anon, nr_file, percentage; 5094 unsigned long nr_scanned; 5095 5096 for_each_evictable_lru(lru) { 5097 if (nr[lru]) { 5098 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX); 5099 nr[lru] -= nr_to_scan; 5100 5101 nr_reclaimed += shrink_list(lru, nr_to_scan, 5102 lruvec, sc); 5103 } 5104 } 5105 5106 cond_resched(); 5107 5108 if (nr_reclaimed < nr_to_reclaim || scan_adjusted) 5109 continue; 5110 5111 /* 5112 * For kswapd and memcg, reclaim at least the number of pages 5113 * requested. Ensure that the anon and file LRUs are scanned 5114 * proportionally what was requested by get_scan_count(). We 5115 * stop reclaiming one LRU and reduce the amount scanning 5116 * proportional to the original scan target. 5117 */ 5118 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE]; 5119 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON]; 5120 5121 /* 5122 * It's just vindictive to attack the larger once the smaller 5123 * has gone to zero. And given the way we stop scanning the 5124 * smaller below, this makes sure that we only make one nudge 5125 * towards proportionality once we've got nr_to_reclaim. 5126 */ 5127 if (!nr_file || !nr_anon) 5128 break; 5129 5130 if (nr_file > nr_anon) { 5131 unsigned long scan_target = targets[LRU_INACTIVE_ANON] + 5132 targets[LRU_ACTIVE_ANON] + 1; 5133 lru = LRU_BASE; 5134 percentage = nr_anon * 100 / scan_target; 5135 } else { 5136 unsigned long scan_target = targets[LRU_INACTIVE_FILE] + 5137 targets[LRU_ACTIVE_FILE] + 1; 5138 lru = LRU_FILE; 5139 percentage = nr_file * 100 / scan_target; 5140 } 5141 5142 /* Stop scanning the smaller of the LRU */ 5143 nr[lru] = 0; 5144 nr[lru + LRU_ACTIVE] = 0; 5145 5146 /* 5147 * Recalculate the other LRU scan count based on its original 5148 * scan target and the percentage scanning already complete 5149 */ 5150 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE; 5151 nr_scanned = targets[lru] - nr[lru]; 5152 nr[lru] = targets[lru] * (100 - percentage) / 100; 5153 nr[lru] -= min(nr[lru], nr_scanned); 5154 5155 lru += LRU_ACTIVE; 5156 nr_scanned = targets[lru] - nr[lru]; 5157 nr[lru] = targets[lru] * (100 - percentage) / 100; 5158 nr[lru] -= min(nr[lru], nr_scanned); 5159 5160 scan_adjusted = true; 5161 } 5162 blk_finish_plug(&plug); 5163 sc->nr_reclaimed += nr_reclaimed; 5164 5165 /* 5166 * Even if we did not try to evict anon pages at all, we want to 5167 * rebalance the anon lru active/inactive ratio. 5168 */ 5169 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) && 5170 inactive_is_low(lruvec, LRU_INACTIVE_ANON)) 5171 shrink_active_list(SWAP_CLUSTER_MAX, lruvec, 5172 sc, LRU_ACTIVE_ANON); 5173 } 5174 5175 /* Use reclaim/compaction for costly allocs or under memory pressure */ 5176 static bool in_reclaim_compaction(struct scan_control *sc) 5177 { 5178 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order && 5179 (sc->order > PAGE_ALLOC_COSTLY_ORDER || 5180 sc->priority < DEF_PRIORITY - 2)) 5181 return true; 5182 5183 return false; 5184 } 5185 5186 /* 5187 * Reclaim/compaction is used for high-order allocation requests. It reclaims 5188 * order-0 pages before compacting the zone. should_continue_reclaim() returns 5189 * true if more pages should be reclaimed such that when the page allocator 5190 * calls try_to_compact_pages() that it will have enough free pages to succeed. 5191 * It will give up earlier than that if there is difficulty reclaiming pages. 5192 */ 5193 static inline bool should_continue_reclaim(struct pglist_data *pgdat, 5194 unsigned long nr_reclaimed, 5195 struct scan_control *sc) 5196 { 5197 unsigned long pages_for_compaction; 5198 unsigned long inactive_lru_pages; 5199 int z; 5200 5201 /* If not in reclaim/compaction mode, stop */ 5202 if (!in_reclaim_compaction(sc)) 5203 return false; 5204 5205 /* 5206 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX 5207 * number of pages that were scanned. This will return to the caller 5208 * with the risk reclaim/compaction and the resulting allocation attempt 5209 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL 5210 * allocations through requiring that the full LRU list has been scanned 5211 * first, by assuming that zero delta of sc->nr_scanned means full LRU 5212 * scan, but that approximation was wrong, and there were corner cases 5213 * where always a non-zero amount of pages were scanned. 5214 */ 5215 if (!nr_reclaimed) 5216 return false; 5217 5218 /* If compaction would go ahead or the allocation would succeed, stop */ 5219 for (z = 0; z <= sc->reclaim_idx; z++) { 5220 struct zone *zone = &pgdat->node_zones[z]; 5221 if (!managed_zone(zone)) 5222 continue; 5223 5224 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) { 5225 case COMPACT_SUCCESS: 5226 case COMPACT_CONTINUE: 5227 return false; 5228 default: 5229 /* check next zone */ 5230 ; 5231 } 5232 } 5233 5234 /* 5235 * If we have not reclaimed enough pages for compaction and the 5236 * inactive lists are large enough, continue reclaiming 5237 */ 5238 pages_for_compaction = compact_gap(sc->order); 5239 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE); 5240 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc)) 5241 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON); 5242 5243 return inactive_lru_pages > pages_for_compaction; 5244 } 5245 5246 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc) 5247 { 5248 struct mem_cgroup *target_memcg = sc->target_mem_cgroup; 5249 struct mem_cgroup *memcg; 5250 5251 memcg = mem_cgroup_iter(target_memcg, NULL, NULL); 5252 do { 5253 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat); 5254 unsigned long reclaimed; 5255 unsigned long scanned; 5256 5257 /* 5258 * This loop can become CPU-bound when target memcgs 5259 * aren't eligible for reclaim - either because they 5260 * don't have any reclaimable pages, or because their 5261 * memory is explicitly protected. Avoid soft lockups. 5262 */ 5263 cond_resched(); 5264 5265 mem_cgroup_calculate_protection(target_memcg, memcg); 5266 5267 if (mem_cgroup_below_min(memcg)) { 5268 /* 5269 * Hard protection. 5270 * If there is no reclaimable memory, OOM. 5271 */ 5272 continue; 5273 } else if (mem_cgroup_below_low(memcg)) { 5274 /* 5275 * Soft protection. 5276 * Respect the protection only as long as 5277 * there is an unprotected supply 5278 * of reclaimable memory from other cgroups. 5279 */ 5280 if (!sc->memcg_low_reclaim) { 5281 sc->memcg_low_skipped = 1; 5282 continue; 5283 } 5284 memcg_memory_event(memcg, MEMCG_LOW); 5285 } 5286 5287 reclaimed = sc->nr_reclaimed; 5288 scanned = sc->nr_scanned; 5289 5290 shrink_lruvec(lruvec, sc); 5291 5292 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, 5293 sc->priority); 5294 5295 /* Record the group's reclaim efficiency */ 5296 if (!sc->proactive) 5297 vmpressure(sc->gfp_mask, memcg, false, 5298 sc->nr_scanned - scanned, 5299 sc->nr_reclaimed - reclaimed); 5300 5301 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL))); 5302 } 5303 5304 static void shrink_node(pg_data_t *pgdat, struct scan_control *sc) 5305 { 5306 struct reclaim_state *reclaim_state = current->reclaim_state; 5307 unsigned long nr_reclaimed, nr_scanned; 5308 struct lruvec *target_lruvec; 5309 bool reclaimable = false; 5310 5311 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat); 5312 5313 again: 5314 memset(&sc->nr, 0, sizeof(sc->nr)); 5315 5316 nr_reclaimed = sc->nr_reclaimed; 5317 nr_scanned = sc->nr_scanned; 5318 5319 prepare_scan_count(pgdat, sc); 5320 5321 shrink_node_memcgs(pgdat, sc); 5322 5323 if (reclaim_state) { 5324 sc->nr_reclaimed += reclaim_state->reclaimed_slab; 5325 reclaim_state->reclaimed_slab = 0; 5326 } 5327 5328 /* Record the subtree's reclaim efficiency */ 5329 if (!sc->proactive) 5330 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true, 5331 sc->nr_scanned - nr_scanned, 5332 sc->nr_reclaimed - nr_reclaimed); 5333 5334 if (sc->nr_reclaimed - nr_reclaimed) 5335 reclaimable = true; 5336 5337 if (current_is_kswapd()) { 5338 /* 5339 * If reclaim is isolating dirty pages under writeback, 5340 * it implies that the long-lived page allocation rate 5341 * is exceeding the page laundering rate. Either the 5342 * global limits are not being effective at throttling 5343 * processes due to the page distribution throughout 5344 * zones or there is heavy usage of a slow backing 5345 * device. The only option is to throttle from reclaim 5346 * context which is not ideal as there is no guarantee 5347 * the dirtying process is throttled in the same way 5348 * balance_dirty_pages() manages. 5349 * 5350 * Once a node is flagged PGDAT_WRITEBACK, kswapd will 5351 * count the number of pages under pages flagged for 5352 * immediate reclaim and stall if any are encountered 5353 * in the nr_immediate check below. 5354 */ 5355 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken) 5356 set_bit(PGDAT_WRITEBACK, &pgdat->flags); 5357 5358 /* Allow kswapd to start writing pages during reclaim.*/ 5359 if (sc->nr.unqueued_dirty == sc->nr.file_taken) 5360 set_bit(PGDAT_DIRTY, &pgdat->flags); 5361 5362 /* 5363 * If kswapd scans pages marked for immediate 5364 * reclaim and under writeback (nr_immediate), it 5365 * implies that pages are cycling through the LRU 5366 * faster than they are written so forcibly stall 5367 * until some pages complete writeback. 5368 */ 5369 if (sc->nr.immediate) 5370 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK); 5371 } 5372 5373 /* 5374 * Tag a node/memcg as congested if all the dirty pages were marked 5375 * for writeback and immediate reclaim (counted in nr.congested). 5376 * 5377 * Legacy memcg will stall in page writeback so avoid forcibly 5378 * stalling in reclaim_throttle(). 5379 */ 5380 if ((current_is_kswapd() || 5381 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) && 5382 sc->nr.dirty && sc->nr.dirty == sc->nr.congested) 5383 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags); 5384 5385 /* 5386 * Stall direct reclaim for IO completions if the lruvec is 5387 * node is congested. Allow kswapd to continue until it 5388 * starts encountering unqueued dirty pages or cycling through 5389 * the LRU too quickly. 5390 */ 5391 if (!current_is_kswapd() && current_may_throttle() && 5392 !sc->hibernation_mode && 5393 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags)) 5394 reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED); 5395 5396 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed, 5397 sc)) 5398 goto again; 5399 5400 /* 5401 * Kswapd gives up on balancing particular nodes after too 5402 * many failures to reclaim anything from them and goes to 5403 * sleep. On reclaim progress, reset the failure counter. A 5404 * successful direct reclaim run will revive a dormant kswapd. 5405 */ 5406 if (reclaimable) 5407 pgdat->kswapd_failures = 0; 5408 } 5409 5410 /* 5411 * Returns true if compaction should go ahead for a costly-order request, or 5412 * the allocation would already succeed without compaction. Return false if we 5413 * should reclaim first. 5414 */ 5415 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc) 5416 { 5417 unsigned long watermark; 5418 enum compact_result suitable; 5419 5420 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx); 5421 if (suitable == COMPACT_SUCCESS) 5422 /* Allocation should succeed already. Don't reclaim. */ 5423 return true; 5424 if (suitable == COMPACT_SKIPPED) 5425 /* Compaction cannot yet proceed. Do reclaim. */ 5426 return false; 5427 5428 /* 5429 * Compaction is already possible, but it takes time to run and there 5430 * are potentially other callers using the pages just freed. So proceed 5431 * with reclaim to make a buffer of free pages available to give 5432 * compaction a reasonable chance of completing and allocating the page. 5433 * Note that we won't actually reclaim the whole buffer in one attempt 5434 * as the target watermark in should_continue_reclaim() is lower. But if 5435 * we are already above the high+gap watermark, don't reclaim at all. 5436 */ 5437 watermark = high_wmark_pages(zone) + compact_gap(sc->order); 5438 5439 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx); 5440 } 5441 5442 static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc) 5443 { 5444 /* 5445 * If reclaim is making progress greater than 12% efficiency then 5446 * wake all the NOPROGRESS throttled tasks. 5447 */ 5448 if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) { 5449 wait_queue_head_t *wqh; 5450 5451 wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS]; 5452 if (waitqueue_active(wqh)) 5453 wake_up(wqh); 5454 5455 return; 5456 } 5457 5458 /* 5459 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will 5460 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages 5461 * under writeback and marked for immediate reclaim at the tail of the 5462 * LRU. 5463 */ 5464 if (current_is_kswapd() || cgroup_reclaim(sc)) 5465 return; 5466 5467 /* Throttle if making no progress at high prioities. */ 5468 if (sc->priority == 1 && !sc->nr_reclaimed) 5469 reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS); 5470 } 5471 5472 /* 5473 * This is the direct reclaim path, for page-allocating processes. We only 5474 * try to reclaim pages from zones which will satisfy the caller's allocation 5475 * request. 5476 * 5477 * If a zone is deemed to be full of pinned pages then just give it a light 5478 * scan then give up on it. 5479 */ 5480 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc) 5481 { 5482 struct zoneref *z; 5483 struct zone *zone; 5484 unsigned long nr_soft_reclaimed; 5485 unsigned long nr_soft_scanned; 5486 gfp_t orig_mask; 5487 pg_data_t *last_pgdat = NULL; 5488 pg_data_t *first_pgdat = NULL; 5489 5490 /* 5491 * If the number of buffer_heads in the machine exceeds the maximum 5492 * allowed level, force direct reclaim to scan the highmem zone as 5493 * highmem pages could be pinning lowmem pages storing buffer_heads 5494 */ 5495 orig_mask = sc->gfp_mask; 5496 if (buffer_heads_over_limit) { 5497 sc->gfp_mask |= __GFP_HIGHMEM; 5498 sc->reclaim_idx = gfp_zone(sc->gfp_mask); 5499 } 5500 5501 for_each_zone_zonelist_nodemask(zone, z, zonelist, 5502 sc->reclaim_idx, sc->nodemask) { 5503 /* 5504 * Take care memory controller reclaiming has small influence 5505 * to global LRU. 5506 */ 5507 if (!cgroup_reclaim(sc)) { 5508 if (!cpuset_zone_allowed(zone, 5509 GFP_KERNEL | __GFP_HARDWALL)) 5510 continue; 5511 5512 /* 5513 * If we already have plenty of memory free for 5514 * compaction in this zone, don't free any more. 5515 * Even though compaction is invoked for any 5516 * non-zero order, only frequent costly order 5517 * reclamation is disruptive enough to become a 5518 * noticeable problem, like transparent huge 5519 * page allocations. 5520 */ 5521 if (IS_ENABLED(CONFIG_COMPACTION) && 5522 sc->order > PAGE_ALLOC_COSTLY_ORDER && 5523 compaction_ready(zone, sc)) { 5524 sc->compaction_ready = true; 5525 continue; 5526 } 5527 5528 /* 5529 * Shrink each node in the zonelist once. If the 5530 * zonelist is ordered by zone (not the default) then a 5531 * node may be shrunk multiple times but in that case 5532 * the user prefers lower zones being preserved. 5533 */ 5534 if (zone->zone_pgdat == last_pgdat) 5535 continue; 5536 5537 /* 5538 * This steals pages from memory cgroups over softlimit 5539 * and returns the number of reclaimed pages and 5540 * scanned pages. This works for global memory pressure 5541 * and balancing, not for a memcg's limit. 5542 */ 5543 nr_soft_scanned = 0; 5544 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat, 5545 sc->order, sc->gfp_mask, 5546 &nr_soft_scanned); 5547 sc->nr_reclaimed += nr_soft_reclaimed; 5548 sc->nr_scanned += nr_soft_scanned; 5549 /* need some check for avoid more shrink_zone() */ 5550 } 5551 5552 if (!first_pgdat) 5553 first_pgdat = zone->zone_pgdat; 5554 5555 /* See comment about same check for global reclaim above */ 5556 if (zone->zone_pgdat == last_pgdat) 5557 continue; 5558 last_pgdat = zone->zone_pgdat; 5559 shrink_node(zone->zone_pgdat, sc); 5560 } 5561 5562 if (first_pgdat) 5563 consider_reclaim_throttle(first_pgdat, sc); 5564 5565 /* 5566 * Restore to original mask to avoid the impact on the caller if we 5567 * promoted it to __GFP_HIGHMEM. 5568 */ 5569 sc->gfp_mask = orig_mask; 5570 } 5571 5572 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat) 5573 { 5574 struct lruvec *target_lruvec; 5575 unsigned long refaults; 5576 5577 if (lru_gen_enabled()) 5578 return; 5579 5580 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat); 5581 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON); 5582 target_lruvec->refaults[WORKINGSET_ANON] = refaults; 5583 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE); 5584 target_lruvec->refaults[WORKINGSET_FILE] = refaults; 5585 } 5586 5587 /* 5588 * This is the main entry point to direct page reclaim. 5589 * 5590 * If a full scan of the inactive list fails to free enough memory then we 5591 * are "out of memory" and something needs to be killed. 5592 * 5593 * If the caller is !__GFP_FS then the probability of a failure is reasonably 5594 * high - the zone may be full of dirty or under-writeback pages, which this 5595 * caller can't do much about. We kick the writeback threads and take explicit 5596 * naps in the hope that some of these pages can be written. But if the 5597 * allocating task holds filesystem locks which prevent writeout this might not 5598 * work, and the allocation attempt will fail. 5599 * 5600 * returns: 0, if no pages reclaimed 5601 * else, the number of pages reclaimed 5602 */ 5603 static unsigned long do_try_to_free_pages(struct zonelist *zonelist, 5604 struct scan_control *sc) 5605 { 5606 int initial_priority = sc->priority; 5607 pg_data_t *last_pgdat; 5608 struct zoneref *z; 5609 struct zone *zone; 5610 retry: 5611 delayacct_freepages_start(); 5612 5613 if (!cgroup_reclaim(sc)) 5614 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1); 5615 5616 do { 5617 if (!sc->proactive) 5618 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup, 5619 sc->priority); 5620 sc->nr_scanned = 0; 5621 shrink_zones(zonelist, sc); 5622 5623 if (sc->nr_reclaimed >= sc->nr_to_reclaim) 5624 break; 5625 5626 if (sc->compaction_ready) 5627 break; 5628 5629 /* 5630 * If we're getting trouble reclaiming, start doing 5631 * writepage even in laptop mode. 5632 */ 5633 if (sc->priority < DEF_PRIORITY - 2) 5634 sc->may_writepage = 1; 5635 } while (--sc->priority >= 0); 5636 5637 last_pgdat = NULL; 5638 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx, 5639 sc->nodemask) { 5640 if (zone->zone_pgdat == last_pgdat) 5641 continue; 5642 last_pgdat = zone->zone_pgdat; 5643 5644 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat); 5645 5646 if (cgroup_reclaim(sc)) { 5647 struct lruvec *lruvec; 5648 5649 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, 5650 zone->zone_pgdat); 5651 clear_bit(LRUVEC_CONGESTED, &lruvec->flags); 5652 } 5653 } 5654 5655 delayacct_freepages_end(); 5656 5657 if (sc->nr_reclaimed) 5658 return sc->nr_reclaimed; 5659 5660 /* Aborted reclaim to try compaction? don't OOM, then */ 5661 if (sc->compaction_ready) 5662 return 1; 5663 5664 /* 5665 * We make inactive:active ratio decisions based on the node's 5666 * composition of memory, but a restrictive reclaim_idx or a 5667 * memory.low cgroup setting can exempt large amounts of 5668 * memory from reclaim. Neither of which are very common, so 5669 * instead of doing costly eligibility calculations of the 5670 * entire cgroup subtree up front, we assume the estimates are 5671 * good, and retry with forcible deactivation if that fails. 5672 */ 5673 if (sc->skipped_deactivate) { 5674 sc->priority = initial_priority; 5675 sc->force_deactivate = 1; 5676 sc->skipped_deactivate = 0; 5677 goto retry; 5678 } 5679 5680 /* Untapped cgroup reserves? Don't OOM, retry. */ 5681 if (sc->memcg_low_skipped) { 5682 sc->priority = initial_priority; 5683 sc->force_deactivate = 0; 5684 sc->memcg_low_reclaim = 1; 5685 sc->memcg_low_skipped = 0; 5686 goto retry; 5687 } 5688 5689 return 0; 5690 } 5691 5692 static bool allow_direct_reclaim(pg_data_t *pgdat) 5693 { 5694 struct zone *zone; 5695 unsigned long pfmemalloc_reserve = 0; 5696 unsigned long free_pages = 0; 5697 int i; 5698 bool wmark_ok; 5699 5700 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES) 5701 return true; 5702 5703 for (i = 0; i <= ZONE_NORMAL; i++) { 5704 zone = &pgdat->node_zones[i]; 5705 if (!managed_zone(zone)) 5706 continue; 5707 5708 if (!zone_reclaimable_pages(zone)) 5709 continue; 5710 5711 pfmemalloc_reserve += min_wmark_pages(zone); 5712 free_pages += zone_page_state(zone, NR_FREE_PAGES); 5713 } 5714 5715 /* If there are no reserves (unexpected config) then do not throttle */ 5716 if (!pfmemalloc_reserve) 5717 return true; 5718 5719 wmark_ok = free_pages > pfmemalloc_reserve / 2; 5720 5721 /* kswapd must be awake if processes are being throttled */ 5722 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) { 5723 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL) 5724 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL); 5725 5726 wake_up_interruptible(&pgdat->kswapd_wait); 5727 } 5728 5729 return wmark_ok; 5730 } 5731 5732 /* 5733 * Throttle direct reclaimers if backing storage is backed by the network 5734 * and the PFMEMALLOC reserve for the preferred node is getting dangerously 5735 * depleted. kswapd will continue to make progress and wake the processes 5736 * when the low watermark is reached. 5737 * 5738 * Returns true if a fatal signal was delivered during throttling. If this 5739 * happens, the page allocator should not consider triggering the OOM killer. 5740 */ 5741 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist, 5742 nodemask_t *nodemask) 5743 { 5744 struct zoneref *z; 5745 struct zone *zone; 5746 pg_data_t *pgdat = NULL; 5747 5748 /* 5749 * Kernel threads should not be throttled as they may be indirectly 5750 * responsible for cleaning pages necessary for reclaim to make forward 5751 * progress. kjournald for example may enter direct reclaim while 5752 * committing a transaction where throttling it could forcing other 5753 * processes to block on log_wait_commit(). 5754 */ 5755 if (current->flags & PF_KTHREAD) 5756 goto out; 5757 5758 /* 5759 * If a fatal signal is pending, this process should not throttle. 5760 * It should return quickly so it can exit and free its memory 5761 */ 5762 if (fatal_signal_pending(current)) 5763 goto out; 5764 5765 /* 5766 * Check if the pfmemalloc reserves are ok by finding the first node 5767 * with a usable ZONE_NORMAL or lower zone. The expectation is that 5768 * GFP_KERNEL will be required for allocating network buffers when 5769 * swapping over the network so ZONE_HIGHMEM is unusable. 5770 * 5771 * Throttling is based on the first usable node and throttled processes 5772 * wait on a queue until kswapd makes progress and wakes them. There 5773 * is an affinity then between processes waking up and where reclaim 5774 * progress has been made assuming the process wakes on the same node. 5775 * More importantly, processes running on remote nodes will not compete 5776 * for remote pfmemalloc reserves and processes on different nodes 5777 * should make reasonable progress. 5778 */ 5779 for_each_zone_zonelist_nodemask(zone, z, zonelist, 5780 gfp_zone(gfp_mask), nodemask) { 5781 if (zone_idx(zone) > ZONE_NORMAL) 5782 continue; 5783 5784 /* Throttle based on the first usable node */ 5785 pgdat = zone->zone_pgdat; 5786 if (allow_direct_reclaim(pgdat)) 5787 goto out; 5788 break; 5789 } 5790 5791 /* If no zone was usable by the allocation flags then do not throttle */ 5792 if (!pgdat) 5793 goto out; 5794 5795 /* Account for the throttling */ 5796 count_vm_event(PGSCAN_DIRECT_THROTTLE); 5797 5798 /* 5799 * If the caller cannot enter the filesystem, it's possible that it 5800 * is due to the caller holding an FS lock or performing a journal 5801 * transaction in the case of a filesystem like ext[3|4]. In this case, 5802 * it is not safe to block on pfmemalloc_wait as kswapd could be 5803 * blocked waiting on the same lock. Instead, throttle for up to a 5804 * second before continuing. 5805 */ 5806 if (!(gfp_mask & __GFP_FS)) 5807 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait, 5808 allow_direct_reclaim(pgdat), HZ); 5809 else 5810 /* Throttle until kswapd wakes the process */ 5811 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait, 5812 allow_direct_reclaim(pgdat)); 5813 5814 if (fatal_signal_pending(current)) 5815 return true; 5816 5817 out: 5818 return false; 5819 } 5820 5821 unsigned long try_to_free_pages(struct zonelist *zonelist, int order, 5822 gfp_t gfp_mask, nodemask_t *nodemask) 5823 { 5824 unsigned long nr_reclaimed; 5825 struct scan_control sc = { 5826 .nr_to_reclaim = SWAP_CLUSTER_MAX, 5827 .gfp_mask = current_gfp_context(gfp_mask), 5828 .reclaim_idx = gfp_zone(gfp_mask), 5829 .order = order, 5830 .nodemask = nodemask, 5831 .priority = DEF_PRIORITY, 5832 .may_writepage = !laptop_mode, 5833 .may_unmap = 1, 5834 .may_swap = 1, 5835 }; 5836 5837 /* 5838 * scan_control uses s8 fields for order, priority, and reclaim_idx. 5839 * Confirm they are large enough for max values. 5840 */ 5841 BUILD_BUG_ON(MAX_ORDER > S8_MAX); 5842 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX); 5843 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX); 5844 5845 /* 5846 * Do not enter reclaim if fatal signal was delivered while throttled. 5847 * 1 is returned so that the page allocator does not OOM kill at this 5848 * point. 5849 */ 5850 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask)) 5851 return 1; 5852 5853 set_task_reclaim_state(current, &sc.reclaim_state); 5854 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask); 5855 5856 nr_reclaimed = do_try_to_free_pages(zonelist, &sc); 5857 5858 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed); 5859 set_task_reclaim_state(current, NULL); 5860 5861 return nr_reclaimed; 5862 } 5863 5864 #ifdef CONFIG_MEMCG 5865 5866 /* Only used by soft limit reclaim. Do not reuse for anything else. */ 5867 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg, 5868 gfp_t gfp_mask, bool noswap, 5869 pg_data_t *pgdat, 5870 unsigned long *nr_scanned) 5871 { 5872 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat); 5873 struct scan_control sc = { 5874 .nr_to_reclaim = SWAP_CLUSTER_MAX, 5875 .target_mem_cgroup = memcg, 5876 .may_writepage = !laptop_mode, 5877 .may_unmap = 1, 5878 .reclaim_idx = MAX_NR_ZONES - 1, 5879 .may_swap = !noswap, 5880 }; 5881 5882 WARN_ON_ONCE(!current->reclaim_state); 5883 5884 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) | 5885 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK); 5886 5887 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order, 5888 sc.gfp_mask); 5889 5890 /* 5891 * NOTE: Although we can get the priority field, using it 5892 * here is not a good idea, since it limits the pages we can scan. 5893 * if we don't reclaim here, the shrink_node from balance_pgdat 5894 * will pick up pages from other mem cgroup's as well. We hack 5895 * the priority and make it zero. 5896 */ 5897 shrink_lruvec(lruvec, &sc); 5898 5899 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed); 5900 5901 *nr_scanned = sc.nr_scanned; 5902 5903 return sc.nr_reclaimed; 5904 } 5905 5906 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg, 5907 unsigned long nr_pages, 5908 gfp_t gfp_mask, 5909 unsigned int reclaim_options) 5910 { 5911 unsigned long nr_reclaimed; 5912 unsigned int noreclaim_flag; 5913 struct scan_control sc = { 5914 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX), 5915 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) | 5916 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK), 5917 .reclaim_idx = MAX_NR_ZONES - 1, 5918 .target_mem_cgroup = memcg, 5919 .priority = DEF_PRIORITY, 5920 .may_writepage = !laptop_mode, 5921 .may_unmap = 1, 5922 .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP), 5923 .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE), 5924 }; 5925 /* 5926 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put 5927 * equal pressure on all the nodes. This is based on the assumption that 5928 * the reclaim does not bail out early. 5929 */ 5930 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask); 5931 5932 set_task_reclaim_state(current, &sc.reclaim_state); 5933 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask); 5934 noreclaim_flag = memalloc_noreclaim_save(); 5935 5936 nr_reclaimed = do_try_to_free_pages(zonelist, &sc); 5937 5938 memalloc_noreclaim_restore(noreclaim_flag); 5939 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed); 5940 set_task_reclaim_state(current, NULL); 5941 5942 return nr_reclaimed; 5943 } 5944 #endif 5945 5946 static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc) 5947 { 5948 struct mem_cgroup *memcg; 5949 struct lruvec *lruvec; 5950 5951 if (lru_gen_enabled()) { 5952 lru_gen_age_node(pgdat, sc); 5953 return; 5954 } 5955 5956 if (!can_age_anon_pages(pgdat, sc)) 5957 return; 5958 5959 lruvec = mem_cgroup_lruvec(NULL, pgdat); 5960 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON)) 5961 return; 5962 5963 memcg = mem_cgroup_iter(NULL, NULL, NULL); 5964 do { 5965 lruvec = mem_cgroup_lruvec(memcg, pgdat); 5966 shrink_active_list(SWAP_CLUSTER_MAX, lruvec, 5967 sc, LRU_ACTIVE_ANON); 5968 memcg = mem_cgroup_iter(NULL, memcg, NULL); 5969 } while (memcg); 5970 } 5971 5972 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx) 5973 { 5974 int i; 5975 struct zone *zone; 5976 5977 /* 5978 * Check for watermark boosts top-down as the higher zones 5979 * are more likely to be boosted. Both watermarks and boosts 5980 * should not be checked at the same time as reclaim would 5981 * start prematurely when there is no boosting and a lower 5982 * zone is balanced. 5983 */ 5984 for (i = highest_zoneidx; i >= 0; i--) { 5985 zone = pgdat->node_zones + i; 5986 if (!managed_zone(zone)) 5987 continue; 5988 5989 if (zone->watermark_boost) 5990 return true; 5991 } 5992 5993 return false; 5994 } 5995 5996 /* 5997 * Returns true if there is an eligible zone balanced for the request order 5998 * and highest_zoneidx 5999 */ 6000 static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx) 6001 { 6002 int i; 6003 unsigned long mark = -1; 6004 struct zone *zone; 6005 6006 /* 6007 * Check watermarks bottom-up as lower zones are more likely to 6008 * meet watermarks. 6009 */ 6010 for (i = 0; i <= highest_zoneidx; i++) { 6011 zone = pgdat->node_zones + i; 6012 6013 if (!managed_zone(zone)) 6014 continue; 6015 6016 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) 6017 mark = wmark_pages(zone, WMARK_PROMO); 6018 else 6019 mark = high_wmark_pages(zone); 6020 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx)) 6021 return true; 6022 } 6023 6024 /* 6025 * If a node has no managed zone within highest_zoneidx, it does not 6026 * need balancing by definition. This can happen if a zone-restricted 6027 * allocation tries to wake a remote kswapd. 6028 */ 6029 if (mark == -1) 6030 return true; 6031 6032 return false; 6033 } 6034 6035 /* Clear pgdat state for congested, dirty or under writeback. */ 6036 static void clear_pgdat_congested(pg_data_t *pgdat) 6037 { 6038 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat); 6039 6040 clear_bit(LRUVEC_CONGESTED, &lruvec->flags); 6041 clear_bit(PGDAT_DIRTY, &pgdat->flags); 6042 clear_bit(PGDAT_WRITEBACK, &pgdat->flags); 6043 } 6044 6045 /* 6046 * Prepare kswapd for sleeping. This verifies that there are no processes 6047 * waiting in throttle_direct_reclaim() and that watermarks have been met. 6048 * 6049 * Returns true if kswapd is ready to sleep 6050 */ 6051 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, 6052 int highest_zoneidx) 6053 { 6054 /* 6055 * The throttled processes are normally woken up in balance_pgdat() as 6056 * soon as allow_direct_reclaim() is true. But there is a potential 6057 * race between when kswapd checks the watermarks and a process gets 6058 * throttled. There is also a potential race if processes get 6059 * throttled, kswapd wakes, a large process exits thereby balancing the 6060 * zones, which causes kswapd to exit balance_pgdat() before reaching 6061 * the wake up checks. If kswapd is going to sleep, no process should 6062 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If 6063 * the wake up is premature, processes will wake kswapd and get 6064 * throttled again. The difference from wake ups in balance_pgdat() is 6065 * that here we are under prepare_to_wait(). 6066 */ 6067 if (waitqueue_active(&pgdat->pfmemalloc_wait)) 6068 wake_up_all(&pgdat->pfmemalloc_wait); 6069 6070 /* Hopeless node, leave it to direct reclaim */ 6071 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES) 6072 return true; 6073 6074 if (pgdat_balanced(pgdat, order, highest_zoneidx)) { 6075 clear_pgdat_congested(pgdat); 6076 return true; 6077 } 6078 6079 return false; 6080 } 6081 6082 /* 6083 * kswapd shrinks a node of pages that are at or below the highest usable 6084 * zone that is currently unbalanced. 6085 * 6086 * Returns true if kswapd scanned at least the requested number of pages to 6087 * reclaim or if the lack of progress was due to pages under writeback. 6088 * This is used to determine if the scanning priority needs to be raised. 6089 */ 6090 static bool kswapd_shrink_node(pg_data_t *pgdat, 6091 struct scan_control *sc) 6092 { 6093 struct zone *zone; 6094 int z; 6095 6096 /* Reclaim a number of pages proportional to the number of zones */ 6097 sc->nr_to_reclaim = 0; 6098 for (z = 0; z <= sc->reclaim_idx; z++) { 6099 zone = pgdat->node_zones + z; 6100 if (!managed_zone(zone)) 6101 continue; 6102 6103 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX); 6104 } 6105 6106 /* 6107 * Historically care was taken to put equal pressure on all zones but 6108 * now pressure is applied based on node LRU order. 6109 */ 6110 shrink_node(pgdat, sc); 6111 6112 /* 6113 * Fragmentation may mean that the system cannot be rebalanced for 6114 * high-order allocations. If twice the allocation size has been 6115 * reclaimed then recheck watermarks only at order-0 to prevent 6116 * excessive reclaim. Assume that a process requested a high-order 6117 * can direct reclaim/compact. 6118 */ 6119 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order)) 6120 sc->order = 0; 6121 6122 return sc->nr_scanned >= sc->nr_to_reclaim; 6123 } 6124 6125 /* Page allocator PCP high watermark is lowered if reclaim is active. */ 6126 static inline void 6127 update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active) 6128 { 6129 int i; 6130 struct zone *zone; 6131 6132 for (i = 0; i <= highest_zoneidx; i++) { 6133 zone = pgdat->node_zones + i; 6134 6135 if (!managed_zone(zone)) 6136 continue; 6137 6138 if (active) 6139 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags); 6140 else 6141 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags); 6142 } 6143 } 6144 6145 static inline void 6146 set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx) 6147 { 6148 update_reclaim_active(pgdat, highest_zoneidx, true); 6149 } 6150 6151 static inline void 6152 clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx) 6153 { 6154 update_reclaim_active(pgdat, highest_zoneidx, false); 6155 } 6156 6157 /* 6158 * For kswapd, balance_pgdat() will reclaim pages across a node from zones 6159 * that are eligible for use by the caller until at least one zone is 6160 * balanced. 6161 * 6162 * Returns the order kswapd finished reclaiming at. 6163 * 6164 * kswapd scans the zones in the highmem->normal->dma direction. It skips 6165 * zones which have free_pages > high_wmark_pages(zone), but once a zone is 6166 * found to have free_pages <= high_wmark_pages(zone), any page in that zone 6167 * or lower is eligible for reclaim until at least one usable zone is 6168 * balanced. 6169 */ 6170 static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx) 6171 { 6172 int i; 6173 unsigned long nr_soft_reclaimed; 6174 unsigned long nr_soft_scanned; 6175 unsigned long pflags; 6176 unsigned long nr_boost_reclaim; 6177 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, }; 6178 bool boosted; 6179 struct zone *zone; 6180 struct scan_control sc = { 6181 .gfp_mask = GFP_KERNEL, 6182 .order = order, 6183 .may_unmap = 1, 6184 }; 6185 6186 set_task_reclaim_state(current, &sc.reclaim_state); 6187 psi_memstall_enter(&pflags); 6188 __fs_reclaim_acquire(_THIS_IP_); 6189 6190 count_vm_event(PAGEOUTRUN); 6191 6192 /* 6193 * Account for the reclaim boost. Note that the zone boost is left in 6194 * place so that parallel allocations that are near the watermark will 6195 * stall or direct reclaim until kswapd is finished. 6196 */ 6197 nr_boost_reclaim = 0; 6198 for (i = 0; i <= highest_zoneidx; i++) { 6199 zone = pgdat->node_zones + i; 6200 if (!managed_zone(zone)) 6201 continue; 6202 6203 nr_boost_reclaim += zone->watermark_boost; 6204 zone_boosts[i] = zone->watermark_boost; 6205 } 6206 boosted = nr_boost_reclaim; 6207 6208 restart: 6209 set_reclaim_active(pgdat, highest_zoneidx); 6210 sc.priority = DEF_PRIORITY; 6211 do { 6212 unsigned long nr_reclaimed = sc.nr_reclaimed; 6213 bool raise_priority = true; 6214 bool balanced; 6215 bool ret; 6216 6217 sc.reclaim_idx = highest_zoneidx; 6218 6219 /* 6220 * If the number of buffer_heads exceeds the maximum allowed 6221 * then consider reclaiming from all zones. This has a dual 6222 * purpose -- on 64-bit systems it is expected that 6223 * buffer_heads are stripped during active rotation. On 32-bit 6224 * systems, highmem pages can pin lowmem memory and shrinking 6225 * buffers can relieve lowmem pressure. Reclaim may still not 6226 * go ahead if all eligible zones for the original allocation 6227 * request are balanced to avoid excessive reclaim from kswapd. 6228 */ 6229 if (buffer_heads_over_limit) { 6230 for (i = MAX_NR_ZONES - 1; i >= 0; i--) { 6231 zone = pgdat->node_zones + i; 6232 if (!managed_zone(zone)) 6233 continue; 6234 6235 sc.reclaim_idx = i; 6236 break; 6237 } 6238 } 6239 6240 /* 6241 * If the pgdat is imbalanced then ignore boosting and preserve 6242 * the watermarks for a later time and restart. Note that the 6243 * zone watermarks will be still reset at the end of balancing 6244 * on the grounds that the normal reclaim should be enough to 6245 * re-evaluate if boosting is required when kswapd next wakes. 6246 */ 6247 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx); 6248 if (!balanced && nr_boost_reclaim) { 6249 nr_boost_reclaim = 0; 6250 goto restart; 6251 } 6252 6253 /* 6254 * If boosting is not active then only reclaim if there are no 6255 * eligible zones. Note that sc.reclaim_idx is not used as 6256 * buffer_heads_over_limit may have adjusted it. 6257 */ 6258 if (!nr_boost_reclaim && balanced) 6259 goto out; 6260 6261 /* Limit the priority of boosting to avoid reclaim writeback */ 6262 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2) 6263 raise_priority = false; 6264 6265 /* 6266 * Do not writeback or swap pages for boosted reclaim. The 6267 * intent is to relieve pressure not issue sub-optimal IO 6268 * from reclaim context. If no pages are reclaimed, the 6269 * reclaim will be aborted. 6270 */ 6271 sc.may_writepage = !laptop_mode && !nr_boost_reclaim; 6272 sc.may_swap = !nr_boost_reclaim; 6273 6274 /* 6275 * Do some background aging, to give pages a chance to be 6276 * referenced before reclaiming. All pages are rotated 6277 * regardless of classzone as this is about consistent aging. 6278 */ 6279 kswapd_age_node(pgdat, &sc); 6280 6281 /* 6282 * If we're getting trouble reclaiming, start doing writepage 6283 * even in laptop mode. 6284 */ 6285 if (sc.priority < DEF_PRIORITY - 2) 6286 sc.may_writepage = 1; 6287 6288 /* Call soft limit reclaim before calling shrink_node. */ 6289 sc.nr_scanned = 0; 6290 nr_soft_scanned = 0; 6291 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order, 6292 sc.gfp_mask, &nr_soft_scanned); 6293 sc.nr_reclaimed += nr_soft_reclaimed; 6294 6295 /* 6296 * There should be no need to raise the scanning priority if 6297 * enough pages are already being scanned that that high 6298 * watermark would be met at 100% efficiency. 6299 */ 6300 if (kswapd_shrink_node(pgdat, &sc)) 6301 raise_priority = false; 6302 6303 /* 6304 * If the low watermark is met there is no need for processes 6305 * to be throttled on pfmemalloc_wait as they should not be 6306 * able to safely make forward progress. Wake them 6307 */ 6308 if (waitqueue_active(&pgdat->pfmemalloc_wait) && 6309 allow_direct_reclaim(pgdat)) 6310 wake_up_all(&pgdat->pfmemalloc_wait); 6311 6312 /* Check if kswapd should be suspending */ 6313 __fs_reclaim_release(_THIS_IP_); 6314 ret = try_to_freeze(); 6315 __fs_reclaim_acquire(_THIS_IP_); 6316 if (ret || kthread_should_stop()) 6317 break; 6318 6319 /* 6320 * Raise priority if scanning rate is too low or there was no 6321 * progress in reclaiming pages 6322 */ 6323 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed; 6324 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed); 6325 6326 /* 6327 * If reclaim made no progress for a boost, stop reclaim as 6328 * IO cannot be queued and it could be an infinite loop in 6329 * extreme circumstances. 6330 */ 6331 if (nr_boost_reclaim && !nr_reclaimed) 6332 break; 6333 6334 if (raise_priority || !nr_reclaimed) 6335 sc.priority--; 6336 } while (sc.priority >= 1); 6337 6338 if (!sc.nr_reclaimed) 6339 pgdat->kswapd_failures++; 6340 6341 out: 6342 clear_reclaim_active(pgdat, highest_zoneidx); 6343 6344 /* If reclaim was boosted, account for the reclaim done in this pass */ 6345 if (boosted) { 6346 unsigned long flags; 6347 6348 for (i = 0; i <= highest_zoneidx; i++) { 6349 if (!zone_boosts[i]) 6350 continue; 6351 6352 /* Increments are under the zone lock */ 6353 zone = pgdat->node_zones + i; 6354 spin_lock_irqsave(&zone->lock, flags); 6355 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]); 6356 spin_unlock_irqrestore(&zone->lock, flags); 6357 } 6358 6359 /* 6360 * As there is now likely space, wakeup kcompact to defragment 6361 * pageblocks. 6362 */ 6363 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx); 6364 } 6365 6366 snapshot_refaults(NULL, pgdat); 6367 __fs_reclaim_release(_THIS_IP_); 6368 psi_memstall_leave(&pflags); 6369 set_task_reclaim_state(current, NULL); 6370 6371 /* 6372 * Return the order kswapd stopped reclaiming at as 6373 * prepare_kswapd_sleep() takes it into account. If another caller 6374 * entered the allocator slow path while kswapd was awake, order will 6375 * remain at the higher level. 6376 */ 6377 return sc.order; 6378 } 6379 6380 /* 6381 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to 6382 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is 6383 * not a valid index then either kswapd runs for first time or kswapd couldn't 6384 * sleep after previous reclaim attempt (node is still unbalanced). In that 6385 * case return the zone index of the previous kswapd reclaim cycle. 6386 */ 6387 static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat, 6388 enum zone_type prev_highest_zoneidx) 6389 { 6390 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx); 6391 6392 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx; 6393 } 6394 6395 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order, 6396 unsigned int highest_zoneidx) 6397 { 6398 long remaining = 0; 6399 DEFINE_WAIT(wait); 6400 6401 if (freezing(current) || kthread_should_stop()) 6402 return; 6403 6404 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE); 6405 6406 /* 6407 * Try to sleep for a short interval. Note that kcompactd will only be 6408 * woken if it is possible to sleep for a short interval. This is 6409 * deliberate on the assumption that if reclaim cannot keep an 6410 * eligible zone balanced that it's also unlikely that compaction will 6411 * succeed. 6412 */ 6413 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) { 6414 /* 6415 * Compaction records what page blocks it recently failed to 6416 * isolate pages from and skips them in the future scanning. 6417 * When kswapd is going to sleep, it is reasonable to assume 6418 * that pages and compaction may succeed so reset the cache. 6419 */ 6420 reset_isolation_suitable(pgdat); 6421 6422 /* 6423 * We have freed the memory, now we should compact it to make 6424 * allocation of the requested order possible. 6425 */ 6426 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx); 6427 6428 remaining = schedule_timeout(HZ/10); 6429 6430 /* 6431 * If woken prematurely then reset kswapd_highest_zoneidx and 6432 * order. The values will either be from a wakeup request or 6433 * the previous request that slept prematurely. 6434 */ 6435 if (remaining) { 6436 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, 6437 kswapd_highest_zoneidx(pgdat, 6438 highest_zoneidx)); 6439 6440 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order) 6441 WRITE_ONCE(pgdat->kswapd_order, reclaim_order); 6442 } 6443 6444 finish_wait(&pgdat->kswapd_wait, &wait); 6445 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE); 6446 } 6447 6448 /* 6449 * After a short sleep, check if it was a premature sleep. If not, then 6450 * go fully to sleep until explicitly woken up. 6451 */ 6452 if (!remaining && 6453 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) { 6454 trace_mm_vmscan_kswapd_sleep(pgdat->node_id); 6455 6456 /* 6457 * vmstat counters are not perfectly accurate and the estimated 6458 * value for counters such as NR_FREE_PAGES can deviate from the 6459 * true value by nr_online_cpus * threshold. To avoid the zone 6460 * watermarks being breached while under pressure, we reduce the 6461 * per-cpu vmstat threshold while kswapd is awake and restore 6462 * them before going back to sleep. 6463 */ 6464 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold); 6465 6466 if (!kthread_should_stop()) 6467 schedule(); 6468 6469 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold); 6470 } else { 6471 if (remaining) 6472 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY); 6473 else 6474 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY); 6475 } 6476 finish_wait(&pgdat->kswapd_wait, &wait); 6477 } 6478 6479 /* 6480 * The background pageout daemon, started as a kernel thread 6481 * from the init process. 6482 * 6483 * This basically trickles out pages so that we have _some_ 6484 * free memory available even if there is no other activity 6485 * that frees anything up. This is needed for things like routing 6486 * etc, where we otherwise might have all activity going on in 6487 * asynchronous contexts that cannot page things out. 6488 * 6489 * If there are applications that are active memory-allocators 6490 * (most normal use), this basically shouldn't matter. 6491 */ 6492 static int kswapd(void *p) 6493 { 6494 unsigned int alloc_order, reclaim_order; 6495 unsigned int highest_zoneidx = MAX_NR_ZONES - 1; 6496 pg_data_t *pgdat = (pg_data_t *)p; 6497 struct task_struct *tsk = current; 6498 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id); 6499 6500 if (!cpumask_empty(cpumask)) 6501 set_cpus_allowed_ptr(tsk, cpumask); 6502 6503 /* 6504 * Tell the memory management that we're a "memory allocator", 6505 * and that if we need more memory we should get access to it 6506 * regardless (see "__alloc_pages()"). "kswapd" should 6507 * never get caught in the normal page freeing logic. 6508 * 6509 * (Kswapd normally doesn't need memory anyway, but sometimes 6510 * you need a small amount of memory in order to be able to 6511 * page out something else, and this flag essentially protects 6512 * us from recursively trying to free more memory as we're 6513 * trying to free the first piece of memory in the first place). 6514 */ 6515 tsk->flags |= PF_MEMALLOC | PF_KSWAPD; 6516 set_freezable(); 6517 6518 WRITE_ONCE(pgdat->kswapd_order, 0); 6519 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES); 6520 atomic_set(&pgdat->nr_writeback_throttled, 0); 6521 for ( ; ; ) { 6522 bool ret; 6523 6524 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order); 6525 highest_zoneidx = kswapd_highest_zoneidx(pgdat, 6526 highest_zoneidx); 6527 6528 kswapd_try_sleep: 6529 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order, 6530 highest_zoneidx); 6531 6532 /* Read the new order and highest_zoneidx */ 6533 alloc_order = READ_ONCE(pgdat->kswapd_order); 6534 highest_zoneidx = kswapd_highest_zoneidx(pgdat, 6535 highest_zoneidx); 6536 WRITE_ONCE(pgdat->kswapd_order, 0); 6537 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES); 6538 6539 ret = try_to_freeze(); 6540 if (kthread_should_stop()) 6541 break; 6542 6543 /* 6544 * We can speed up thawing tasks if we don't call balance_pgdat 6545 * after returning from the refrigerator 6546 */ 6547 if (ret) 6548 continue; 6549 6550 /* 6551 * Reclaim begins at the requested order but if a high-order 6552 * reclaim fails then kswapd falls back to reclaiming for 6553 * order-0. If that happens, kswapd will consider sleeping 6554 * for the order it finished reclaiming at (reclaim_order) 6555 * but kcompactd is woken to compact for the original 6556 * request (alloc_order). 6557 */ 6558 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx, 6559 alloc_order); 6560 reclaim_order = balance_pgdat(pgdat, alloc_order, 6561 highest_zoneidx); 6562 if (reclaim_order < alloc_order) 6563 goto kswapd_try_sleep; 6564 } 6565 6566 tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD); 6567 6568 return 0; 6569 } 6570 6571 /* 6572 * A zone is low on free memory or too fragmented for high-order memory. If 6573 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's 6574 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim 6575 * has failed or is not needed, still wake up kcompactd if only compaction is 6576 * needed. 6577 */ 6578 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order, 6579 enum zone_type highest_zoneidx) 6580 { 6581 pg_data_t *pgdat; 6582 enum zone_type curr_idx; 6583 6584 if (!managed_zone(zone)) 6585 return; 6586 6587 if (!cpuset_zone_allowed(zone, gfp_flags)) 6588 return; 6589 6590 pgdat = zone->zone_pgdat; 6591 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx); 6592 6593 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx) 6594 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx); 6595 6596 if (READ_ONCE(pgdat->kswapd_order) < order) 6597 WRITE_ONCE(pgdat->kswapd_order, order); 6598 6599 if (!waitqueue_active(&pgdat->kswapd_wait)) 6600 return; 6601 6602 /* Hopeless node, leave it to direct reclaim if possible */ 6603 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES || 6604 (pgdat_balanced(pgdat, order, highest_zoneidx) && 6605 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) { 6606 /* 6607 * There may be plenty of free memory available, but it's too 6608 * fragmented for high-order allocations. Wake up kcompactd 6609 * and rely on compaction_suitable() to determine if it's 6610 * needed. If it fails, it will defer subsequent attempts to 6611 * ratelimit its work. 6612 */ 6613 if (!(gfp_flags & __GFP_DIRECT_RECLAIM)) 6614 wakeup_kcompactd(pgdat, order, highest_zoneidx); 6615 return; 6616 } 6617 6618 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order, 6619 gfp_flags); 6620 wake_up_interruptible(&pgdat->kswapd_wait); 6621 } 6622 6623 #ifdef CONFIG_HIBERNATION 6624 /* 6625 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of 6626 * freed pages. 6627 * 6628 * Rather than trying to age LRUs the aim is to preserve the overall 6629 * LRU order by reclaiming preferentially 6630 * inactive > active > active referenced > active mapped 6631 */ 6632 unsigned long shrink_all_memory(unsigned long nr_to_reclaim) 6633 { 6634 struct scan_control sc = { 6635 .nr_to_reclaim = nr_to_reclaim, 6636 .gfp_mask = GFP_HIGHUSER_MOVABLE, 6637 .reclaim_idx = MAX_NR_ZONES - 1, 6638 .priority = DEF_PRIORITY, 6639 .may_writepage = 1, 6640 .may_unmap = 1, 6641 .may_swap = 1, 6642 .hibernation_mode = 1, 6643 }; 6644 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask); 6645 unsigned long nr_reclaimed; 6646 unsigned int noreclaim_flag; 6647 6648 fs_reclaim_acquire(sc.gfp_mask); 6649 noreclaim_flag = memalloc_noreclaim_save(); 6650 set_task_reclaim_state(current, &sc.reclaim_state); 6651 6652 nr_reclaimed = do_try_to_free_pages(zonelist, &sc); 6653 6654 set_task_reclaim_state(current, NULL); 6655 memalloc_noreclaim_restore(noreclaim_flag); 6656 fs_reclaim_release(sc.gfp_mask); 6657 6658 return nr_reclaimed; 6659 } 6660 #endif /* CONFIG_HIBERNATION */ 6661 6662 /* 6663 * This kswapd start function will be called by init and node-hot-add. 6664 */ 6665 void kswapd_run(int nid) 6666 { 6667 pg_data_t *pgdat = NODE_DATA(nid); 6668 6669 pgdat_kswapd_lock(pgdat); 6670 if (!pgdat->kswapd) { 6671 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid); 6672 if (IS_ERR(pgdat->kswapd)) { 6673 /* failure at boot is fatal */ 6674 BUG_ON(system_state < SYSTEM_RUNNING); 6675 pr_err("Failed to start kswapd on node %d\n", nid); 6676 pgdat->kswapd = NULL; 6677 } 6678 } 6679 pgdat_kswapd_unlock(pgdat); 6680 } 6681 6682 /* 6683 * Called by memory hotplug when all memory in a node is offlined. Caller must 6684 * be holding mem_hotplug_begin/done(). 6685 */ 6686 void kswapd_stop(int nid) 6687 { 6688 pg_data_t *pgdat = NODE_DATA(nid); 6689 struct task_struct *kswapd; 6690 6691 pgdat_kswapd_lock(pgdat); 6692 kswapd = pgdat->kswapd; 6693 if (kswapd) { 6694 kthread_stop(kswapd); 6695 pgdat->kswapd = NULL; 6696 } 6697 pgdat_kswapd_unlock(pgdat); 6698 } 6699 6700 static int __init kswapd_init(void) 6701 { 6702 int nid; 6703 6704 swap_setup(); 6705 for_each_node_state(nid, N_MEMORY) 6706 kswapd_run(nid); 6707 return 0; 6708 } 6709 6710 module_init(kswapd_init) 6711 6712 #ifdef CONFIG_NUMA 6713 /* 6714 * Node reclaim mode 6715 * 6716 * If non-zero call node_reclaim when the number of free pages falls below 6717 * the watermarks. 6718 */ 6719 int node_reclaim_mode __read_mostly; 6720 6721 /* 6722 * Priority for NODE_RECLAIM. This determines the fraction of pages 6723 * of a node considered for each zone_reclaim. 4 scans 1/16th of 6724 * a zone. 6725 */ 6726 #define NODE_RECLAIM_PRIORITY 4 6727 6728 /* 6729 * Percentage of pages in a zone that must be unmapped for node_reclaim to 6730 * occur. 6731 */ 6732 int sysctl_min_unmapped_ratio = 1; 6733 6734 /* 6735 * If the number of slab pages in a zone grows beyond this percentage then 6736 * slab reclaim needs to occur. 6737 */ 6738 int sysctl_min_slab_ratio = 5; 6739 6740 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat) 6741 { 6742 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED); 6743 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) + 6744 node_page_state(pgdat, NR_ACTIVE_FILE); 6745 6746 /* 6747 * It's possible for there to be more file mapped pages than 6748 * accounted for by the pages on the file LRU lists because 6749 * tmpfs pages accounted for as ANON can also be FILE_MAPPED 6750 */ 6751 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0; 6752 } 6753 6754 /* Work out how many page cache pages we can reclaim in this reclaim_mode */ 6755 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat) 6756 { 6757 unsigned long nr_pagecache_reclaimable; 6758 unsigned long delta = 0; 6759 6760 /* 6761 * If RECLAIM_UNMAP is set, then all file pages are considered 6762 * potentially reclaimable. Otherwise, we have to worry about 6763 * pages like swapcache and node_unmapped_file_pages() provides 6764 * a better estimate 6765 */ 6766 if (node_reclaim_mode & RECLAIM_UNMAP) 6767 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES); 6768 else 6769 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat); 6770 6771 /* If we can't clean pages, remove dirty pages from consideration */ 6772 if (!(node_reclaim_mode & RECLAIM_WRITE)) 6773 delta += node_page_state(pgdat, NR_FILE_DIRTY); 6774 6775 /* Watch for any possible underflows due to delta */ 6776 if (unlikely(delta > nr_pagecache_reclaimable)) 6777 delta = nr_pagecache_reclaimable; 6778 6779 return nr_pagecache_reclaimable - delta; 6780 } 6781 6782 /* 6783 * Try to free up some pages from this node through reclaim. 6784 */ 6785 static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order) 6786 { 6787 /* Minimum pages needed in order to stay on node */ 6788 const unsigned long nr_pages = 1 << order; 6789 struct task_struct *p = current; 6790 unsigned int noreclaim_flag; 6791 struct scan_control sc = { 6792 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX), 6793 .gfp_mask = current_gfp_context(gfp_mask), 6794 .order = order, 6795 .priority = NODE_RECLAIM_PRIORITY, 6796 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE), 6797 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP), 6798 .may_swap = 1, 6799 .reclaim_idx = gfp_zone(gfp_mask), 6800 }; 6801 unsigned long pflags; 6802 6803 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order, 6804 sc.gfp_mask); 6805 6806 cond_resched(); 6807 psi_memstall_enter(&pflags); 6808 fs_reclaim_acquire(sc.gfp_mask); 6809 /* 6810 * We need to be able to allocate from the reserves for RECLAIM_UNMAP 6811 */ 6812 noreclaim_flag = memalloc_noreclaim_save(); 6813 set_task_reclaim_state(p, &sc.reclaim_state); 6814 6815 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages || 6816 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) { 6817 /* 6818 * Free memory by calling shrink node with increasing 6819 * priorities until we have enough memory freed. 6820 */ 6821 do { 6822 shrink_node(pgdat, &sc); 6823 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0); 6824 } 6825 6826 set_task_reclaim_state(p, NULL); 6827 memalloc_noreclaim_restore(noreclaim_flag); 6828 fs_reclaim_release(sc.gfp_mask); 6829 psi_memstall_leave(&pflags); 6830 6831 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed); 6832 6833 return sc.nr_reclaimed >= nr_pages; 6834 } 6835 6836 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order) 6837 { 6838 int ret; 6839 6840 /* 6841 * Node reclaim reclaims unmapped file backed pages and 6842 * slab pages if we are over the defined limits. 6843 * 6844 * A small portion of unmapped file backed pages is needed for 6845 * file I/O otherwise pages read by file I/O will be immediately 6846 * thrown out if the node is overallocated. So we do not reclaim 6847 * if less than a specified percentage of the node is used by 6848 * unmapped file backed pages. 6849 */ 6850 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages && 6851 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <= 6852 pgdat->min_slab_pages) 6853 return NODE_RECLAIM_FULL; 6854 6855 /* 6856 * Do not scan if the allocation should not be delayed. 6857 */ 6858 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC)) 6859 return NODE_RECLAIM_NOSCAN; 6860 6861 /* 6862 * Only run node reclaim on the local node or on nodes that do not 6863 * have associated processors. This will favor the local processor 6864 * over remote processors and spread off node memory allocations 6865 * as wide as possible. 6866 */ 6867 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id()) 6868 return NODE_RECLAIM_NOSCAN; 6869 6870 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags)) 6871 return NODE_RECLAIM_NOSCAN; 6872 6873 ret = __node_reclaim(pgdat, gfp_mask, order); 6874 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags); 6875 6876 if (!ret) 6877 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED); 6878 6879 return ret; 6880 } 6881 #endif 6882 6883 void check_move_unevictable_pages(struct pagevec *pvec) 6884 { 6885 struct folio_batch fbatch; 6886 unsigned i; 6887 6888 folio_batch_init(&fbatch); 6889 for (i = 0; i < pvec->nr; i++) { 6890 struct page *page = pvec->pages[i]; 6891 6892 if (PageTransTail(page)) 6893 continue; 6894 folio_batch_add(&fbatch, page_folio(page)); 6895 } 6896 check_move_unevictable_folios(&fbatch); 6897 } 6898 EXPORT_SYMBOL_GPL(check_move_unevictable_pages); 6899 6900 /** 6901 * check_move_unevictable_folios - Move evictable folios to appropriate zone 6902 * lru list 6903 * @fbatch: Batch of lru folios to check. 6904 * 6905 * Checks folios for evictability, if an evictable folio is in the unevictable 6906 * lru list, moves it to the appropriate evictable lru list. This function 6907 * should be only used for lru folios. 6908 */ 6909 void check_move_unevictable_folios(struct folio_batch *fbatch) 6910 { 6911 struct lruvec *lruvec = NULL; 6912 int pgscanned = 0; 6913 int pgrescued = 0; 6914 int i; 6915 6916 for (i = 0; i < fbatch->nr; i++) { 6917 struct folio *folio = fbatch->folios[i]; 6918 int nr_pages = folio_nr_pages(folio); 6919 6920 pgscanned += nr_pages; 6921 6922 /* block memcg migration while the folio moves between lrus */ 6923 if (!folio_test_clear_lru(folio)) 6924 continue; 6925 6926 lruvec = folio_lruvec_relock_irq(folio, lruvec); 6927 if (folio_evictable(folio) && folio_test_unevictable(folio)) { 6928 lruvec_del_folio(lruvec, folio); 6929 folio_clear_unevictable(folio); 6930 lruvec_add_folio(lruvec, folio); 6931 pgrescued += nr_pages; 6932 } 6933 folio_set_lru(folio); 6934 } 6935 6936 if (lruvec) { 6937 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued); 6938 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned); 6939 unlock_page_lruvec_irq(lruvec); 6940 } else if (pgscanned) { 6941 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned); 6942 } 6943 } 6944 EXPORT_SYMBOL_GPL(check_move_unevictable_folios); 6945