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