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