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