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