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