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