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