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