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 mmgrab(mm); 2867 2868 return mm; 2869 } 2870 2871 void lru_gen_add_mm(struct mm_struct *mm) 2872 { 2873 int nid; 2874 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm); 2875 struct lru_gen_mm_list *mm_list = get_mm_list(memcg); 2876 2877 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list)); 2878 #ifdef CONFIG_MEMCG 2879 VM_WARN_ON_ONCE(mm->lru_gen.memcg); 2880 mm->lru_gen.memcg = memcg; 2881 #endif 2882 spin_lock(&mm_list->lock); 2883 2884 for_each_node_state(nid, N_MEMORY) { 2885 struct lruvec *lruvec = get_lruvec(memcg, nid); 2886 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec); 2887 2888 /* the first addition since the last iteration */ 2889 if (mm_state->tail == &mm_list->fifo) 2890 mm_state->tail = &mm->lru_gen.list; 2891 } 2892 2893 list_add_tail(&mm->lru_gen.list, &mm_list->fifo); 2894 2895 spin_unlock(&mm_list->lock); 2896 } 2897 2898 void lru_gen_del_mm(struct mm_struct *mm) 2899 { 2900 int nid; 2901 struct lru_gen_mm_list *mm_list; 2902 struct mem_cgroup *memcg = NULL; 2903 2904 if (list_empty(&mm->lru_gen.list)) 2905 return; 2906 2907 #ifdef CONFIG_MEMCG 2908 memcg = mm->lru_gen.memcg; 2909 #endif 2910 mm_list = get_mm_list(memcg); 2911 2912 spin_lock(&mm_list->lock); 2913 2914 for_each_node(nid) { 2915 struct lruvec *lruvec = get_lruvec(memcg, nid); 2916 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec); 2917 2918 /* where the current iteration continues after */ 2919 if (mm_state->head == &mm->lru_gen.list) 2920 mm_state->head = mm_state->head->prev; 2921 2922 /* where the last iteration ended before */ 2923 if (mm_state->tail == &mm->lru_gen.list) 2924 mm_state->tail = mm_state->tail->next; 2925 } 2926 2927 list_del_init(&mm->lru_gen.list); 2928 2929 spin_unlock(&mm_list->lock); 2930 2931 #ifdef CONFIG_MEMCG 2932 mem_cgroup_put(mm->lru_gen.memcg); 2933 mm->lru_gen.memcg = NULL; 2934 #endif 2935 } 2936 2937 #ifdef CONFIG_MEMCG 2938 void lru_gen_migrate_mm(struct mm_struct *mm) 2939 { 2940 struct mem_cgroup *memcg; 2941 struct task_struct *task = rcu_dereference_protected(mm->owner, true); 2942 2943 VM_WARN_ON_ONCE(task->mm != mm); 2944 lockdep_assert_held(&task->alloc_lock); 2945 2946 /* for mm_update_next_owner() */ 2947 if (mem_cgroup_disabled()) 2948 return; 2949 2950 /* migration can happen before addition */ 2951 if (!mm->lru_gen.memcg) 2952 return; 2953 2954 rcu_read_lock(); 2955 memcg = mem_cgroup_from_task(task); 2956 rcu_read_unlock(); 2957 if (memcg == mm->lru_gen.memcg) 2958 return; 2959 2960 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list)); 2961 2962 lru_gen_del_mm(mm); 2963 lru_gen_add_mm(mm); 2964 } 2965 #endif 2966 2967 #else /* !CONFIG_LRU_GEN_WALKS_MMU */ 2968 2969 static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg) 2970 { 2971 return NULL; 2972 } 2973 2974 static struct lru_gen_mm_state *get_mm_state(struct lruvec *lruvec) 2975 { 2976 return NULL; 2977 } 2978 2979 static struct mm_struct *get_next_mm(struct lru_gen_mm_walk *walk) 2980 { 2981 return NULL; 2982 } 2983 2984 #endif 2985 2986 static void reset_mm_stats(struct lru_gen_mm_walk *walk, bool last) 2987 { 2988 int i; 2989 int hist; 2990 struct lruvec *lruvec = walk->lruvec; 2991 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec); 2992 2993 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock); 2994 2995 hist = lru_hist_from_seq(walk->seq); 2996 2997 for (i = 0; i < NR_MM_STATS; i++) { 2998 WRITE_ONCE(mm_state->stats[hist][i], 2999 mm_state->stats[hist][i] + walk->mm_stats[i]); 3000 walk->mm_stats[i] = 0; 3001 } 3002 3003 if (NR_HIST_GENS > 1 && last) { 3004 hist = lru_hist_from_seq(walk->seq + 1); 3005 3006 for (i = 0; i < NR_MM_STATS; i++) 3007 WRITE_ONCE(mm_state->stats[hist][i], 0); 3008 } 3009 } 3010 3011 static bool iterate_mm_list(struct lru_gen_mm_walk *walk, struct mm_struct **iter) 3012 { 3013 bool first = false; 3014 bool last = false; 3015 struct mm_struct *mm = NULL; 3016 struct lruvec *lruvec = walk->lruvec; 3017 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 3018 struct lru_gen_mm_list *mm_list = get_mm_list(memcg); 3019 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec); 3020 3021 /* 3022 * mm_state->seq is incremented after each iteration of mm_list. There 3023 * are three interesting cases for this page table walker: 3024 * 1. It tries to start a new iteration with a stale max_seq: there is 3025 * nothing left to do. 3026 * 2. It started the next iteration: it needs to reset the Bloom filter 3027 * so that a fresh set of PTE tables can be recorded. 3028 * 3. It ended the current iteration: it needs to reset the mm stats 3029 * counters and tell its caller to increment max_seq. 3030 */ 3031 spin_lock(&mm_list->lock); 3032 3033 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->seq); 3034 3035 if (walk->seq <= mm_state->seq) 3036 goto done; 3037 3038 if (!mm_state->head) 3039 mm_state->head = &mm_list->fifo; 3040 3041 if (mm_state->head == &mm_list->fifo) 3042 first = true; 3043 3044 do { 3045 mm_state->head = mm_state->head->next; 3046 if (mm_state->head == &mm_list->fifo) { 3047 WRITE_ONCE(mm_state->seq, mm_state->seq + 1); 3048 last = true; 3049 break; 3050 } 3051 3052 /* force scan for those added after the last iteration */ 3053 if (!mm_state->tail || mm_state->tail == mm_state->head) { 3054 mm_state->tail = mm_state->head->next; 3055 walk->force_scan = true; 3056 } 3057 } while (!(mm = get_next_mm(walk))); 3058 done: 3059 if (*iter || last) 3060 reset_mm_stats(walk, last); 3061 3062 spin_unlock(&mm_list->lock); 3063 3064 if (mm && first) 3065 reset_bloom_filter(mm_state, walk->seq + 1); 3066 3067 if (*iter) 3068 mmdrop(*iter); 3069 3070 *iter = mm; 3071 3072 return last; 3073 } 3074 3075 static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long seq) 3076 { 3077 bool success = false; 3078 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 3079 struct lru_gen_mm_list *mm_list = get_mm_list(memcg); 3080 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec); 3081 3082 spin_lock(&mm_list->lock); 3083 3084 VM_WARN_ON_ONCE(mm_state->seq + 1 < seq); 3085 3086 if (seq > mm_state->seq) { 3087 mm_state->head = NULL; 3088 mm_state->tail = NULL; 3089 WRITE_ONCE(mm_state->seq, mm_state->seq + 1); 3090 success = true; 3091 } 3092 3093 spin_unlock(&mm_list->lock); 3094 3095 return success; 3096 } 3097 3098 /****************************************************************************** 3099 * PID controller 3100 ******************************************************************************/ 3101 3102 /* 3103 * A feedback loop based on Proportional-Integral-Derivative (PID) controller. 3104 * 3105 * The P term is refaulted/(evicted+protected) from a tier in the generation 3106 * currently being evicted; the I term is the exponential moving average of the 3107 * P term over the generations previously evicted, using the smoothing factor 3108 * 1/2; the D term isn't supported. 3109 * 3110 * The setpoint (SP) is always the first tier of one type; the process variable 3111 * (PV) is either any tier of the other type or any other tier of the same 3112 * type. 3113 * 3114 * The error is the difference between the SP and the PV; the correction is to 3115 * turn off protection when SP>PV or turn on protection when SP<PV. 3116 * 3117 * For future optimizations: 3118 * 1. The D term may discount the other two terms over time so that long-lived 3119 * generations can resist stale information. 3120 */ 3121 struct ctrl_pos { 3122 unsigned long refaulted; 3123 unsigned long total; 3124 int gain; 3125 }; 3126 3127 static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain, 3128 struct ctrl_pos *pos) 3129 { 3130 int i; 3131 struct lru_gen_folio *lrugen = &lruvec->lrugen; 3132 int hist = lru_hist_from_seq(lrugen->min_seq[type]); 3133 3134 pos->gain = gain; 3135 pos->refaulted = pos->total = 0; 3136 3137 for (i = tier % MAX_NR_TIERS; i <= min(tier, MAX_NR_TIERS - 1); i++) { 3138 pos->refaulted += lrugen->avg_refaulted[type][i] + 3139 atomic_long_read(&lrugen->refaulted[hist][type][i]); 3140 pos->total += lrugen->avg_total[type][i] + 3141 lrugen->protected[hist][type][i] + 3142 atomic_long_read(&lrugen->evicted[hist][type][i]); 3143 } 3144 } 3145 3146 static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover) 3147 { 3148 int hist, tier; 3149 struct lru_gen_folio *lrugen = &lruvec->lrugen; 3150 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1; 3151 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1; 3152 3153 lockdep_assert_held(&lruvec->lru_lock); 3154 3155 if (!carryover && !clear) 3156 return; 3157 3158 hist = lru_hist_from_seq(seq); 3159 3160 for (tier = 0; tier < MAX_NR_TIERS; tier++) { 3161 if (carryover) { 3162 unsigned long sum; 3163 3164 sum = lrugen->avg_refaulted[type][tier] + 3165 atomic_long_read(&lrugen->refaulted[hist][type][tier]); 3166 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2); 3167 3168 sum = lrugen->avg_total[type][tier] + 3169 lrugen->protected[hist][type][tier] + 3170 atomic_long_read(&lrugen->evicted[hist][type][tier]); 3171 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2); 3172 } 3173 3174 if (clear) { 3175 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0); 3176 atomic_long_set(&lrugen->evicted[hist][type][tier], 0); 3177 WRITE_ONCE(lrugen->protected[hist][type][tier], 0); 3178 } 3179 } 3180 } 3181 3182 static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv) 3183 { 3184 /* 3185 * Return true if the PV has a limited number of refaults or a lower 3186 * refaulted/total than the SP. 3187 */ 3188 return pv->refaulted < MIN_LRU_BATCH || 3189 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <= 3190 (sp->refaulted + 1) * pv->total * pv->gain; 3191 } 3192 3193 /****************************************************************************** 3194 * the aging 3195 ******************************************************************************/ 3196 3197 /* promote pages accessed through page tables */ 3198 static int folio_update_gen(struct folio *folio, int gen) 3199 { 3200 unsigned long new_flags, old_flags = READ_ONCE(folio->flags.f); 3201 3202 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS); 3203 3204 /* see the comment on LRU_REFS_FLAGS */ 3205 if (!folio_test_referenced(folio) && !folio_test_workingset(folio)) { 3206 set_mask_bits(&folio->flags.f, LRU_REFS_MASK, BIT(PG_referenced)); 3207 return -1; 3208 } 3209 3210 do { 3211 /* lru_gen_del_folio() has isolated this page? */ 3212 if (!(old_flags & LRU_GEN_MASK)) 3213 return -1; 3214 3215 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_FLAGS); 3216 new_flags |= ((gen + 1UL) << LRU_GEN_PGOFF) | BIT(PG_workingset); 3217 } while (!try_cmpxchg(&folio->flags.f, &old_flags, new_flags)); 3218 3219 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1; 3220 } 3221 3222 /* protect pages accessed multiple times through file descriptors */ 3223 static int folio_inc_gen(struct lruvec *lruvec, struct folio *folio, bool reclaiming) 3224 { 3225 int type = folio_is_file_lru(folio); 3226 struct lru_gen_folio *lrugen = &lruvec->lrugen; 3227 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]); 3228 unsigned long new_flags, old_flags = READ_ONCE(folio->flags.f); 3229 3230 VM_WARN_ON_ONCE_FOLIO(!(old_flags & LRU_GEN_MASK), folio); 3231 3232 do { 3233 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1; 3234 /* folio_update_gen() has promoted this page? */ 3235 if (new_gen >= 0 && new_gen != old_gen) 3236 return new_gen; 3237 3238 new_gen = (old_gen + 1) % MAX_NR_GENS; 3239 3240 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_FLAGS); 3241 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF; 3242 /* for folio_end_writeback() */ 3243 if (reclaiming) 3244 new_flags |= BIT(PG_reclaim); 3245 } while (!try_cmpxchg(&folio->flags.f, &old_flags, new_flags)); 3246 3247 lru_gen_update_size(lruvec, folio, old_gen, new_gen); 3248 3249 return new_gen; 3250 } 3251 3252 static void update_batch_size(struct lru_gen_mm_walk *walk, struct folio *folio, 3253 int old_gen, int new_gen) 3254 { 3255 int type = folio_is_file_lru(folio); 3256 int zone = folio_zonenum(folio); 3257 int delta = folio_nr_pages(folio); 3258 3259 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS); 3260 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS); 3261 3262 walk->batched++; 3263 3264 walk->nr_pages[old_gen][type][zone] -= delta; 3265 walk->nr_pages[new_gen][type][zone] += delta; 3266 } 3267 3268 static void reset_batch_size(struct lru_gen_mm_walk *walk) 3269 { 3270 int gen, type, zone; 3271 struct lruvec *lruvec = walk->lruvec; 3272 struct lru_gen_folio *lrugen = &lruvec->lrugen; 3273 3274 walk->batched = 0; 3275 3276 for_each_gen_type_zone(gen, type, zone) { 3277 enum lru_list lru = type * LRU_INACTIVE_FILE; 3278 int delta = walk->nr_pages[gen][type][zone]; 3279 3280 if (!delta) 3281 continue; 3282 3283 walk->nr_pages[gen][type][zone] = 0; 3284 WRITE_ONCE(lrugen->nr_pages[gen][type][zone], 3285 lrugen->nr_pages[gen][type][zone] + delta); 3286 3287 if (lru_gen_is_active(lruvec, gen)) 3288 lru += LRU_ACTIVE; 3289 __update_lru_size(lruvec, lru, zone, delta); 3290 } 3291 } 3292 3293 static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args) 3294 { 3295 struct address_space *mapping; 3296 struct vm_area_struct *vma = args->vma; 3297 struct lru_gen_mm_walk *walk = args->private; 3298 3299 if (!vma_is_accessible(vma)) 3300 return true; 3301 3302 if (is_vm_hugetlb_page(vma)) 3303 return true; 3304 3305 if (!vma_has_recency(vma)) 3306 return true; 3307 3308 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL)) 3309 return true; 3310 3311 if (vma == get_gate_vma(vma->vm_mm)) 3312 return true; 3313 3314 if (vma_is_anonymous(vma)) 3315 return !walk->swappiness; 3316 3317 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping)) 3318 return true; 3319 3320 mapping = vma->vm_file->f_mapping; 3321 if (mapping_unevictable(mapping)) 3322 return true; 3323 3324 if (shmem_mapping(mapping)) 3325 return !walk->swappiness; 3326 3327 if (walk->swappiness > MAX_SWAPPINESS) 3328 return true; 3329 3330 /* to exclude special mappings like dax, etc. */ 3331 return !mapping->a_ops->read_folio; 3332 } 3333 3334 /* 3335 * Some userspace memory allocators map many single-page VMAs. Instead of 3336 * returning back to the PGD table for each of such VMAs, finish an entire PMD 3337 * table to reduce zigzags and improve cache performance. 3338 */ 3339 static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args, 3340 unsigned long *vm_start, unsigned long *vm_end) 3341 { 3342 unsigned long start = round_up(*vm_end, size); 3343 unsigned long end = (start | ~mask) + 1; 3344 VMA_ITERATOR(vmi, args->mm, start); 3345 3346 VM_WARN_ON_ONCE(mask & size); 3347 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask)); 3348 3349 for_each_vma(vmi, args->vma) { 3350 if (end && end <= args->vma->vm_start) 3351 return false; 3352 3353 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) 3354 continue; 3355 3356 *vm_start = max(start, args->vma->vm_start); 3357 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1; 3358 3359 return true; 3360 } 3361 3362 return false; 3363 } 3364 3365 static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr, 3366 struct pglist_data *pgdat) 3367 { 3368 unsigned long pfn = pte_pfn(pte); 3369 3370 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end); 3371 3372 if (!pte_present(pte) || is_zero_pfn(pfn)) 3373 return -1; 3374 3375 if (WARN_ON_ONCE(pte_special(pte))) 3376 return -1; 3377 3378 if (!pte_young(pte) && !mm_has_notifiers(vma->vm_mm)) 3379 return -1; 3380 3381 if (WARN_ON_ONCE(!pfn_valid(pfn))) 3382 return -1; 3383 3384 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat)) 3385 return -1; 3386 3387 return pfn; 3388 } 3389 3390 static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr, 3391 struct pglist_data *pgdat) 3392 { 3393 unsigned long pfn = pmd_pfn(pmd); 3394 3395 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end); 3396 3397 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd)) 3398 return -1; 3399 3400 if (!pmd_young(pmd) && !mm_has_notifiers(vma->vm_mm)) 3401 return -1; 3402 3403 if (WARN_ON_ONCE(!pfn_valid(pfn))) 3404 return -1; 3405 3406 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat)) 3407 return -1; 3408 3409 return pfn; 3410 } 3411 3412 static struct folio *get_pfn_folio(unsigned long pfn, struct mem_cgroup *memcg, 3413 struct pglist_data *pgdat) 3414 { 3415 struct folio *folio = pfn_folio(pfn); 3416 3417 if (folio_lru_gen(folio) < 0) 3418 return NULL; 3419 3420 if (folio_nid(folio) != pgdat->node_id) 3421 return NULL; 3422 3423 rcu_read_lock(); 3424 if (folio_memcg(folio) != memcg) 3425 folio = NULL; 3426 rcu_read_unlock(); 3427 3428 return folio; 3429 } 3430 3431 static bool suitable_to_scan(int total, int young) 3432 { 3433 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8); 3434 3435 /* suitable if the average number of young PTEs per cacheline is >=1 */ 3436 return young * n >= total; 3437 } 3438 3439 static void walk_update_folio(struct lru_gen_mm_walk *walk, struct folio *folio, 3440 int new_gen, bool dirty) 3441 { 3442 int old_gen; 3443 3444 if (!folio) 3445 return; 3446 3447 if (dirty && !folio_test_dirty(folio) && 3448 !(folio_test_anon(folio) && folio_test_swapbacked(folio) && 3449 !folio_test_swapcache(folio))) 3450 folio_mark_dirty(folio); 3451 3452 if (walk) { 3453 old_gen = folio_update_gen(folio, new_gen); 3454 if (old_gen >= 0 && old_gen != new_gen) 3455 update_batch_size(walk, folio, old_gen, new_gen); 3456 } else if (lru_gen_set_refs(folio)) { 3457 old_gen = folio_lru_gen(folio); 3458 if (old_gen >= 0 && old_gen != new_gen) 3459 folio_activate(folio); 3460 } 3461 } 3462 3463 static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end, 3464 struct mm_walk *args) 3465 { 3466 int i; 3467 bool dirty; 3468 pte_t *pte; 3469 spinlock_t *ptl; 3470 unsigned long addr; 3471 int total = 0; 3472 int young = 0; 3473 struct folio *last = NULL; 3474 struct lru_gen_mm_walk *walk = args->private; 3475 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec); 3476 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec); 3477 DEFINE_MAX_SEQ(walk->lruvec); 3478 int gen = lru_gen_from_seq(max_seq); 3479 unsigned int nr; 3480 pmd_t pmdval; 3481 3482 pte = pte_offset_map_rw_nolock(args->mm, pmd, start & PMD_MASK, &pmdval, &ptl); 3483 if (!pte) 3484 return false; 3485 3486 if (!spin_trylock(ptl)) { 3487 pte_unmap(pte); 3488 return true; 3489 } 3490 3491 if (unlikely(!pmd_same(pmdval, pmdp_get_lockless(pmd)))) { 3492 pte_unmap_unlock(pte, ptl); 3493 return false; 3494 } 3495 3496 lazy_mmu_mode_enable(); 3497 restart: 3498 for (i = pte_index(start), addr = start; addr != end; i += nr, addr += nr * PAGE_SIZE) { 3499 unsigned long pfn; 3500 struct folio *folio; 3501 pte_t *cur_pte = pte + i; 3502 pte_t ptent = ptep_get(cur_pte); 3503 3504 nr = 1; 3505 total++; 3506 walk->mm_stats[MM_LEAF_TOTAL]++; 3507 3508 pfn = get_pte_pfn(ptent, args->vma, addr, pgdat); 3509 if (pfn == -1) 3510 continue; 3511 3512 folio = get_pfn_folio(pfn, memcg, pgdat); 3513 if (!folio) 3514 continue; 3515 3516 if (folio_test_large(folio)) { 3517 const unsigned int max_nr = (end - addr) >> PAGE_SHIFT; 3518 3519 nr = folio_pte_batch_flags(folio, NULL, cur_pte, &ptent, 3520 max_nr, FPB_MERGE_YOUNG_DIRTY); 3521 total += nr - 1; 3522 walk->mm_stats[MM_LEAF_TOTAL] += nr - 1; 3523 } 3524 3525 if (!test_and_clear_young_ptes_notify(args->vma, addr, cur_pte, nr)) 3526 continue; 3527 3528 if (last != folio) { 3529 walk_update_folio(walk, last, gen, dirty); 3530 3531 last = folio; 3532 dirty = false; 3533 } 3534 3535 if (pte_dirty(ptent)) 3536 dirty = true; 3537 3538 young += nr; 3539 walk->mm_stats[MM_LEAF_YOUNG] += nr; 3540 } 3541 3542 walk_update_folio(walk, last, gen, dirty); 3543 last = NULL; 3544 3545 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end)) 3546 goto restart; 3547 3548 lazy_mmu_mode_disable(); 3549 pte_unmap_unlock(pte, ptl); 3550 3551 return suitable_to_scan(total, young); 3552 } 3553 3554 static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area_struct *vma, 3555 struct mm_walk *args, unsigned long *bitmap, unsigned long *first) 3556 { 3557 int i; 3558 bool dirty; 3559 pmd_t *pmd; 3560 spinlock_t *ptl; 3561 struct folio *last = NULL; 3562 struct lru_gen_mm_walk *walk = args->private; 3563 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec); 3564 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec); 3565 DEFINE_MAX_SEQ(walk->lruvec); 3566 int gen = lru_gen_from_seq(max_seq); 3567 3568 VM_WARN_ON_ONCE(pud_leaf(*pud)); 3569 3570 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */ 3571 if (*first == -1) { 3572 *first = addr; 3573 bitmap_zero(bitmap, MIN_LRU_BATCH); 3574 return; 3575 } 3576 3577 i = addr == -1 ? 0 : pmd_index(addr) - pmd_index(*first); 3578 if (i && i <= MIN_LRU_BATCH) { 3579 __set_bit(i - 1, bitmap); 3580 return; 3581 } 3582 3583 pmd = pmd_offset(pud, *first); 3584 3585 ptl = pmd_lockptr(args->mm, pmd); 3586 if (!spin_trylock(ptl)) 3587 goto done; 3588 3589 lazy_mmu_mode_enable(); 3590 3591 do { 3592 unsigned long pfn; 3593 struct folio *folio; 3594 3595 /* don't round down the first address */ 3596 addr = i ? (*first & PMD_MASK) + i * PMD_SIZE : *first; 3597 3598 if (!pmd_present(pmd[i])) 3599 goto next; 3600 3601 if (!pmd_trans_huge(pmd[i])) { 3602 if (!walk->force_scan && should_clear_pmd_young() && 3603 !mm_has_notifiers(args->mm)) 3604 pmdp_test_and_clear_young(vma, addr, pmd + i); 3605 goto next; 3606 } 3607 3608 pfn = get_pmd_pfn(pmd[i], vma, addr, pgdat); 3609 if (pfn == -1) 3610 goto next; 3611 3612 folio = get_pfn_folio(pfn, memcg, pgdat); 3613 if (!folio) 3614 goto next; 3615 3616 if (!pmdp_test_and_clear_young_notify(vma, addr, pmd + i)) 3617 goto next; 3618 3619 if (last != folio) { 3620 walk_update_folio(walk, last, gen, dirty); 3621 3622 last = folio; 3623 dirty = false; 3624 } 3625 3626 if (pmd_dirty(pmd[i])) 3627 dirty = true; 3628 3629 walk->mm_stats[MM_LEAF_YOUNG]++; 3630 next: 3631 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1; 3632 } while (i <= MIN_LRU_BATCH); 3633 3634 walk_update_folio(walk, last, gen, dirty); 3635 3636 lazy_mmu_mode_disable(); 3637 spin_unlock(ptl); 3638 done: 3639 *first = -1; 3640 } 3641 3642 static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end, 3643 struct mm_walk *args) 3644 { 3645 int i; 3646 pmd_t *pmd; 3647 unsigned long next; 3648 unsigned long addr; 3649 struct vm_area_struct *vma; 3650 DECLARE_BITMAP(bitmap, MIN_LRU_BATCH); 3651 unsigned long first = -1; 3652 struct lru_gen_mm_walk *walk = args->private; 3653 struct lru_gen_mm_state *mm_state = get_mm_state(walk->lruvec); 3654 3655 VM_WARN_ON_ONCE(pud_leaf(*pud)); 3656 3657 /* 3658 * Finish an entire PMD in two passes: the first only reaches to PTE 3659 * tables to avoid taking the PMD lock; the second, if necessary, takes 3660 * the PMD lock to clear the accessed bit in PMD entries. 3661 */ 3662 pmd = pmd_offset(pud, start & PUD_MASK); 3663 restart: 3664 /* walk_pte_range() may call get_next_vma() */ 3665 vma = args->vma; 3666 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) { 3667 pmd_t val = pmdp_get_lockless(pmd + i); 3668 3669 next = pmd_addr_end(addr, end); 3670 3671 if (!pmd_present(val) || is_huge_zero_pmd(val)) { 3672 walk->mm_stats[MM_LEAF_TOTAL]++; 3673 continue; 3674 } 3675 3676 if (pmd_trans_huge(val)) { 3677 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec); 3678 unsigned long pfn = get_pmd_pfn(val, vma, addr, pgdat); 3679 3680 walk->mm_stats[MM_LEAF_TOTAL]++; 3681 3682 if (pfn != -1) 3683 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &first); 3684 continue; 3685 } 3686 3687 if (!walk->force_scan && should_clear_pmd_young() && 3688 !mm_has_notifiers(args->mm)) { 3689 if (!pmd_young(val)) 3690 continue; 3691 3692 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &first); 3693 } 3694 3695 if (!walk->force_scan && !test_bloom_filter(mm_state, walk->seq, pmd + i)) 3696 continue; 3697 3698 walk->mm_stats[MM_NONLEAF_FOUND]++; 3699 3700 if (!walk_pte_range(&val, addr, next, args)) 3701 continue; 3702 3703 walk->mm_stats[MM_NONLEAF_ADDED]++; 3704 3705 /* carry over to the next generation */ 3706 update_bloom_filter(mm_state, walk->seq + 1, pmd + i); 3707 } 3708 3709 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &first); 3710 3711 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end)) 3712 goto restart; 3713 } 3714 3715 static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end, 3716 struct mm_walk *args) 3717 { 3718 int i; 3719 pud_t *pud; 3720 unsigned long addr; 3721 unsigned long next; 3722 struct lru_gen_mm_walk *walk = args->private; 3723 3724 VM_WARN_ON_ONCE(p4d_leaf(*p4d)); 3725 3726 pud = pud_offset(p4d, start & P4D_MASK); 3727 restart: 3728 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) { 3729 pud_t val = pudp_get(pud + i); 3730 3731 next = pud_addr_end(addr, end); 3732 3733 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val))) 3734 continue; 3735 3736 walk_pmd_range(&val, addr, next, args); 3737 3738 if (need_resched() || walk->batched >= MAX_LRU_BATCH) { 3739 end = (addr | ~PUD_MASK) + 1; 3740 goto done; 3741 } 3742 } 3743 3744 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end)) 3745 goto restart; 3746 3747 end = round_up(end, P4D_SIZE); 3748 done: 3749 if (!end || !args->vma) 3750 return 1; 3751 3752 walk->next_addr = max(end, args->vma->vm_start); 3753 3754 return -EAGAIN; 3755 } 3756 3757 static void walk_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk) 3758 { 3759 static const struct mm_walk_ops mm_walk_ops = { 3760 .test_walk = should_skip_vma, 3761 .p4d_entry = walk_pud_range, 3762 .walk_lock = PGWALK_RDLOCK, 3763 }; 3764 int err; 3765 struct lruvec *lruvec = walk->lruvec; 3766 3767 walk->next_addr = FIRST_USER_ADDRESS; 3768 3769 do { 3770 DEFINE_MAX_SEQ(lruvec); 3771 3772 err = -EBUSY; 3773 3774 /* another thread might have called inc_max_seq() */ 3775 if (walk->seq != max_seq) 3776 break; 3777 3778 /* the caller might be holding the lock for write */ 3779 if (mmap_read_trylock(mm)) { 3780 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk); 3781 3782 mmap_read_unlock(mm); 3783 } 3784 3785 if (walk->batched) { 3786 lruvec_lock_irq(lruvec); 3787 reset_batch_size(walk); 3788 lruvec_unlock_irq(lruvec); 3789 } 3790 3791 cond_resched(); 3792 } while (err == -EAGAIN); 3793 } 3794 3795 static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat, bool force_alloc) 3796 { 3797 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk; 3798 3799 if (pgdat && current_is_kswapd()) { 3800 VM_WARN_ON_ONCE(walk); 3801 3802 walk = &pgdat->mm_walk; 3803 } else if (!walk && force_alloc) { 3804 VM_WARN_ON_ONCE(current_is_kswapd()); 3805 3806 walk = kzalloc_obj(*walk, 3807 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN); 3808 } 3809 3810 current->reclaim_state->mm_walk = walk; 3811 3812 return walk; 3813 } 3814 3815 static void clear_mm_walk(void) 3816 { 3817 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk; 3818 3819 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages))); 3820 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats))); 3821 3822 current->reclaim_state->mm_walk = NULL; 3823 3824 if (!current_is_kswapd()) 3825 kfree(walk); 3826 } 3827 3828 static bool inc_min_seq(struct lruvec *lruvec, int type, int swappiness) 3829 { 3830 int zone; 3831 int remaining = MAX_LRU_BATCH; 3832 struct lru_gen_folio *lrugen = &lruvec->lrugen; 3833 int hist = lru_hist_from_seq(lrugen->min_seq[type]); 3834 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]); 3835 3836 /* For file type, skip the check if swappiness is anon only */ 3837 if (type && (swappiness == SWAPPINESS_ANON_ONLY)) 3838 goto done; 3839 3840 /* For anon type, skip the check if swappiness is zero (file only) */ 3841 if (!type && !swappiness) 3842 goto done; 3843 3844 /* prevent cold/hot inversion if the type is evictable */ 3845 for (zone = 0; zone < MAX_NR_ZONES; zone++) { 3846 struct list_head *head = &lrugen->folios[old_gen][type][zone]; 3847 3848 while (!list_empty(head)) { 3849 struct folio *folio = lru_to_folio(head); 3850 int refs = folio_lru_refs(folio); 3851 bool workingset = folio_test_workingset(folio); 3852 3853 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio); 3854 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio); 3855 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio); 3856 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio); 3857 3858 new_gen = folio_inc_gen(lruvec, folio, false); 3859 list_move_tail(&folio->lru, &lrugen->folios[new_gen][type][zone]); 3860 3861 /* don't count the workingset being lazily promoted */ 3862 if (refs + workingset != BIT(LRU_REFS_WIDTH) + 1) { 3863 int tier = lru_tier_from_refs(refs, workingset); 3864 int delta = folio_nr_pages(folio); 3865 3866 WRITE_ONCE(lrugen->protected[hist][type][tier], 3867 lrugen->protected[hist][type][tier] + delta); 3868 } 3869 3870 if (!--remaining) 3871 return false; 3872 } 3873 } 3874 done: 3875 reset_ctrl_pos(lruvec, type, true); 3876 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1); 3877 3878 return true; 3879 } 3880 3881 static bool try_to_inc_min_seq(struct lruvec *lruvec, int swappiness) 3882 { 3883 int gen, type, zone; 3884 bool success = false; 3885 bool seq_inc_flag = false; 3886 struct lru_gen_folio *lrugen = &lruvec->lrugen; 3887 DEFINE_MIN_SEQ(lruvec); 3888 3889 VM_WARN_ON_ONCE(!seq_is_valid(lruvec)); 3890 3891 /* find the oldest populated generation */ 3892 for_each_evictable_type(type, swappiness) { 3893 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) { 3894 gen = lru_gen_from_seq(min_seq[type]); 3895 3896 for (zone = 0; zone < MAX_NR_ZONES; zone++) { 3897 if (!list_empty(&lrugen->folios[gen][type][zone])) 3898 goto next; 3899 } 3900 3901 min_seq[type]++; 3902 seq_inc_flag = true; 3903 } 3904 next: 3905 ; 3906 } 3907 3908 /* 3909 * If min_seq[type] of both anonymous and file is not increased, 3910 * we can directly return false to avoid unnecessary checking 3911 * overhead later. 3912 */ 3913 if (!seq_inc_flag) 3914 return success; 3915 3916 /* see the comment on lru_gen_folio */ 3917 if (swappiness && swappiness <= MAX_SWAPPINESS) { 3918 unsigned long seq = lrugen->max_seq - MIN_NR_GENS; 3919 3920 if (min_seq[LRU_GEN_ANON] > seq && min_seq[LRU_GEN_FILE] < seq) 3921 min_seq[LRU_GEN_ANON] = seq; 3922 else if (min_seq[LRU_GEN_FILE] > seq && min_seq[LRU_GEN_ANON] < seq) 3923 min_seq[LRU_GEN_FILE] = seq; 3924 } 3925 3926 for_each_evictable_type(type, swappiness) { 3927 if (min_seq[type] <= lrugen->min_seq[type]) 3928 continue; 3929 3930 reset_ctrl_pos(lruvec, type, true); 3931 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]); 3932 success = true; 3933 } 3934 3935 return success; 3936 } 3937 3938 static bool inc_max_seq(struct lruvec *lruvec, unsigned long seq, int swappiness) 3939 { 3940 bool success; 3941 int prev, next; 3942 int type, zone; 3943 struct lru_gen_folio *lrugen = &lruvec->lrugen; 3944 restart: 3945 if (seq < READ_ONCE(lrugen->max_seq)) 3946 return false; 3947 3948 lruvec_lock_irq(lruvec); 3949 3950 VM_WARN_ON_ONCE(!seq_is_valid(lruvec)); 3951 3952 success = seq == lrugen->max_seq; 3953 if (!success) 3954 goto unlock; 3955 3956 for (type = 0; type < ANON_AND_FILE; type++) { 3957 if (get_nr_gens(lruvec, type) != MAX_NR_GENS) 3958 continue; 3959 3960 if (inc_min_seq(lruvec, type, swappiness)) 3961 continue; 3962 3963 lruvec_unlock_irq(lruvec); 3964 cond_resched(); 3965 goto restart; 3966 } 3967 3968 /* 3969 * Update the active/inactive LRU sizes for compatibility. Both sides of 3970 * the current max_seq need to be covered, since max_seq+1 can overlap 3971 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do 3972 * overlap, cold/hot inversion happens. 3973 */ 3974 prev = lru_gen_from_seq(lrugen->max_seq - 1); 3975 next = lru_gen_from_seq(lrugen->max_seq + 1); 3976 3977 for (type = 0; type < ANON_AND_FILE; type++) { 3978 for (zone = 0; zone < MAX_NR_ZONES; zone++) { 3979 enum lru_list lru = type * LRU_INACTIVE_FILE; 3980 long delta = lrugen->nr_pages[prev][type][zone] - 3981 lrugen->nr_pages[next][type][zone]; 3982 3983 if (!delta) 3984 continue; 3985 3986 __update_lru_size(lruvec, lru, zone, delta); 3987 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta); 3988 } 3989 } 3990 3991 for (type = 0; type < ANON_AND_FILE; type++) 3992 reset_ctrl_pos(lruvec, type, false); 3993 3994 WRITE_ONCE(lrugen->timestamps[next], jiffies); 3995 /* make sure preceding modifications appear */ 3996 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1); 3997 unlock: 3998 lruvec_unlock_irq(lruvec); 3999 4000 return success; 4001 } 4002 4003 static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long seq, 4004 int swappiness, bool force_scan) 4005 { 4006 bool success; 4007 struct lru_gen_mm_walk *walk; 4008 struct mm_struct *mm = NULL; 4009 struct lru_gen_folio *lrugen = &lruvec->lrugen; 4010 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec); 4011 4012 VM_WARN_ON_ONCE(seq > READ_ONCE(lrugen->max_seq)); 4013 4014 if (!mm_state) 4015 return inc_max_seq(lruvec, seq, swappiness); 4016 4017 /* see the comment in iterate_mm_list() */ 4018 if (seq <= READ_ONCE(mm_state->seq)) 4019 return false; 4020 4021 /* 4022 * If the hardware doesn't automatically set the accessed bit, fallback 4023 * to lru_gen_look_around(), which only clears the accessed bit in a 4024 * handful of PTEs. Spreading the work out over a period of time usually 4025 * is less efficient, but it avoids bursty page faults. 4026 */ 4027 if (!should_walk_mmu()) { 4028 success = iterate_mm_list_nowalk(lruvec, seq); 4029 goto done; 4030 } 4031 4032 walk = set_mm_walk(NULL, true); 4033 if (!walk) { 4034 success = iterate_mm_list_nowalk(lruvec, seq); 4035 goto done; 4036 } 4037 4038 walk->lruvec = lruvec; 4039 walk->seq = seq; 4040 walk->swappiness = swappiness; 4041 walk->force_scan = force_scan; 4042 4043 do { 4044 success = iterate_mm_list(walk, &mm); 4045 if (mm) 4046 walk_mm(mm, walk); 4047 } while (mm); 4048 done: 4049 if (success) { 4050 success = inc_max_seq(lruvec, seq, swappiness); 4051 WARN_ON_ONCE(!success); 4052 } 4053 4054 return success; 4055 } 4056 4057 /****************************************************************************** 4058 * working set protection 4059 ******************************************************************************/ 4060 4061 static void set_initial_priority(struct pglist_data *pgdat, struct scan_control *sc) 4062 { 4063 int priority; 4064 unsigned long reclaimable; 4065 4066 if (sc->priority != DEF_PRIORITY || sc->nr_to_reclaim < MIN_LRU_BATCH) 4067 return; 4068 /* 4069 * Determine the initial priority based on 4070 * (total >> priority) * reclaimed_to_scanned_ratio = nr_to_reclaim, 4071 * where reclaimed_to_scanned_ratio = inactive / total. 4072 */ 4073 reclaimable = node_page_state(pgdat, NR_INACTIVE_FILE); 4074 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc)) 4075 reclaimable += node_page_state(pgdat, NR_INACTIVE_ANON); 4076 4077 /* round down reclaimable and round up sc->nr_to_reclaim */ 4078 priority = fls_long(reclaimable) - 1 - fls_long(sc->nr_to_reclaim - 1); 4079 4080 /* 4081 * The estimation is based on LRU pages only, so cap it to prevent 4082 * overshoots of shrinker objects by large margins. 4083 */ 4084 sc->priority = clamp(priority, DEF_PRIORITY / 2, DEF_PRIORITY); 4085 } 4086 4087 static bool lruvec_is_sizable(struct lruvec *lruvec, struct scan_control *sc) 4088 { 4089 int gen, type, zone; 4090 unsigned long total = 0; 4091 int swappiness = get_swappiness(lruvec, sc); 4092 struct lru_gen_folio *lrugen = &lruvec->lrugen; 4093 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 4094 DEFINE_MAX_SEQ(lruvec); 4095 DEFINE_MIN_SEQ(lruvec); 4096 4097 for_each_evictable_type(type, swappiness) { 4098 unsigned long seq; 4099 4100 for (seq = min_seq[type]; seq <= max_seq; seq++) { 4101 gen = lru_gen_from_seq(seq); 4102 4103 for (zone = 0; zone < MAX_NR_ZONES; zone++) 4104 total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L); 4105 } 4106 } 4107 4108 /* whether the size is big enough to be helpful */ 4109 return mem_cgroup_online(memcg) ? (total >> sc->priority) : total; 4110 } 4111 4112 static bool lruvec_is_reclaimable(struct lruvec *lruvec, struct scan_control *sc, 4113 unsigned long min_ttl) 4114 { 4115 int gen; 4116 unsigned long birth; 4117 int swappiness = get_swappiness(lruvec, sc); 4118 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 4119 DEFINE_MIN_SEQ(lruvec); 4120 4121 if (mem_cgroup_below_min(NULL, memcg)) 4122 return false; 4123 4124 if (!lruvec_is_sizable(lruvec, sc)) 4125 return false; 4126 4127 gen = lru_gen_from_seq(evictable_min_seq(min_seq, swappiness)); 4128 birth = READ_ONCE(lruvec->lrugen.timestamps[gen]); 4129 4130 return time_is_before_jiffies(birth + min_ttl); 4131 } 4132 4133 /* to protect the working set of the last N jiffies */ 4134 static unsigned long lru_gen_min_ttl __read_mostly; 4135 4136 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc) 4137 { 4138 struct mem_cgroup *memcg; 4139 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl); 4140 bool reclaimable = !min_ttl; 4141 4142 VM_WARN_ON_ONCE(!current_is_kswapd()); 4143 4144 set_initial_priority(pgdat, sc); 4145 4146 memcg = mem_cgroup_iter(NULL, NULL, NULL); 4147 do { 4148 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat); 4149 4150 mem_cgroup_calculate_protection(NULL, memcg); 4151 4152 if (!reclaimable) 4153 reclaimable = lruvec_is_reclaimable(lruvec, sc, min_ttl); 4154 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL))); 4155 4156 /* 4157 * The main goal is to OOM kill if every generation from all memcgs is 4158 * younger than min_ttl. However, another possibility is all memcgs are 4159 * either too small or below min. 4160 */ 4161 if (!reclaimable && mutex_trylock(&oom_lock)) { 4162 struct oom_control oc = { 4163 .gfp_mask = sc->gfp_mask, 4164 }; 4165 4166 out_of_memory(&oc); 4167 4168 mutex_unlock(&oom_lock); 4169 } 4170 } 4171 4172 /****************************************************************************** 4173 * rmap/PT walk feedback 4174 ******************************************************************************/ 4175 4176 /* 4177 * This function exploits spatial locality when shrink_folio_list() walks the 4178 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If 4179 * the scan was done cacheline efficiently, it adds the PMD entry pointing to 4180 * the PTE table to the Bloom filter. This forms a feedback loop between the 4181 * eviction and the aging. 4182 */ 4183 bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw, unsigned int nr) 4184 { 4185 int i; 4186 bool dirty; 4187 unsigned long start; 4188 unsigned long end; 4189 struct lru_gen_mm_walk *walk; 4190 struct folio *last = NULL; 4191 int young = 1; 4192 pte_t *pte = pvmw->pte; 4193 unsigned long addr = pvmw->address; 4194 struct vm_area_struct *vma = pvmw->vma; 4195 struct folio *folio = pfn_folio(pvmw->pfn); 4196 struct mem_cgroup *memcg; 4197 struct pglist_data *pgdat = folio_pgdat(folio); 4198 struct lruvec *lruvec; 4199 struct lru_gen_mm_state *mm_state; 4200 unsigned long max_seq; 4201 int gen; 4202 4203 lockdep_assert_held(pvmw->ptl); 4204 VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio); 4205 4206 if (!test_and_clear_young_ptes_notify(vma, addr, pte, nr)) 4207 return false; 4208 4209 if (spin_is_contended(pvmw->ptl)) 4210 return true; 4211 4212 /* exclude special VMAs containing anon pages from COW */ 4213 if (vma->vm_flags & VM_SPECIAL) 4214 return true; 4215 4216 /* avoid taking the LRU lock under the PTL when possible */ 4217 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL; 4218 4219 start = max(addr & PMD_MASK, vma->vm_start); 4220 end = min(addr | ~PMD_MASK, vma->vm_end - 1) + 1; 4221 4222 if (end - start == PAGE_SIZE) 4223 return true; 4224 4225 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) { 4226 if (addr - start < MIN_LRU_BATCH * PAGE_SIZE / 2) 4227 end = start + MIN_LRU_BATCH * PAGE_SIZE; 4228 else if (end - addr < MIN_LRU_BATCH * PAGE_SIZE / 2) 4229 start = end - MIN_LRU_BATCH * PAGE_SIZE; 4230 else { 4231 start = addr - MIN_LRU_BATCH * PAGE_SIZE / 2; 4232 end = addr + MIN_LRU_BATCH * PAGE_SIZE / 2; 4233 } 4234 } 4235 4236 memcg = get_mem_cgroup_from_folio(folio); 4237 lruvec = mem_cgroup_lruvec(memcg, pgdat); 4238 max_seq = READ_ONCE((lruvec)->lrugen.max_seq); 4239 gen = lru_gen_from_seq(max_seq); 4240 mm_state = get_mm_state(lruvec); 4241 4242 lazy_mmu_mode_enable(); 4243 4244 pte -= (addr - start) / PAGE_SIZE; 4245 4246 for (i = 0, addr = start; addr != end; 4247 i += nr, pte += nr, addr += nr * PAGE_SIZE) { 4248 unsigned long pfn; 4249 pte_t ptent = ptep_get(pte); 4250 4251 nr = 1; 4252 pfn = get_pte_pfn(ptent, vma, addr, pgdat); 4253 if (pfn == -1) 4254 continue; 4255 4256 folio = get_pfn_folio(pfn, memcg, pgdat); 4257 if (!folio) 4258 continue; 4259 4260 if (folio_test_large(folio)) { 4261 const unsigned int max_nr = (end - addr) >> PAGE_SHIFT; 4262 4263 nr = folio_pte_batch_flags(folio, NULL, pte, &ptent, 4264 max_nr, FPB_MERGE_YOUNG_DIRTY); 4265 } 4266 4267 if (!test_and_clear_young_ptes_notify(vma, addr, pte, nr)) 4268 continue; 4269 4270 if (last != folio) { 4271 walk_update_folio(walk, last, gen, dirty); 4272 4273 last = folio; 4274 dirty = false; 4275 } 4276 4277 if (pte_dirty(ptent)) 4278 dirty = true; 4279 4280 young += nr; 4281 } 4282 4283 walk_update_folio(walk, last, gen, dirty); 4284 4285 lazy_mmu_mode_disable(); 4286 4287 /* feedback from rmap walkers to page table walkers */ 4288 if (mm_state && suitable_to_scan(i, young)) 4289 update_bloom_filter(mm_state, max_seq, pvmw->pmd); 4290 4291 mem_cgroup_put(memcg); 4292 4293 return true; 4294 } 4295 4296 /****************************************************************************** 4297 * memcg LRU 4298 ******************************************************************************/ 4299 4300 /* see the comment on MEMCG_NR_GENS */ 4301 enum { 4302 MEMCG_LRU_NOP, 4303 MEMCG_LRU_HEAD, 4304 MEMCG_LRU_TAIL, 4305 MEMCG_LRU_OLD, 4306 MEMCG_LRU_YOUNG, 4307 }; 4308 4309 static void lru_gen_rotate_memcg(struct lruvec *lruvec, int op) 4310 { 4311 int seg; 4312 int old, new; 4313 unsigned long flags; 4314 int bin = get_random_u32_below(MEMCG_NR_BINS); 4315 struct pglist_data *pgdat = lruvec_pgdat(lruvec); 4316 4317 spin_lock_irqsave(&pgdat->memcg_lru.lock, flags); 4318 4319 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list)); 4320 4321 seg = 0; 4322 new = old = lruvec->lrugen.gen; 4323 4324 /* see the comment on MEMCG_NR_GENS */ 4325 if (op == MEMCG_LRU_HEAD) 4326 seg = MEMCG_LRU_HEAD; 4327 else if (op == MEMCG_LRU_TAIL) 4328 seg = MEMCG_LRU_TAIL; 4329 else if (op == MEMCG_LRU_OLD) 4330 new = get_memcg_gen(pgdat->memcg_lru.seq); 4331 else if (op == MEMCG_LRU_YOUNG) 4332 new = get_memcg_gen(pgdat->memcg_lru.seq + 1); 4333 else 4334 VM_WARN_ON_ONCE(true); 4335 4336 WRITE_ONCE(lruvec->lrugen.seg, seg); 4337 WRITE_ONCE(lruvec->lrugen.gen, new); 4338 4339 hlist_nulls_del_rcu(&lruvec->lrugen.list); 4340 4341 if (op == MEMCG_LRU_HEAD || op == MEMCG_LRU_OLD) 4342 hlist_nulls_add_head_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]); 4343 else 4344 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]); 4345 4346 pgdat->memcg_lru.nr_memcgs[old]--; 4347 pgdat->memcg_lru.nr_memcgs[new]++; 4348 4349 if (!pgdat->memcg_lru.nr_memcgs[old] && old == get_memcg_gen(pgdat->memcg_lru.seq)) 4350 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1); 4351 4352 spin_unlock_irqrestore(&pgdat->memcg_lru.lock, flags); 4353 } 4354 4355 #ifdef CONFIG_MEMCG 4356 4357 void lru_gen_online_memcg(struct mem_cgroup *memcg) 4358 { 4359 int gen; 4360 int nid; 4361 int bin = get_random_u32_below(MEMCG_NR_BINS); 4362 4363 for_each_node(nid) { 4364 struct pglist_data *pgdat = NODE_DATA(nid); 4365 struct lruvec *lruvec = get_lruvec(memcg, nid); 4366 4367 spin_lock_irq(&pgdat->memcg_lru.lock); 4368 4369 VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec->lrugen.list)); 4370 4371 gen = get_memcg_gen(pgdat->memcg_lru.seq); 4372 4373 lruvec->lrugen.gen = gen; 4374 4375 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[gen][bin]); 4376 pgdat->memcg_lru.nr_memcgs[gen]++; 4377 4378 spin_unlock_irq(&pgdat->memcg_lru.lock); 4379 } 4380 } 4381 4382 void lru_gen_offline_memcg(struct mem_cgroup *memcg) 4383 { 4384 int nid; 4385 4386 for_each_node(nid) { 4387 struct lruvec *lruvec = get_lruvec(memcg, nid); 4388 4389 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_OLD); 4390 } 4391 } 4392 4393 void lru_gen_release_memcg(struct mem_cgroup *memcg) 4394 { 4395 int gen; 4396 int nid; 4397 4398 for_each_node(nid) { 4399 struct pglist_data *pgdat = NODE_DATA(nid); 4400 struct lruvec *lruvec = get_lruvec(memcg, nid); 4401 4402 spin_lock_irq(&pgdat->memcg_lru.lock); 4403 4404 if (hlist_nulls_unhashed(&lruvec->lrugen.list)) 4405 goto unlock; 4406 4407 gen = lruvec->lrugen.gen; 4408 4409 hlist_nulls_del_init_rcu(&lruvec->lrugen.list); 4410 pgdat->memcg_lru.nr_memcgs[gen]--; 4411 4412 if (!pgdat->memcg_lru.nr_memcgs[gen] && gen == get_memcg_gen(pgdat->memcg_lru.seq)) 4413 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1); 4414 unlock: 4415 spin_unlock_irq(&pgdat->memcg_lru.lock); 4416 } 4417 } 4418 4419 void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid) 4420 { 4421 struct lruvec *lruvec = get_lruvec(memcg, nid); 4422 4423 /* see the comment on MEMCG_NR_GENS */ 4424 if (READ_ONCE(lruvec->lrugen.seg) != MEMCG_LRU_HEAD) 4425 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_HEAD); 4426 } 4427 4428 bool recheck_lru_gen_max_memcg(struct mem_cgroup *memcg, int nid) 4429 { 4430 struct lruvec *lruvec = get_lruvec(memcg, nid); 4431 int type; 4432 4433 for (type = 0; type < ANON_AND_FILE; type++) { 4434 if (get_nr_gens(lruvec, type) != MAX_NR_GENS) 4435 return false; 4436 } 4437 4438 return true; 4439 } 4440 4441 static void try_to_inc_max_seq_nowalk(struct mem_cgroup *memcg, 4442 struct lruvec *lruvec) 4443 { 4444 struct lru_gen_mm_list *mm_list = get_mm_list(memcg); 4445 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec); 4446 int swappiness = mem_cgroup_swappiness(memcg); 4447 DEFINE_MAX_SEQ(lruvec); 4448 bool success = false; 4449 4450 /* 4451 * We are not iterating the mm_list here, updating mm_state->seq is just 4452 * to make mm walkers work properly. 4453 */ 4454 if (mm_state) { 4455 spin_lock(&mm_list->lock); 4456 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq); 4457 if (max_seq > mm_state->seq) { 4458 WRITE_ONCE(mm_state->seq, mm_state->seq + 1); 4459 success = true; 4460 } 4461 spin_unlock(&mm_list->lock); 4462 } else { 4463 success = true; 4464 } 4465 4466 if (success) 4467 inc_max_seq(lruvec, max_seq, swappiness); 4468 } 4469 4470 /* 4471 * We need to ensure that the folios of child memcg can be reparented to the 4472 * same gen of the parent memcg, so the gens of the parent memcg needed be 4473 * incremented to the MAX_NR_GENS before reparenting. 4474 */ 4475 void max_lru_gen_memcg(struct mem_cgroup *memcg, int nid) 4476 { 4477 struct lruvec *lruvec = get_lruvec(memcg, nid); 4478 int type; 4479 4480 for (type = 0; type < ANON_AND_FILE; type++) { 4481 while (get_nr_gens(lruvec, type) < MAX_NR_GENS) { 4482 try_to_inc_max_seq_nowalk(memcg, lruvec); 4483 cond_resched(); 4484 } 4485 } 4486 } 4487 4488 /* 4489 * Compared to traditional LRU, MGLRU faces the following challenges: 4490 * 4491 * 1. Each lruvec has between MIN_NR_GENS and MAX_NR_GENS generations, the 4492 * number of generations of the parent and child memcg may be different, 4493 * so we cannot simply transfer MGLRU folios in the child memcg to the 4494 * parent memcg as we did for traditional LRU folios. 4495 * 2. The generation information is stored in folio->flags, but we cannot 4496 * traverse these folios while holding the lru lock, otherwise it may 4497 * cause softlockup. 4498 * 3. In walk_update_folio(), the gen of folio and corresponding lru size 4499 * may be updated, but the folio is not immediately moved to the 4500 * corresponding lru list. Therefore, there may be folios of different 4501 * generations on an LRU list. 4502 * 4. In lru_gen_del_folio(), the generation to which the folio belongs is 4503 * found based on the generation information in folio->flags, and the 4504 * corresponding LRU size will be updated. Therefore, we need to update 4505 * the lru size correctly during reparenting, otherwise the lru size may 4506 * be updated incorrectly in lru_gen_del_folio(). 4507 * 4508 * Finally, we choose a compromise method, which is to splice the lru list in 4509 * the child memcg to the lru list of the same generation in the parent memcg 4510 * during reparenting. 4511 * 4512 * The same generation has different meanings in the parent and child memcg, 4513 * so this compromise method will cause the LRU inversion problem. But as the 4514 * system runs, this problem will be fixed automatically. 4515 */ 4516 static void __lru_gen_reparent_memcg(struct lruvec *child_lruvec, struct lruvec *parent_lruvec, 4517 int zone, int type) 4518 { 4519 struct lru_gen_folio *child_lrugen, *parent_lrugen; 4520 enum lru_list lru = type * LRU_INACTIVE_FILE; 4521 int i; 4522 4523 child_lrugen = &child_lruvec->lrugen; 4524 parent_lrugen = &parent_lruvec->lrugen; 4525 4526 for (i = 0; i < get_nr_gens(child_lruvec, type); i++) { 4527 int gen = lru_gen_from_seq(child_lrugen->max_seq - i); 4528 long nr_pages = child_lrugen->nr_pages[gen][type][zone]; 4529 int child_lru_active = lru_gen_is_active(child_lruvec, gen) ? LRU_ACTIVE : 0; 4530 int parent_lru_active = lru_gen_is_active(parent_lruvec, gen) ? LRU_ACTIVE : 0; 4531 4532 /* Assuming that child pages are colder than parent pages */ 4533 list_splice_tail_init(&child_lrugen->folios[gen][type][zone], 4534 &parent_lrugen->folios[gen][type][zone]); 4535 4536 WRITE_ONCE(child_lrugen->nr_pages[gen][type][zone], 0); 4537 WRITE_ONCE(parent_lrugen->nr_pages[gen][type][zone], 4538 parent_lrugen->nr_pages[gen][type][zone] + nr_pages); 4539 4540 if (lru_gen_is_active(child_lruvec, gen) != lru_gen_is_active(parent_lruvec, gen)) { 4541 __update_lru_size(child_lruvec, lru + child_lru_active, zone, -nr_pages); 4542 __update_lru_size(parent_lruvec, lru + parent_lru_active, zone, nr_pages); 4543 } 4544 } 4545 } 4546 4547 void lru_gen_reparent_memcg(struct mem_cgroup *memcg, struct mem_cgroup *parent, int nid) 4548 { 4549 struct lruvec *child_lruvec, *parent_lruvec; 4550 int type, zid; 4551 struct zone *zone; 4552 enum lru_list lru; 4553 4554 child_lruvec = get_lruvec(memcg, nid); 4555 parent_lruvec = get_lruvec(parent, nid); 4556 4557 for_each_managed_zone_pgdat(zone, NODE_DATA(nid), zid, MAX_NR_ZONES - 1) 4558 for (type = 0; type < ANON_AND_FILE; type++) 4559 __lru_gen_reparent_memcg(child_lruvec, parent_lruvec, zid, type); 4560 4561 for_each_lru(lru) { 4562 for_each_managed_zone_pgdat(zone, NODE_DATA(nid), zid, MAX_NR_ZONES - 1) { 4563 unsigned long size = mem_cgroup_get_zone_lru_size(child_lruvec, lru, zid); 4564 4565 mem_cgroup_update_lru_size(parent_lruvec, lru, zid, size); 4566 } 4567 } 4568 } 4569 4570 #endif /* CONFIG_MEMCG */ 4571 4572 /****************************************************************************** 4573 * the eviction 4574 ******************************************************************************/ 4575 4576 static bool sort_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc, 4577 int tier_idx) 4578 { 4579 bool success; 4580 bool dirty, writeback; 4581 int gen = folio_lru_gen(folio); 4582 int type = folio_is_file_lru(folio); 4583 int zone = folio_zonenum(folio); 4584 int delta = folio_nr_pages(folio); 4585 int refs = folio_lru_refs(folio); 4586 bool workingset = folio_test_workingset(folio); 4587 int tier = lru_tier_from_refs(refs, workingset); 4588 struct lru_gen_folio *lrugen = &lruvec->lrugen; 4589 4590 VM_WARN_ON_ONCE_FOLIO(gen >= MAX_NR_GENS, folio); 4591 4592 /* unevictable */ 4593 if (!folio_evictable(folio)) { 4594 success = lru_gen_del_folio(lruvec, folio, true); 4595 VM_WARN_ON_ONCE_FOLIO(!success, folio); 4596 folio_set_unevictable(folio); 4597 lruvec_add_folio(lruvec, folio); 4598 __count_vm_events(UNEVICTABLE_PGCULLED, delta); 4599 return true; 4600 } 4601 4602 /* promoted */ 4603 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) { 4604 list_move(&folio->lru, &lrugen->folios[gen][type][zone]); 4605 return true; 4606 } 4607 4608 /* protected */ 4609 if (tier > tier_idx || refs + workingset == BIT(LRU_REFS_WIDTH) + 1) { 4610 gen = folio_inc_gen(lruvec, folio, false); 4611 list_move(&folio->lru, &lrugen->folios[gen][type][zone]); 4612 4613 /* don't count the workingset being lazily promoted */ 4614 if (refs + workingset != BIT(LRU_REFS_WIDTH) + 1) { 4615 int hist = lru_hist_from_seq(lrugen->min_seq[type]); 4616 4617 WRITE_ONCE(lrugen->protected[hist][type][tier], 4618 lrugen->protected[hist][type][tier] + delta); 4619 } 4620 return true; 4621 } 4622 4623 /* ineligible */ 4624 if (zone > sc->reclaim_idx) { 4625 gen = folio_inc_gen(lruvec, folio, false); 4626 list_move_tail(&folio->lru, &lrugen->folios[gen][type][zone]); 4627 return true; 4628 } 4629 4630 dirty = folio_test_dirty(folio); 4631 writeback = folio_test_writeback(folio); 4632 if (type == LRU_GEN_FILE && dirty) { 4633 sc->nr.file_taken += delta; 4634 if (!writeback) 4635 sc->nr.unqueued_dirty += delta; 4636 } 4637 4638 /* waiting for writeback */ 4639 if (writeback || (type == LRU_GEN_FILE && dirty)) { 4640 gen = folio_inc_gen(lruvec, folio, true); 4641 list_move(&folio->lru, &lrugen->folios[gen][type][zone]); 4642 return true; 4643 } 4644 4645 return false; 4646 } 4647 4648 static bool isolate_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc) 4649 { 4650 bool success; 4651 4652 /* swap constrained */ 4653 if (!(sc->gfp_mask & __GFP_IO) && 4654 (folio_test_dirty(folio) || 4655 (folio_test_anon(folio) && !folio_test_swapcache(folio)))) 4656 return false; 4657 4658 /* raced with release_pages() */ 4659 if (!folio_try_get(folio)) 4660 return false; 4661 4662 /* raced with another isolation */ 4663 if (!folio_test_clear_lru(folio)) { 4664 folio_put(folio); 4665 return false; 4666 } 4667 4668 /* see the comment on LRU_REFS_FLAGS */ 4669 if (!folio_test_referenced(folio)) 4670 set_mask_bits(&folio->flags.f, LRU_REFS_MASK, 0); 4671 4672 /* for shrink_folio_list() */ 4673 folio_clear_reclaim(folio); 4674 4675 success = lru_gen_del_folio(lruvec, folio, true); 4676 VM_WARN_ON_ONCE_FOLIO(!success, folio); 4677 4678 return true; 4679 } 4680 4681 static int scan_folios(unsigned long nr_to_scan, struct lruvec *lruvec, 4682 struct scan_control *sc, int type, int tier, 4683 struct list_head *list) 4684 { 4685 int i; 4686 int gen; 4687 enum node_stat_item item; 4688 int sorted = 0; 4689 int scanned = 0; 4690 int isolated = 0; 4691 int skipped = 0; 4692 int scan_batch = min(nr_to_scan, MAX_LRU_BATCH); 4693 int remaining = scan_batch; 4694 struct lru_gen_folio *lrugen = &lruvec->lrugen; 4695 4696 VM_WARN_ON_ONCE(!list_empty(list)); 4697 4698 if (get_nr_gens(lruvec, type) == MIN_NR_GENS) 4699 return 0; 4700 4701 gen = lru_gen_from_seq(lrugen->min_seq[type]); 4702 4703 for (i = MAX_NR_ZONES; i > 0; i--) { 4704 LIST_HEAD(moved); 4705 int skipped_zone = 0; 4706 int zone = (sc->reclaim_idx + i) % MAX_NR_ZONES; 4707 struct list_head *head = &lrugen->folios[gen][type][zone]; 4708 4709 while (!list_empty(head)) { 4710 struct folio *folio = lru_to_folio(head); 4711 int delta = folio_nr_pages(folio); 4712 4713 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio); 4714 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio); 4715 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio); 4716 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio); 4717 4718 scanned += delta; 4719 4720 if (sort_folio(lruvec, folio, sc, tier)) 4721 sorted += delta; 4722 else if (isolate_folio(lruvec, folio, sc)) { 4723 list_add(&folio->lru, list); 4724 isolated += delta; 4725 } else { 4726 list_move(&folio->lru, &moved); 4727 skipped_zone += delta; 4728 } 4729 4730 if (!--remaining || max(isolated, skipped_zone) >= MIN_LRU_BATCH) 4731 break; 4732 } 4733 4734 if (skipped_zone) { 4735 list_splice(&moved, head); 4736 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped_zone); 4737 skipped += skipped_zone; 4738 } 4739 4740 if (!remaining || isolated >= MIN_LRU_BATCH) 4741 break; 4742 } 4743 4744 item = PGSCAN_KSWAPD + reclaimer_offset(sc); 4745 mod_lruvec_state(lruvec, item, isolated); 4746 mod_lruvec_state(lruvec, PGREFILL, sorted); 4747 mod_lruvec_state(lruvec, PGSCAN_ANON + type, isolated); 4748 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, scan_batch, 4749 scanned, skipped, isolated, 4750 type ? LRU_INACTIVE_FILE : LRU_INACTIVE_ANON); 4751 if (type == LRU_GEN_FILE) 4752 sc->nr.file_taken += isolated; 4753 /* 4754 * There might not be eligible folios due to reclaim_idx. Check the 4755 * remaining to prevent livelock if it's not making progress. 4756 */ 4757 return isolated || !remaining ? scanned : 0; 4758 } 4759 4760 static int get_tier_idx(struct lruvec *lruvec, int type) 4761 { 4762 int tier; 4763 struct ctrl_pos sp, pv = {}; 4764 4765 /* 4766 * To leave a margin for fluctuations, use a larger gain factor (2:3). 4767 * This value is chosen because any other tier would have at least twice 4768 * as many refaults as the first tier. 4769 */ 4770 read_ctrl_pos(lruvec, type, 0, 2, &sp); 4771 for (tier = 1; tier < MAX_NR_TIERS; tier++) { 4772 read_ctrl_pos(lruvec, type, tier, 3, &pv); 4773 if (!positive_ctrl_err(&sp, &pv)) 4774 break; 4775 } 4776 4777 return tier - 1; 4778 } 4779 4780 static int get_type_to_scan(struct lruvec *lruvec, int swappiness) 4781 { 4782 struct ctrl_pos sp, pv = {}; 4783 4784 if (swappiness <= MIN_SWAPPINESS + 1) 4785 return LRU_GEN_FILE; 4786 4787 if (swappiness >= MAX_SWAPPINESS) 4788 return LRU_GEN_ANON; 4789 /* 4790 * Compare the sum of all tiers of anon with that of file to determine 4791 * which type to scan. 4792 */ 4793 read_ctrl_pos(lruvec, LRU_GEN_ANON, MAX_NR_TIERS, swappiness, &sp); 4794 read_ctrl_pos(lruvec, LRU_GEN_FILE, MAX_NR_TIERS, MAX_SWAPPINESS - swappiness, &pv); 4795 4796 return positive_ctrl_err(&sp, &pv); 4797 } 4798 4799 static int isolate_folios(unsigned long nr_to_scan, struct lruvec *lruvec, 4800 struct scan_control *sc, int swappiness, 4801 int *type_scanned, struct list_head *list) 4802 { 4803 int i; 4804 int type = get_type_to_scan(lruvec, swappiness); 4805 4806 for_each_evictable_type(i, swappiness) { 4807 int scanned; 4808 int tier = get_tier_idx(lruvec, type); 4809 4810 *type_scanned = type; 4811 4812 scanned = scan_folios(nr_to_scan, lruvec, sc, type, tier, list); 4813 if (scanned) 4814 return scanned; 4815 4816 type = !type; 4817 } 4818 4819 return 0; 4820 } 4821 4822 static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec, 4823 struct scan_control *sc, int swappiness) 4824 { 4825 int type; 4826 int scanned; 4827 int reclaimed; 4828 LIST_HEAD(list); 4829 LIST_HEAD(clean); 4830 struct folio *folio; 4831 struct folio *next; 4832 enum node_stat_item item; 4833 struct reclaim_stat stat; 4834 struct lru_gen_mm_walk *walk; 4835 bool skip_retry = false; 4836 struct lru_gen_folio *lrugen = &lruvec->lrugen; 4837 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 4838 struct pglist_data *pgdat = lruvec_pgdat(lruvec); 4839 4840 lruvec_lock_irq(lruvec); 4841 4842 scanned = isolate_folios(nr_to_scan, lruvec, sc, swappiness, &type, &list); 4843 4844 scanned += try_to_inc_min_seq(lruvec, swappiness); 4845 4846 if (evictable_min_seq(lrugen->min_seq, swappiness) + MIN_NR_GENS > lrugen->max_seq) 4847 scanned = 0; 4848 4849 lruvec_unlock_irq(lruvec); 4850 4851 if (list_empty(&list)) 4852 return scanned; 4853 retry: 4854 reclaimed = shrink_folio_list(&list, pgdat, sc, &stat, false, memcg); 4855 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty; 4856 sc->nr_reclaimed += reclaimed; 4857 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id, 4858 scanned, reclaimed, &stat, sc->priority, 4859 type ? LRU_INACTIVE_FILE : LRU_INACTIVE_ANON); 4860 4861 list_for_each_entry_safe_reverse(folio, next, &list, lru) { 4862 DEFINE_MIN_SEQ(lruvec); 4863 4864 if (!folio_evictable(folio)) { 4865 list_del(&folio->lru); 4866 folio_putback_lru(folio); 4867 continue; 4868 } 4869 4870 /* retry folios that may have missed folio_rotate_reclaimable() */ 4871 if (!skip_retry && !folio_test_active(folio) && !folio_mapped(folio) && 4872 !folio_test_dirty(folio) && !folio_test_writeback(folio)) { 4873 list_move(&folio->lru, &clean); 4874 continue; 4875 } 4876 4877 /* don't add rejected folios to the oldest generation */ 4878 if (lru_gen_folio_seq(lruvec, folio, false) == min_seq[type]) 4879 set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS, BIT(PG_active)); 4880 } 4881 4882 move_folios_to_lru(&list); 4883 4884 walk = current->reclaim_state->mm_walk; 4885 if (walk && walk->batched) { 4886 walk->lruvec = lruvec; 4887 lruvec_lock_irq(lruvec); 4888 reset_batch_size(walk); 4889 lruvec_unlock_irq(lruvec); 4890 } 4891 4892 mod_lruvec_state(lruvec, PGDEMOTE_KSWAPD + reclaimer_offset(sc), 4893 stat.nr_demoted); 4894 4895 item = PGSTEAL_KSWAPD + reclaimer_offset(sc); 4896 mod_lruvec_state(lruvec, item, reclaimed); 4897 mod_lruvec_state(lruvec, PGSTEAL_ANON + type, reclaimed); 4898 4899 list_splice_init(&clean, &list); 4900 4901 if (!list_empty(&list)) { 4902 skip_retry = true; 4903 goto retry; 4904 } 4905 4906 return scanned; 4907 } 4908 4909 static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, 4910 int swappiness, unsigned long *nr_to_scan) 4911 { 4912 int gen, type, zone; 4913 unsigned long size = 0; 4914 struct lru_gen_folio *lrugen = &lruvec->lrugen; 4915 DEFINE_MIN_SEQ(lruvec); 4916 4917 *nr_to_scan = 0; 4918 /* have to run aging, since eviction is not possible anymore */ 4919 if (evictable_min_seq(min_seq, swappiness) + MIN_NR_GENS > max_seq) 4920 return true; 4921 4922 for_each_evictable_type(type, swappiness) { 4923 unsigned long seq; 4924 4925 for (seq = min_seq[type]; seq <= max_seq; seq++) { 4926 gen = lru_gen_from_seq(seq); 4927 4928 for (zone = 0; zone < MAX_NR_ZONES; zone++) 4929 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L); 4930 } 4931 } 4932 4933 *nr_to_scan = size; 4934 /* better to run aging even though eviction is still possible */ 4935 return evictable_min_seq(min_seq, swappiness) + MIN_NR_GENS == max_seq; 4936 } 4937 4938 /* 4939 * For future optimizations: 4940 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg 4941 * reclaim. 4942 */ 4943 static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, int swappiness) 4944 { 4945 bool success; 4946 unsigned long nr_to_scan; 4947 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 4948 DEFINE_MAX_SEQ(lruvec); 4949 4950 if (mem_cgroup_below_min(sc->target_mem_cgroup, memcg)) 4951 return -1; 4952 4953 success = should_run_aging(lruvec, max_seq, swappiness, &nr_to_scan); 4954 4955 /* try to scrape all its memory if this memcg was deleted */ 4956 if (nr_to_scan && !mem_cgroup_online(memcg)) 4957 return nr_to_scan; 4958 4959 nr_to_scan = apply_proportional_protection(memcg, sc, nr_to_scan); 4960 4961 /* try to get away with not aging at the default priority */ 4962 if (!success || sc->priority == DEF_PRIORITY) 4963 return nr_to_scan >> sc->priority; 4964 4965 /* stop scanning this lruvec as it's low on cold folios */ 4966 return try_to_inc_max_seq(lruvec, max_seq, swappiness, false) ? -1 : 0; 4967 } 4968 4969 static bool should_abort_scan(struct lruvec *lruvec, struct scan_control *sc) 4970 { 4971 int i; 4972 enum zone_watermarks mark; 4973 4974 if (sc->nr_reclaimed >= max(sc->nr_to_reclaim, compact_gap(sc->order))) 4975 return true; 4976 4977 /* check the order to exclude compaction-induced reclaim */ 4978 if (!current_is_kswapd() || sc->order) 4979 return false; 4980 4981 mark = sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ? 4982 WMARK_PROMO : WMARK_HIGH; 4983 4984 for (i = 0; i <= sc->reclaim_idx; i++) { 4985 struct zone *zone = lruvec_pgdat(lruvec)->node_zones + i; 4986 unsigned long size = wmark_pages(zone, mark) + MIN_LRU_BATCH; 4987 4988 if (managed_zone(zone) && !zone_watermark_ok(zone, 0, size, sc->reclaim_idx, 0)) 4989 return false; 4990 } 4991 4992 /* kswapd should abort if all eligible zones are safe */ 4993 return true; 4994 } 4995 4996 static bool try_to_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc) 4997 { 4998 long nr_to_scan; 4999 unsigned long scanned = 0; 5000 int swappiness = get_swappiness(lruvec, sc); 5001 5002 while (true) { 5003 int delta; 5004 5005 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness); 5006 if (nr_to_scan <= 0) 5007 break; 5008 5009 delta = evict_folios(nr_to_scan, lruvec, sc, swappiness); 5010 if (!delta) 5011 break; 5012 5013 scanned += delta; 5014 if (scanned >= nr_to_scan) 5015 break; 5016 5017 if (should_abort_scan(lruvec, sc)) 5018 break; 5019 5020 cond_resched(); 5021 } 5022 5023 /* 5024 * If too many file cache in the coldest generation can't be evicted 5025 * due to being dirty, wake up the flusher. 5026 */ 5027 if (sc->nr.unqueued_dirty && sc->nr.unqueued_dirty == sc->nr.file_taken) { 5028 struct pglist_data *pgdat = lruvec_pgdat(lruvec); 5029 5030 wakeup_flusher_threads(WB_REASON_VMSCAN); 5031 5032 /* 5033 * For cgroupv1 dirty throttling is achieved by waking up 5034 * the kernel flusher here and later waiting on folios 5035 * which are in writeback to finish (see shrink_folio_list()). 5036 * 5037 * Flusher may not be able to issue writeback quickly 5038 * enough for cgroupv1 writeback throttling to work 5039 * on a large system. 5040 */ 5041 if (!writeback_throttling_sane(sc)) 5042 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK); 5043 } 5044 5045 /* whether this lruvec should be rotated */ 5046 return nr_to_scan < 0; 5047 } 5048 5049 static int shrink_one(struct lruvec *lruvec, struct scan_control *sc) 5050 { 5051 bool success; 5052 unsigned long scanned = sc->nr_scanned; 5053 unsigned long reclaimed = sc->nr_reclaimed; 5054 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 5055 struct pglist_data *pgdat = lruvec_pgdat(lruvec); 5056 5057 /* lru_gen_age_node() called mem_cgroup_calculate_protection() */ 5058 if (mem_cgroup_below_min(NULL, memcg)) 5059 return MEMCG_LRU_YOUNG; 5060 5061 if (mem_cgroup_below_low(NULL, memcg)) { 5062 /* see the comment on MEMCG_NR_GENS */ 5063 if (READ_ONCE(lruvec->lrugen.seg) != MEMCG_LRU_TAIL) 5064 return MEMCG_LRU_TAIL; 5065 5066 memcg_memory_event(memcg, MEMCG_LOW); 5067 } 5068 5069 success = try_to_shrink_lruvec(lruvec, sc); 5070 5071 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, sc->priority); 5072 5073 if (!sc->proactive) 5074 vmpressure(sc->gfp_mask, memcg, false, sc->nr_scanned - scanned, 5075 sc->nr_reclaimed - reclaimed); 5076 5077 flush_reclaim_state(sc); 5078 5079 if (success && mem_cgroup_online(memcg)) 5080 return MEMCG_LRU_YOUNG; 5081 5082 if (!success && lruvec_is_sizable(lruvec, sc)) 5083 return 0; 5084 5085 /* one retry if offlined or too small */ 5086 return READ_ONCE(lruvec->lrugen.seg) != MEMCG_LRU_TAIL ? 5087 MEMCG_LRU_TAIL : MEMCG_LRU_YOUNG; 5088 } 5089 5090 static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc) 5091 { 5092 int op; 5093 int gen; 5094 int bin; 5095 int first_bin; 5096 struct lruvec *lruvec; 5097 struct lru_gen_folio *lrugen; 5098 struct mem_cgroup *memcg; 5099 struct hlist_nulls_node *pos; 5100 5101 gen = get_memcg_gen(READ_ONCE(pgdat->memcg_lru.seq)); 5102 bin = first_bin = get_random_u32_below(MEMCG_NR_BINS); 5103 restart: 5104 op = 0; 5105 memcg = NULL; 5106 5107 rcu_read_lock(); 5108 5109 hlist_nulls_for_each_entry_rcu(lrugen, pos, &pgdat->memcg_lru.fifo[gen][bin], list) { 5110 if (op) { 5111 lru_gen_rotate_memcg(lruvec, op); 5112 op = 0; 5113 } 5114 5115 mem_cgroup_put(memcg); 5116 memcg = NULL; 5117 5118 if (gen != READ_ONCE(lrugen->gen)) 5119 continue; 5120 5121 lruvec = container_of(lrugen, struct lruvec, lrugen); 5122 memcg = lruvec_memcg(lruvec); 5123 5124 if (!mem_cgroup_tryget(memcg)) { 5125 lru_gen_release_memcg(memcg); 5126 memcg = NULL; 5127 continue; 5128 } 5129 5130 rcu_read_unlock(); 5131 5132 op = shrink_one(lruvec, sc); 5133 5134 rcu_read_lock(); 5135 5136 if (should_abort_scan(lruvec, sc)) 5137 break; 5138 } 5139 5140 rcu_read_unlock(); 5141 5142 if (op) 5143 lru_gen_rotate_memcg(lruvec, op); 5144 5145 mem_cgroup_put(memcg); 5146 5147 if (!is_a_nulls(pos)) 5148 return; 5149 5150 /* restart if raced with lru_gen_rotate_memcg() */ 5151 if (gen != get_nulls_value(pos)) 5152 goto restart; 5153 5154 /* try the rest of the bins of the current generation */ 5155 bin = get_memcg_bin(bin + 1); 5156 if (bin != first_bin) 5157 goto restart; 5158 } 5159 5160 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc) 5161 { 5162 struct blk_plug plug; 5163 5164 VM_WARN_ON_ONCE(root_reclaim(sc)); 5165 VM_WARN_ON_ONCE(!sc->may_writepage || !sc->may_unmap); 5166 5167 lru_add_drain(); 5168 5169 blk_start_plug(&plug); 5170 5171 set_mm_walk(NULL, sc->proactive); 5172 5173 if (try_to_shrink_lruvec(lruvec, sc)) 5174 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_YOUNG); 5175 5176 clear_mm_walk(); 5177 5178 blk_finish_plug(&plug); 5179 } 5180 5181 static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc) 5182 { 5183 struct blk_plug plug; 5184 unsigned long reclaimed = sc->nr_reclaimed; 5185 5186 VM_WARN_ON_ONCE(!root_reclaim(sc)); 5187 5188 /* 5189 * Unmapped clean folios are already prioritized. Scanning for more of 5190 * them is likely futile and can cause high reclaim latency when there 5191 * is a large number of memcgs. 5192 */ 5193 if (!sc->may_writepage || !sc->may_unmap) 5194 goto done; 5195 5196 lru_add_drain(); 5197 5198 blk_start_plug(&plug); 5199 5200 set_mm_walk(pgdat, sc->proactive); 5201 5202 set_initial_priority(pgdat, sc); 5203 5204 if (current_is_kswapd()) 5205 sc->nr_reclaimed = 0; 5206 5207 if (mem_cgroup_disabled()) 5208 shrink_one(&pgdat->__lruvec, sc); 5209 else 5210 shrink_many(pgdat, sc); 5211 5212 if (current_is_kswapd()) 5213 sc->nr_reclaimed += reclaimed; 5214 5215 clear_mm_walk(); 5216 5217 blk_finish_plug(&plug); 5218 done: 5219 if (sc->nr_reclaimed > reclaimed) 5220 kswapd_try_clear_hopeless(pgdat, sc->order, sc->reclaim_idx); 5221 } 5222 5223 /****************************************************************************** 5224 * state change 5225 ******************************************************************************/ 5226 5227 static bool __maybe_unused state_is_valid(struct lruvec *lruvec) 5228 { 5229 struct lru_gen_folio *lrugen = &lruvec->lrugen; 5230 5231 if (lrugen->enabled) { 5232 enum lru_list lru; 5233 5234 for_each_evictable_lru(lru) { 5235 if (!list_empty(&lruvec->lists[lru])) 5236 return false; 5237 } 5238 } else { 5239 int gen, type, zone; 5240 5241 for_each_gen_type_zone(gen, type, zone) { 5242 if (!list_empty(&lrugen->folios[gen][type][zone])) 5243 return false; 5244 } 5245 } 5246 5247 return true; 5248 } 5249 5250 static bool fill_evictable(struct lruvec *lruvec) 5251 { 5252 enum lru_list lru; 5253 int remaining = MAX_LRU_BATCH; 5254 5255 for_each_evictable_lru(lru) { 5256 int type = is_file_lru(lru); 5257 bool active = is_active_lru(lru); 5258 struct list_head *head = &lruvec->lists[lru]; 5259 5260 while (!list_empty(head)) { 5261 bool success; 5262 struct folio *folio = lru_to_folio(head); 5263 5264 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio); 5265 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio) != active, folio); 5266 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio); 5267 VM_WARN_ON_ONCE_FOLIO(folio_lru_gen(folio) != -1, folio); 5268 5269 lruvec_del_folio(lruvec, folio); 5270 success = lru_gen_add_folio(lruvec, folio, false); 5271 VM_WARN_ON_ONCE(!success); 5272 5273 if (!--remaining) 5274 return false; 5275 } 5276 } 5277 5278 return true; 5279 } 5280 5281 static bool drain_evictable(struct lruvec *lruvec) 5282 { 5283 int gen, type, zone; 5284 int remaining = MAX_LRU_BATCH; 5285 5286 for_each_gen_type_zone(gen, type, zone) { 5287 struct list_head *head = &lruvec->lrugen.folios[gen][type][zone]; 5288 5289 while (!list_empty(head)) { 5290 bool success; 5291 struct folio *folio = lru_to_folio(head); 5292 5293 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio); 5294 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio); 5295 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio); 5296 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio); 5297 5298 success = lru_gen_del_folio(lruvec, folio, false); 5299 VM_WARN_ON_ONCE(!success); 5300 lruvec_add_folio(lruvec, folio); 5301 5302 if (!--remaining) 5303 return false; 5304 } 5305 } 5306 5307 return true; 5308 } 5309 5310 static void lru_gen_change_state(bool enabled) 5311 { 5312 static DEFINE_MUTEX(state_mutex); 5313 5314 struct mem_cgroup *memcg; 5315 5316 cgroup_lock(); 5317 cpus_read_lock(); 5318 get_online_mems(); 5319 mutex_lock(&state_mutex); 5320 5321 if (enabled == lru_gen_enabled()) 5322 goto unlock; 5323 5324 static_branch_enable_cpuslocked(&lru_switch); 5325 5326 if (enabled) 5327 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]); 5328 else 5329 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]); 5330 5331 memcg = mem_cgroup_iter(NULL, NULL, NULL); 5332 do { 5333 int nid; 5334 5335 for_each_node(nid) { 5336 struct lruvec *lruvec = get_lruvec(memcg, nid); 5337 5338 lruvec_lock_irq(lruvec); 5339 5340 VM_WARN_ON_ONCE(!seq_is_valid(lruvec)); 5341 VM_WARN_ON_ONCE(!state_is_valid(lruvec)); 5342 5343 lruvec->lrugen.enabled = enabled; 5344 5345 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) { 5346 lruvec_unlock_irq(lruvec); 5347 cond_resched(); 5348 lruvec_lock_irq(lruvec); 5349 } 5350 5351 lruvec_unlock_irq(lruvec); 5352 } 5353 5354 cond_resched(); 5355 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL))); 5356 5357 static_branch_disable_cpuslocked(&lru_switch); 5358 5359 unlock: 5360 mutex_unlock(&state_mutex); 5361 put_online_mems(); 5362 cpus_read_unlock(); 5363 cgroup_unlock(); 5364 } 5365 5366 /****************************************************************************** 5367 * sysfs interface 5368 ******************************************************************************/ 5369 5370 static ssize_t min_ttl_ms_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) 5371 { 5372 return sysfs_emit(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl))); 5373 } 5374 5375 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */ 5376 static ssize_t min_ttl_ms_store(struct kobject *kobj, struct kobj_attribute *attr, 5377 const char *buf, size_t len) 5378 { 5379 unsigned int msecs; 5380 5381 if (kstrtouint(buf, 0, &msecs)) 5382 return -EINVAL; 5383 5384 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs)); 5385 5386 return len; 5387 } 5388 5389 static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR_RW(min_ttl_ms); 5390 5391 static ssize_t enabled_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) 5392 { 5393 unsigned int caps = 0; 5394 5395 if (get_cap(LRU_GEN_CORE)) 5396 caps |= BIT(LRU_GEN_CORE); 5397 5398 if (should_walk_mmu()) 5399 caps |= BIT(LRU_GEN_MM_WALK); 5400 5401 if (should_clear_pmd_young()) 5402 caps |= BIT(LRU_GEN_NONLEAF_YOUNG); 5403 5404 return sysfs_emit(buf, "0x%04x\n", caps); 5405 } 5406 5407 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */ 5408 static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr, 5409 const char *buf, size_t len) 5410 { 5411 int i; 5412 unsigned int caps; 5413 5414 if (tolower(*buf) == 'n') 5415 caps = 0; 5416 else if (tolower(*buf) == 'y') 5417 caps = -1; 5418 else if (kstrtouint(buf, 0, &caps)) 5419 return -EINVAL; 5420 5421 for (i = 0; i < NR_LRU_GEN_CAPS; i++) { 5422 bool enabled = caps & BIT(i); 5423 5424 if (i == LRU_GEN_CORE) 5425 lru_gen_change_state(enabled); 5426 else if (enabled) 5427 static_branch_enable(&lru_gen_caps[i]); 5428 else 5429 static_branch_disable(&lru_gen_caps[i]); 5430 } 5431 5432 return len; 5433 } 5434 5435 static struct kobj_attribute lru_gen_enabled_attr = __ATTR_RW(enabled); 5436 5437 static struct attribute *lru_gen_attrs[] = { 5438 &lru_gen_min_ttl_attr.attr, 5439 &lru_gen_enabled_attr.attr, 5440 NULL 5441 }; 5442 5443 static const struct attribute_group lru_gen_attr_group = { 5444 .name = "lru_gen", 5445 .attrs = lru_gen_attrs, 5446 }; 5447 5448 /****************************************************************************** 5449 * debugfs interface 5450 ******************************************************************************/ 5451 5452 static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos) 5453 { 5454 struct mem_cgroup *memcg; 5455 loff_t nr_to_skip = *pos; 5456 5457 m->private = kvmalloc(PATH_MAX, GFP_KERNEL); 5458 if (!m->private) 5459 return ERR_PTR(-ENOMEM); 5460 5461 memcg = mem_cgroup_iter(NULL, NULL, NULL); 5462 do { 5463 int nid; 5464 5465 for_each_node_state(nid, N_MEMORY) { 5466 if (!nr_to_skip--) 5467 return get_lruvec(memcg, nid); 5468 } 5469 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL))); 5470 5471 return NULL; 5472 } 5473 5474 static void lru_gen_seq_stop(struct seq_file *m, void *v) 5475 { 5476 if (!IS_ERR_OR_NULL(v)) 5477 mem_cgroup_iter_break(NULL, lruvec_memcg(v)); 5478 5479 kvfree(m->private); 5480 m->private = NULL; 5481 } 5482 5483 static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos) 5484 { 5485 int nid = lruvec_pgdat(v)->node_id; 5486 struct mem_cgroup *memcg = lruvec_memcg(v); 5487 5488 ++*pos; 5489 5490 nid = next_memory_node(nid); 5491 if (nid == MAX_NUMNODES) { 5492 memcg = mem_cgroup_iter(NULL, memcg, NULL); 5493 if (!memcg) 5494 return NULL; 5495 5496 nid = first_memory_node; 5497 } 5498 5499 return get_lruvec(memcg, nid); 5500 } 5501 5502 static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec, 5503 unsigned long max_seq, unsigned long *min_seq, 5504 unsigned long seq) 5505 { 5506 int i; 5507 int type, tier; 5508 int hist = lru_hist_from_seq(seq); 5509 struct lru_gen_folio *lrugen = &lruvec->lrugen; 5510 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec); 5511 5512 for (tier = 0; tier < MAX_NR_TIERS; tier++) { 5513 seq_printf(m, " %10d", tier); 5514 for (type = 0; type < ANON_AND_FILE; type++) { 5515 const char *s = "xxx"; 5516 unsigned long n[3] = {}; 5517 5518 if (seq == max_seq) { 5519 s = "RTx"; 5520 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]); 5521 n[1] = READ_ONCE(lrugen->avg_total[type][tier]); 5522 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) { 5523 s = "rep"; 5524 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]); 5525 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]); 5526 n[2] = READ_ONCE(lrugen->protected[hist][type][tier]); 5527 } 5528 5529 for (i = 0; i < 3; i++) 5530 seq_printf(m, " %10lu%c", n[i], s[i]); 5531 } 5532 seq_putc(m, '\n'); 5533 } 5534 5535 if (!mm_state) 5536 return; 5537 5538 seq_puts(m, " "); 5539 for (i = 0; i < NR_MM_STATS; i++) { 5540 const char *s = "xxxx"; 5541 unsigned long n = 0; 5542 5543 if (seq == max_seq && NR_HIST_GENS == 1) { 5544 s = "TYFA"; 5545 n = READ_ONCE(mm_state->stats[hist][i]); 5546 } else if (seq != max_seq && NR_HIST_GENS > 1) { 5547 s = "tyfa"; 5548 n = READ_ONCE(mm_state->stats[hist][i]); 5549 } 5550 5551 seq_printf(m, " %10lu%c", n, s[i]); 5552 } 5553 seq_putc(m, '\n'); 5554 } 5555 5556 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */ 5557 static int lru_gen_seq_show(struct seq_file *m, void *v) 5558 { 5559 unsigned long seq; 5560 bool full = debugfs_get_aux_num(m->file); 5561 struct lruvec *lruvec = v; 5562 struct lru_gen_folio *lrugen = &lruvec->lrugen; 5563 int nid = lruvec_pgdat(lruvec)->node_id; 5564 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 5565 DEFINE_MAX_SEQ(lruvec); 5566 DEFINE_MIN_SEQ(lruvec); 5567 5568 if (nid == first_memory_node) { 5569 const char *path = memcg ? m->private : ""; 5570 5571 #ifdef CONFIG_MEMCG 5572 if (memcg) 5573 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX); 5574 #endif 5575 seq_printf(m, "memcg %llu %s\n", mem_cgroup_id(memcg), path); 5576 } 5577 5578 seq_printf(m, " node %5d\n", nid); 5579 5580 if (!full) 5581 seq = evictable_min_seq(min_seq, MAX_SWAPPINESS / 2); 5582 else if (max_seq >= MAX_NR_GENS) 5583 seq = max_seq - MAX_NR_GENS + 1; 5584 else 5585 seq = 0; 5586 5587 for (; seq <= max_seq; seq++) { 5588 int type, zone; 5589 int gen = lru_gen_from_seq(seq); 5590 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]); 5591 5592 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth)); 5593 5594 for (type = 0; type < ANON_AND_FILE; type++) { 5595 unsigned long size = 0; 5596 char mark = full && seq < min_seq[type] ? 'x' : ' '; 5597 5598 for (zone = 0; zone < MAX_NR_ZONES; zone++) 5599 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L); 5600 5601 seq_printf(m, " %10lu%c", size, mark); 5602 } 5603 5604 seq_putc(m, '\n'); 5605 5606 if (full) 5607 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq); 5608 } 5609 5610 return 0; 5611 } 5612 5613 static const struct seq_operations lru_gen_seq_ops = { 5614 .start = lru_gen_seq_start, 5615 .stop = lru_gen_seq_stop, 5616 .next = lru_gen_seq_next, 5617 .show = lru_gen_seq_show, 5618 }; 5619 5620 static int run_aging(struct lruvec *lruvec, unsigned long seq, 5621 int swappiness, bool force_scan) 5622 { 5623 DEFINE_MAX_SEQ(lruvec); 5624 5625 if (seq > max_seq) 5626 return -EINVAL; 5627 5628 return try_to_inc_max_seq(lruvec, max_seq, swappiness, force_scan) ? 0 : -EEXIST; 5629 } 5630 5631 static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc, 5632 int swappiness, unsigned long nr_to_reclaim) 5633 { 5634 DEFINE_MAX_SEQ(lruvec); 5635 5636 if (seq + MIN_NR_GENS > max_seq) 5637 return -EINVAL; 5638 5639 sc->nr_reclaimed = 0; 5640 5641 while (!signal_pending(current)) { 5642 DEFINE_MIN_SEQ(lruvec); 5643 5644 if (seq < evictable_min_seq(min_seq, swappiness)) 5645 return 0; 5646 5647 if (sc->nr_reclaimed >= nr_to_reclaim) 5648 return 0; 5649 5650 if (!evict_folios(nr_to_reclaim - sc->nr_reclaimed, lruvec, sc, 5651 swappiness)) 5652 return 0; 5653 5654 cond_resched(); 5655 } 5656 5657 return -EINTR; 5658 } 5659 5660 static int run_cmd(char cmd, u64 memcg_id, int nid, unsigned long seq, 5661 struct scan_control *sc, int swappiness, unsigned long opt) 5662 { 5663 struct lruvec *lruvec; 5664 int err = -EINVAL; 5665 struct mem_cgroup *memcg = NULL; 5666 5667 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY)) 5668 return -EINVAL; 5669 5670 if (!mem_cgroup_disabled()) { 5671 memcg = mem_cgroup_get_from_id(memcg_id); 5672 if (!memcg) 5673 return -EINVAL; 5674 } 5675 5676 if (memcg_id != mem_cgroup_id(memcg)) 5677 goto done; 5678 5679 sc->target_mem_cgroup = memcg; 5680 lruvec = get_lruvec(memcg, nid); 5681 5682 if (swappiness < MIN_SWAPPINESS) 5683 swappiness = get_swappiness(lruvec, sc); 5684 else if (swappiness > SWAPPINESS_ANON_ONLY) 5685 goto done; 5686 5687 switch (cmd) { 5688 case '+': 5689 err = run_aging(lruvec, seq, swappiness, opt); 5690 break; 5691 case '-': 5692 err = run_eviction(lruvec, seq, sc, swappiness, opt); 5693 break; 5694 } 5695 done: 5696 mem_cgroup_put(memcg); 5697 5698 return err; 5699 } 5700 5701 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */ 5702 static ssize_t lru_gen_seq_write(struct file *file, const char __user *src, 5703 size_t len, loff_t *pos) 5704 { 5705 void *buf; 5706 char *cur, *next; 5707 unsigned int flags; 5708 struct blk_plug plug; 5709 int err = -EINVAL; 5710 struct scan_control sc = { 5711 .may_writepage = true, 5712 .may_unmap = true, 5713 .may_swap = true, 5714 .reclaim_idx = MAX_NR_ZONES - 1, 5715 .gfp_mask = GFP_KERNEL, 5716 .proactive = true, 5717 }; 5718 5719 buf = kvmalloc(len + 1, GFP_KERNEL); 5720 if (!buf) 5721 return -ENOMEM; 5722 5723 if (copy_from_user(buf, src, len)) { 5724 kvfree(buf); 5725 return -EFAULT; 5726 } 5727 5728 set_task_reclaim_state(current, &sc.reclaim_state); 5729 flags = memalloc_noreclaim_save(); 5730 blk_start_plug(&plug); 5731 if (!set_mm_walk(NULL, true)) { 5732 err = -ENOMEM; 5733 goto done; 5734 } 5735 5736 next = buf; 5737 next[len] = '\0'; 5738 5739 while ((cur = strsep(&next, ",;\n"))) { 5740 int n; 5741 int end; 5742 char cmd, swap_string[5]; 5743 u64 memcg_id; 5744 unsigned int nid; 5745 unsigned long seq; 5746 unsigned int swappiness; 5747 unsigned long opt = -1; 5748 5749 cur = skip_spaces(cur); 5750 if (!*cur) 5751 continue; 5752 5753 n = sscanf(cur, "%c %llu %u %lu %n %4s %n %lu %n", &cmd, &memcg_id, &nid, 5754 &seq, &end, swap_string, &end, &opt, &end); 5755 if (n < 4 || cur[end]) { 5756 err = -EINVAL; 5757 break; 5758 } 5759 5760 if (n == 4) { 5761 swappiness = -1; 5762 } else if (!strcmp("max", swap_string)) { 5763 /* set by userspace for anonymous memory only */ 5764 swappiness = SWAPPINESS_ANON_ONLY; 5765 } else { 5766 err = kstrtouint(swap_string, 0, &swappiness); 5767 if (err) 5768 break; 5769 } 5770 5771 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt); 5772 if (err) 5773 break; 5774 } 5775 done: 5776 clear_mm_walk(); 5777 blk_finish_plug(&plug); 5778 memalloc_noreclaim_restore(flags); 5779 set_task_reclaim_state(current, NULL); 5780 5781 kvfree(buf); 5782 5783 return err ? : len; 5784 } 5785 5786 static int lru_gen_seq_open(struct inode *inode, struct file *file) 5787 { 5788 return seq_open(file, &lru_gen_seq_ops); 5789 } 5790 5791 static const struct file_operations lru_gen_rw_fops = { 5792 .open = lru_gen_seq_open, 5793 .read = seq_read, 5794 .write = lru_gen_seq_write, 5795 .llseek = seq_lseek, 5796 .release = seq_release, 5797 }; 5798 5799 static const struct file_operations lru_gen_ro_fops = { 5800 .open = lru_gen_seq_open, 5801 .read = seq_read, 5802 .llseek = seq_lseek, 5803 .release = seq_release, 5804 }; 5805 5806 /****************************************************************************** 5807 * initialization 5808 ******************************************************************************/ 5809 5810 void lru_gen_init_pgdat(struct pglist_data *pgdat) 5811 { 5812 int i, j; 5813 5814 spin_lock_init(&pgdat->memcg_lru.lock); 5815 5816 for (i = 0; i < MEMCG_NR_GENS; i++) { 5817 for (j = 0; j < MEMCG_NR_BINS; j++) 5818 INIT_HLIST_NULLS_HEAD(&pgdat->memcg_lru.fifo[i][j], i); 5819 } 5820 } 5821 5822 void lru_gen_init_lruvec(struct lruvec *lruvec) 5823 { 5824 int i; 5825 int gen, type, zone; 5826 struct lru_gen_folio *lrugen = &lruvec->lrugen; 5827 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec); 5828 5829 lrugen->max_seq = MIN_NR_GENS + 1; 5830 lrugen->enabled = lru_gen_enabled(); 5831 5832 for (i = 0; i <= MIN_NR_GENS + 1; i++) 5833 lrugen->timestamps[i] = jiffies; 5834 5835 for_each_gen_type_zone(gen, type, zone) 5836 INIT_LIST_HEAD(&lrugen->folios[gen][type][zone]); 5837 5838 if (mm_state) 5839 mm_state->seq = MIN_NR_GENS; 5840 } 5841 5842 #ifdef CONFIG_MEMCG 5843 5844 void lru_gen_init_memcg(struct mem_cgroup *memcg) 5845 { 5846 struct lru_gen_mm_list *mm_list = get_mm_list(memcg); 5847 5848 if (!mm_list) 5849 return; 5850 5851 INIT_LIST_HEAD(&mm_list->fifo); 5852 spin_lock_init(&mm_list->lock); 5853 } 5854 5855 void lru_gen_exit_memcg(struct mem_cgroup *memcg) 5856 { 5857 int i; 5858 int nid; 5859 struct lru_gen_mm_list *mm_list = get_mm_list(memcg); 5860 5861 VM_WARN_ON_ONCE(mm_list && !list_empty(&mm_list->fifo)); 5862 5863 for_each_node(nid) { 5864 struct lruvec *lruvec = get_lruvec(memcg, nid); 5865 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec); 5866 5867 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0, 5868 sizeof(lruvec->lrugen.nr_pages))); 5869 5870 lruvec->lrugen.list.next = LIST_POISON1; 5871 5872 if (!mm_state) 5873 continue; 5874 5875 for (i = 0; i < NR_BLOOM_FILTERS; i++) { 5876 bitmap_free(mm_state->filters[i]); 5877 mm_state->filters[i] = NULL; 5878 } 5879 } 5880 } 5881 5882 #endif /* CONFIG_MEMCG */ 5883 5884 static int __init init_lru_gen(void) 5885 { 5886 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS); 5887 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS); 5888 5889 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group)) 5890 pr_err("lru_gen: failed to create sysfs group\n"); 5891 5892 debugfs_create_file_aux_num("lru_gen", 0644, NULL, NULL, false, 5893 &lru_gen_rw_fops); 5894 debugfs_create_file_aux_num("lru_gen_full", 0444, NULL, NULL, true, 5895 &lru_gen_ro_fops); 5896 5897 return 0; 5898 }; 5899 late_initcall(init_lru_gen); 5900 5901 #else /* !CONFIG_LRU_GEN */ 5902 5903 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc) 5904 { 5905 BUILD_BUG(); 5906 } 5907 5908 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc) 5909 { 5910 BUILD_BUG(); 5911 } 5912 5913 static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc) 5914 { 5915 BUILD_BUG(); 5916 } 5917 5918 #endif /* CONFIG_LRU_GEN */ 5919 5920 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc) 5921 { 5922 unsigned long nr[NR_LRU_LISTS]; 5923 unsigned long targets[NR_LRU_LISTS]; 5924 unsigned long nr_to_scan; 5925 enum lru_list lru; 5926 unsigned long nr_reclaimed = 0; 5927 unsigned long nr_to_reclaim = sc->nr_to_reclaim; 5928 bool proportional_reclaim; 5929 struct blk_plug plug; 5930 5931 if ((lru_gen_enabled() || lru_gen_switching()) && !root_reclaim(sc)) { 5932 lru_gen_shrink_lruvec(lruvec, sc); 5933 5934 if (!lru_gen_switching()) 5935 return; 5936 5937 } 5938 5939 get_scan_count(lruvec, sc, nr); 5940 5941 /* Record the original scan target for proportional adjustments later */ 5942 memcpy(targets, nr, sizeof(nr)); 5943 5944 /* 5945 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal 5946 * event that can occur when there is little memory pressure e.g. 5947 * multiple streaming readers/writers. Hence, we do not abort scanning 5948 * when the requested number of pages are reclaimed when scanning at 5949 * DEF_PRIORITY on the assumption that the fact we are direct 5950 * reclaiming implies that kswapd is not keeping up and it is best to 5951 * do a batch of work at once. For memcg reclaim one check is made to 5952 * abort proportional reclaim if either the file or anon lru has already 5953 * dropped to zero at the first pass. 5954 */ 5955 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() && 5956 sc->priority == DEF_PRIORITY); 5957 5958 blk_start_plug(&plug); 5959 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] || 5960 nr[LRU_INACTIVE_FILE]) { 5961 unsigned long nr_anon, nr_file, percentage; 5962 unsigned long nr_scanned; 5963 5964 for_each_evictable_lru(lru) { 5965 if (nr[lru]) { 5966 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX); 5967 nr[lru] -= nr_to_scan; 5968 5969 nr_reclaimed += shrink_list(lru, nr_to_scan, 5970 lruvec, sc); 5971 } 5972 } 5973 5974 cond_resched(); 5975 5976 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim) 5977 continue; 5978 5979 /* 5980 * For kswapd and memcg, reclaim at least the number of pages 5981 * requested. Ensure that the anon and file LRUs are scanned 5982 * proportionally what was requested by get_scan_count(). We 5983 * stop reclaiming one LRU and reduce the amount scanning 5984 * proportional to the original scan target. 5985 */ 5986 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE]; 5987 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON]; 5988 5989 /* 5990 * It's just vindictive to attack the larger once the smaller 5991 * has gone to zero. And given the way we stop scanning the 5992 * smaller below, this makes sure that we only make one nudge 5993 * towards proportionality once we've got nr_to_reclaim. 5994 */ 5995 if (!nr_file || !nr_anon) 5996 break; 5997 5998 if (nr_file > nr_anon) { 5999 unsigned long scan_target = targets[LRU_INACTIVE_ANON] + 6000 targets[LRU_ACTIVE_ANON] + 1; 6001 lru = LRU_BASE; 6002 percentage = nr_anon * 100 / scan_target; 6003 } else { 6004 unsigned long scan_target = targets[LRU_INACTIVE_FILE] + 6005 targets[LRU_ACTIVE_FILE] + 1; 6006 lru = LRU_FILE; 6007 percentage = nr_file * 100 / scan_target; 6008 } 6009 6010 /* Stop scanning the smaller of the LRU */ 6011 nr[lru] = 0; 6012 nr[lru + LRU_ACTIVE] = 0; 6013 6014 /* 6015 * Recalculate the other LRU scan count based on its original 6016 * scan target and the percentage scanning already complete 6017 */ 6018 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE; 6019 nr_scanned = targets[lru] - nr[lru]; 6020 nr[lru] = targets[lru] * (100 - percentage) / 100; 6021 nr[lru] -= min(nr[lru], nr_scanned); 6022 6023 lru += LRU_ACTIVE; 6024 nr_scanned = targets[lru] - nr[lru]; 6025 nr[lru] = targets[lru] * (100 - percentage) / 100; 6026 nr[lru] -= min(nr[lru], nr_scanned); 6027 } 6028 blk_finish_plug(&plug); 6029 sc->nr_reclaimed += nr_reclaimed; 6030 6031 /* 6032 * Even if we did not try to evict anon pages at all, we want to 6033 * rebalance the anon lru active/inactive ratio. 6034 */ 6035 if (can_age_anon_pages(lruvec, sc) && 6036 inactive_is_low(lruvec, LRU_INACTIVE_ANON)) 6037 shrink_active_list(SWAP_CLUSTER_MAX, lruvec, 6038 sc, LRU_ACTIVE_ANON); 6039 } 6040 6041 /* Use reclaim/compaction for costly allocs or under memory pressure */ 6042 static bool in_reclaim_compaction(struct scan_control *sc) 6043 { 6044 if (gfp_compaction_allowed(sc->gfp_mask) && sc->order && 6045 (sc->order > PAGE_ALLOC_COSTLY_ORDER || 6046 sc->priority < DEF_PRIORITY - 2)) 6047 return true; 6048 6049 return false; 6050 } 6051 6052 /* 6053 * Reclaim/compaction is used for high-order allocation requests. It reclaims 6054 * order-0 pages before compacting the zone. should_continue_reclaim() returns 6055 * true if more pages should be reclaimed such that when the page allocator 6056 * calls try_to_compact_pages() that it will have enough free pages to succeed. 6057 * It will give up earlier than that if there is difficulty reclaiming pages. 6058 */ 6059 static inline bool should_continue_reclaim(struct pglist_data *pgdat, 6060 unsigned long nr_reclaimed, 6061 struct scan_control *sc) 6062 { 6063 unsigned long pages_for_compaction; 6064 unsigned long inactive_lru_pages; 6065 int z; 6066 struct zone *zone; 6067 6068 /* If not in reclaim/compaction mode, stop */ 6069 if (!in_reclaim_compaction(sc)) 6070 return false; 6071 6072 /* 6073 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX 6074 * number of pages that were scanned. This will return to the caller 6075 * with the risk reclaim/compaction and the resulting allocation attempt 6076 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL 6077 * allocations through requiring that the full LRU list has been scanned 6078 * first, by assuming that zero delta of sc->nr_scanned means full LRU 6079 * scan, but that approximation was wrong, and there were corner cases 6080 * where always a non-zero amount of pages were scanned. 6081 */ 6082 if (!nr_reclaimed) 6083 return false; 6084 6085 /* If compaction would go ahead or the allocation would succeed, stop */ 6086 for_each_managed_zone_pgdat(zone, pgdat, z, sc->reclaim_idx) { 6087 unsigned long watermark = min_wmark_pages(zone); 6088 6089 /* Allocation can already succeed, nothing to do */ 6090 if (zone_watermark_ok(zone, sc->order, watermark, 6091 sc->reclaim_idx, 0)) 6092 return false; 6093 6094 if (compaction_suitable(zone, sc->order, watermark, 6095 sc->reclaim_idx)) 6096 return false; 6097 } 6098 6099 /* 6100 * If we have not reclaimed enough pages for compaction and the 6101 * inactive lists are large enough, continue reclaiming 6102 */ 6103 pages_for_compaction = compact_gap(sc->order); 6104 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE); 6105 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc)) 6106 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON); 6107 6108 return inactive_lru_pages > pages_for_compaction; 6109 } 6110 6111 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc) 6112 { 6113 struct mem_cgroup *target_memcg = sc->target_mem_cgroup; 6114 struct mem_cgroup_reclaim_cookie reclaim = { 6115 .pgdat = pgdat, 6116 }; 6117 struct mem_cgroup_reclaim_cookie *partial = &reclaim; 6118 struct mem_cgroup *memcg; 6119 6120 /* 6121 * In most cases, direct reclaimers can do partial walks 6122 * through the cgroup tree, using an iterator state that 6123 * persists across invocations. This strikes a balance between 6124 * fairness and allocation latency. 6125 * 6126 * For kswapd, reliable forward progress is more important 6127 * than a quick return to idle. Always do full walks. 6128 */ 6129 if (current_is_kswapd() || sc->memcg_full_walk) 6130 partial = NULL; 6131 6132 memcg = mem_cgroup_iter(target_memcg, NULL, partial); 6133 do { 6134 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat); 6135 unsigned long reclaimed; 6136 unsigned long scanned; 6137 6138 /* 6139 * This loop can become CPU-bound when target memcgs 6140 * aren't eligible for reclaim - either because they 6141 * don't have any reclaimable pages, or because their 6142 * memory is explicitly protected. Avoid soft lockups. 6143 */ 6144 cond_resched(); 6145 6146 mem_cgroup_calculate_protection(target_memcg, memcg); 6147 6148 if (mem_cgroup_below_min(target_memcg, memcg)) { 6149 /* 6150 * Hard protection. 6151 * If there is no reclaimable memory, OOM. 6152 */ 6153 continue; 6154 } else if (mem_cgroup_below_low(target_memcg, memcg)) { 6155 /* 6156 * Soft protection. 6157 * Respect the protection only as long as 6158 * there is an unprotected supply 6159 * of reclaimable memory from other cgroups. 6160 */ 6161 if (!sc->memcg_low_reclaim) { 6162 sc->memcg_low_skipped = 1; 6163 continue; 6164 } 6165 memcg_memory_event(memcg, MEMCG_LOW); 6166 } 6167 6168 reclaimed = sc->nr_reclaimed; 6169 scanned = sc->nr_scanned; 6170 6171 shrink_lruvec(lruvec, sc); 6172 6173 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, 6174 sc->priority); 6175 6176 /* Record the group's reclaim efficiency */ 6177 if (!sc->proactive) 6178 vmpressure(sc->gfp_mask, memcg, false, 6179 sc->nr_scanned - scanned, 6180 sc->nr_reclaimed - reclaimed); 6181 6182 /* If partial walks are allowed, bail once goal is reached */ 6183 if (partial && sc->nr_reclaimed >= sc->nr_to_reclaim) { 6184 mem_cgroup_iter_break(target_memcg, memcg); 6185 break; 6186 } 6187 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, partial))); 6188 } 6189 6190 static void shrink_node(pg_data_t *pgdat, struct scan_control *sc) 6191 { 6192 unsigned long nr_reclaimed, nr_scanned, nr_node_reclaimed; 6193 struct lruvec *target_lruvec; 6194 bool reclaimable = false; 6195 6196 if ((lru_gen_enabled() || lru_gen_switching()) && root_reclaim(sc)) { 6197 memset(&sc->nr, 0, sizeof(sc->nr)); 6198 lru_gen_shrink_node(pgdat, sc); 6199 6200 if (!lru_gen_switching()) 6201 return; 6202 6203 } 6204 6205 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat); 6206 6207 again: 6208 memset(&sc->nr, 0, sizeof(sc->nr)); 6209 6210 nr_reclaimed = sc->nr_reclaimed; 6211 nr_scanned = sc->nr_scanned; 6212 6213 prepare_scan_control(pgdat, sc); 6214 6215 shrink_node_memcgs(pgdat, sc); 6216 6217 flush_reclaim_state(sc); 6218 6219 nr_node_reclaimed = sc->nr_reclaimed - nr_reclaimed; 6220 6221 /* Record the subtree's reclaim efficiency */ 6222 if (!sc->proactive) 6223 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true, 6224 sc->nr_scanned - nr_scanned, nr_node_reclaimed); 6225 6226 if (nr_node_reclaimed) 6227 reclaimable = true; 6228 6229 if (current_is_kswapd()) { 6230 /* 6231 * If reclaim is isolating dirty pages under writeback, 6232 * it implies that the long-lived page allocation rate 6233 * is exceeding the page laundering rate. Either the 6234 * global limits are not being effective at throttling 6235 * processes due to the page distribution throughout 6236 * zones or there is heavy usage of a slow backing 6237 * device. The only option is to throttle from reclaim 6238 * context which is not ideal as there is no guarantee 6239 * the dirtying process is throttled in the same way 6240 * balance_dirty_pages() manages. 6241 * 6242 * Once a node is flagged PGDAT_WRITEBACK, kswapd will 6243 * count the number of pages under pages flagged for 6244 * immediate reclaim and stall if any are encountered 6245 * in the nr_immediate check below. 6246 */ 6247 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken) 6248 set_bit(PGDAT_WRITEBACK, &pgdat->flags); 6249 6250 /* 6251 * If kswapd scans pages marked for immediate 6252 * reclaim and under writeback (nr_immediate), it 6253 * implies that pages are cycling through the LRU 6254 * faster than they are written so forcibly stall 6255 * until some pages complete writeback. 6256 */ 6257 if (sc->nr.immediate) 6258 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK); 6259 } 6260 6261 /* 6262 * Tag a node/memcg as congested if all the dirty pages were marked 6263 * for writeback and immediate reclaim (counted in nr.congested). 6264 * 6265 * Legacy memcg will stall in page writeback so avoid forcibly 6266 * stalling in reclaim_throttle(). 6267 */ 6268 if (sc->nr.dirty && sc->nr.dirty == sc->nr.congested) { 6269 if (cgroup_reclaim(sc) && writeback_throttling_sane(sc)) 6270 set_bit(LRUVEC_CGROUP_CONGESTED, &target_lruvec->flags); 6271 6272 if (current_is_kswapd()) 6273 set_bit(LRUVEC_NODE_CONGESTED, &target_lruvec->flags); 6274 } 6275 6276 /* 6277 * Stall direct reclaim for IO completions if the lruvec is 6278 * node is congested. Allow kswapd to continue until it 6279 * starts encountering unqueued dirty pages or cycling through 6280 * the LRU too quickly. 6281 */ 6282 if (!current_is_kswapd() && current_may_throttle() && 6283 !sc->hibernation_mode && 6284 (test_bit(LRUVEC_CGROUP_CONGESTED, &target_lruvec->flags) || 6285 test_bit(LRUVEC_NODE_CONGESTED, &target_lruvec->flags))) 6286 reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED); 6287 6288 if (should_continue_reclaim(pgdat, nr_node_reclaimed, sc)) 6289 goto again; 6290 6291 /* 6292 * Kswapd gives up on balancing particular nodes after too 6293 * many failures to reclaim anything from them and goes to 6294 * sleep. On reclaim progress, reset the failure counter. A 6295 * successful direct reclaim run will revive a dormant kswapd. 6296 */ 6297 if (reclaimable) 6298 kswapd_try_clear_hopeless(pgdat, sc->order, sc->reclaim_idx); 6299 else if (sc->cache_trim_mode) 6300 sc->cache_trim_mode_failed = 1; 6301 } 6302 6303 /* 6304 * Returns true if compaction should go ahead for a costly-order request, or 6305 * the allocation would already succeed without compaction. Return false if we 6306 * should reclaim first. 6307 */ 6308 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc) 6309 { 6310 unsigned long watermark; 6311 6312 if (!gfp_compaction_allowed(sc->gfp_mask)) 6313 return false; 6314 6315 /* Allocation can already succeed, nothing to do */ 6316 if (zone_watermark_ok(zone, sc->order, min_wmark_pages(zone), 6317 sc->reclaim_idx, 0)) 6318 return true; 6319 6320 /* 6321 * Direct reclaim usually targets the min watermark, but compaction 6322 * takes time to run and there are potentially other callers using the 6323 * pages just freed. So target a higher buffer to give compaction a 6324 * reasonable chance of completing and allocating the pages. 6325 * 6326 * Note that we won't actually reclaim the whole buffer in one attempt 6327 * as the target watermark in should_continue_reclaim() is lower. But if 6328 * we are already above the high+gap watermark, don't reclaim at all. 6329 */ 6330 watermark = high_wmark_pages(zone); 6331 if (compaction_suitable(zone, sc->order, watermark, sc->reclaim_idx)) 6332 return true; 6333 6334 return false; 6335 } 6336 6337 static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc) 6338 { 6339 /* 6340 * If reclaim is making progress greater than 12% efficiency then 6341 * wake all the NOPROGRESS throttled tasks. 6342 */ 6343 if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) { 6344 wait_queue_head_t *wqh; 6345 6346 wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS]; 6347 if (waitqueue_active(wqh)) 6348 wake_up(wqh); 6349 6350 return; 6351 } 6352 6353 /* 6354 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will 6355 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages 6356 * under writeback and marked for immediate reclaim at the tail of the 6357 * LRU. 6358 */ 6359 if (current_is_kswapd() || cgroup_reclaim(sc)) 6360 return; 6361 6362 /* Throttle if making no progress at high prioities. */ 6363 if (sc->priority == 1 && !sc->nr_reclaimed) 6364 reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS); 6365 } 6366 6367 /* 6368 * This is the direct reclaim path, for page-allocating processes. We only 6369 * try to reclaim pages from zones which will satisfy the caller's allocation 6370 * request. 6371 * 6372 * If a zone is deemed to be full of pinned pages then just give it a light 6373 * scan then give up on it. 6374 */ 6375 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc) 6376 { 6377 struct zoneref *z; 6378 struct zone *zone; 6379 unsigned long nr_soft_reclaimed; 6380 unsigned long nr_soft_scanned; 6381 gfp_t orig_mask; 6382 pg_data_t *last_pgdat = NULL; 6383 pg_data_t *first_pgdat = NULL; 6384 6385 /* 6386 * If the number of buffer_heads in the machine exceeds the maximum 6387 * allowed level, force direct reclaim to scan the highmem zone as 6388 * highmem pages could be pinning lowmem pages storing buffer_heads 6389 */ 6390 orig_mask = sc->gfp_mask; 6391 if (buffer_heads_over_limit) { 6392 sc->gfp_mask |= __GFP_HIGHMEM; 6393 sc->reclaim_idx = gfp_zone(sc->gfp_mask); 6394 } 6395 6396 for_each_zone_zonelist_nodemask(zone, z, zonelist, 6397 sc->reclaim_idx, sc->nodemask) { 6398 /* 6399 * Take care memory controller reclaiming has small influence 6400 * to global LRU. 6401 */ 6402 if (!cgroup_reclaim(sc)) { 6403 if (!cpuset_zone_allowed(zone, 6404 GFP_KERNEL | __GFP_HARDWALL)) 6405 continue; 6406 6407 /* 6408 * If we already have plenty of memory free for 6409 * compaction in this zone, don't free any more. 6410 * Even though compaction is invoked for any 6411 * non-zero order, only frequent costly order 6412 * reclamation is disruptive enough to become a 6413 * noticeable problem, like transparent huge 6414 * page allocations. 6415 */ 6416 if (IS_ENABLED(CONFIG_COMPACTION) && 6417 sc->order > PAGE_ALLOC_COSTLY_ORDER && 6418 compaction_ready(zone, sc)) { 6419 sc->compaction_ready = true; 6420 continue; 6421 } 6422 6423 /* 6424 * Shrink each node in the zonelist once. If the 6425 * zonelist is ordered by zone (not the default) then a 6426 * node may be shrunk multiple times but in that case 6427 * the user prefers lower zones being preserved. 6428 */ 6429 if (zone->zone_pgdat == last_pgdat) 6430 continue; 6431 6432 /* 6433 * This steals pages from memory cgroups over softlimit 6434 * and returns the number of reclaimed pages and 6435 * scanned pages. This works for global memory pressure 6436 * and balancing, not for a memcg's limit. 6437 */ 6438 nr_soft_scanned = 0; 6439 nr_soft_reclaimed = memcg1_soft_limit_reclaim(zone->zone_pgdat, 6440 sc->order, sc->gfp_mask, 6441 &nr_soft_scanned); 6442 sc->nr_reclaimed += nr_soft_reclaimed; 6443 sc->nr_scanned += nr_soft_scanned; 6444 /* need some check for avoid more shrink_zone() */ 6445 } 6446 6447 if (!first_pgdat) 6448 first_pgdat = zone->zone_pgdat; 6449 6450 /* See comment about same check for global reclaim above */ 6451 if (zone->zone_pgdat == last_pgdat) 6452 continue; 6453 last_pgdat = zone->zone_pgdat; 6454 shrink_node(zone->zone_pgdat, sc); 6455 } 6456 6457 if (first_pgdat) 6458 consider_reclaim_throttle(first_pgdat, sc); 6459 6460 /* 6461 * Restore to original mask to avoid the impact on the caller if we 6462 * promoted it to __GFP_HIGHMEM. 6463 */ 6464 sc->gfp_mask = orig_mask; 6465 } 6466 6467 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat) 6468 { 6469 struct lruvec *target_lruvec; 6470 unsigned long refaults; 6471 6472 if (lru_gen_enabled() && !lru_gen_switching()) 6473 return; 6474 6475 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat); 6476 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON); 6477 target_lruvec->refaults[WORKINGSET_ANON] = refaults; 6478 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE); 6479 target_lruvec->refaults[WORKINGSET_FILE] = refaults; 6480 } 6481 6482 /* 6483 * This is the main entry point to direct page reclaim. 6484 * 6485 * If a full scan of the inactive list fails to free enough memory then we 6486 * are "out of memory" and something needs to be killed. 6487 * 6488 * If the caller is !__GFP_FS then the probability of a failure is reasonably 6489 * high - the zone may be full of dirty or under-writeback pages, which this 6490 * caller can't do much about. We kick the writeback threads and take explicit 6491 * naps in the hope that some of these pages can be written. But if the 6492 * allocating task holds filesystem locks which prevent writeout this might not 6493 * work, and the allocation attempt will fail. 6494 * 6495 * returns: 0, if no pages reclaimed 6496 * else, the number of pages reclaimed 6497 */ 6498 static unsigned long do_try_to_free_pages(struct zonelist *zonelist, 6499 struct scan_control *sc) 6500 { 6501 int initial_priority = sc->priority; 6502 pg_data_t *last_pgdat; 6503 struct zoneref *z; 6504 struct zone *zone; 6505 retry: 6506 delayacct_freepages_start(); 6507 6508 if (!cgroup_reclaim(sc)) 6509 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1); 6510 6511 do { 6512 if (!sc->proactive) 6513 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup, 6514 sc->priority); 6515 sc->nr_scanned = 0; 6516 shrink_zones(zonelist, sc); 6517 6518 if (sc->nr_reclaimed >= sc->nr_to_reclaim) 6519 break; 6520 6521 if (sc->compaction_ready) 6522 break; 6523 } while (--sc->priority >= 0); 6524 6525 last_pgdat = NULL; 6526 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx, 6527 sc->nodemask) { 6528 if (zone->zone_pgdat == last_pgdat) 6529 continue; 6530 last_pgdat = zone->zone_pgdat; 6531 6532 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat); 6533 6534 if (cgroup_reclaim(sc)) { 6535 struct lruvec *lruvec; 6536 6537 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, 6538 zone->zone_pgdat); 6539 clear_bit(LRUVEC_CGROUP_CONGESTED, &lruvec->flags); 6540 } 6541 } 6542 6543 delayacct_freepages_end(); 6544 6545 if (sc->nr_reclaimed) 6546 return sc->nr_reclaimed; 6547 6548 /* Aborted reclaim to try compaction? don't OOM, then */ 6549 if (sc->compaction_ready) 6550 return 1; 6551 6552 /* 6553 * In most cases, direct reclaimers can do partial walks 6554 * through the cgroup tree to meet the reclaim goal while 6555 * keeping latency low. Since the iterator state is shared 6556 * among all direct reclaim invocations (to retain fairness 6557 * among cgroups), though, high concurrency can result in 6558 * individual threads not seeing enough cgroups to make 6559 * meaningful forward progress. Avoid false OOMs in this case. 6560 */ 6561 if (!sc->memcg_full_walk) { 6562 sc->priority = initial_priority; 6563 sc->memcg_full_walk = 1; 6564 goto retry; 6565 } 6566 6567 /* 6568 * We make inactive:active ratio decisions based on the node's 6569 * composition of memory, but a restrictive reclaim_idx or a 6570 * memory.low cgroup setting can exempt large amounts of 6571 * memory from reclaim. Neither of which are very common, so 6572 * instead of doing costly eligibility calculations of the 6573 * entire cgroup subtree up front, we assume the estimates are 6574 * good, and retry with forcible deactivation if that fails. 6575 */ 6576 if (sc->skipped_deactivate) { 6577 sc->priority = initial_priority; 6578 sc->force_deactivate = 1; 6579 sc->skipped_deactivate = 0; 6580 goto retry; 6581 } 6582 6583 /* Untapped cgroup reserves? Don't OOM, retry. */ 6584 if (sc->memcg_low_skipped) { 6585 sc->priority = initial_priority; 6586 sc->force_deactivate = 0; 6587 sc->memcg_low_reclaim = 1; 6588 sc->memcg_low_skipped = 0; 6589 goto retry; 6590 } 6591 6592 return 0; 6593 } 6594 6595 static bool allow_direct_reclaim(pg_data_t *pgdat) 6596 { 6597 struct zone *zone; 6598 unsigned long pfmemalloc_reserve = 0; 6599 unsigned long free_pages = 0; 6600 int i; 6601 bool wmark_ok; 6602 6603 if (kswapd_test_hopeless(pgdat)) 6604 return true; 6605 6606 for_each_managed_zone_pgdat(zone, pgdat, i, ZONE_NORMAL) { 6607 if (!zone_reclaimable_pages(zone) && zone_page_state_snapshot(zone, NR_FREE_PAGES)) 6608 continue; 6609 6610 pfmemalloc_reserve += min_wmark_pages(zone); 6611 free_pages += zone_page_state_snapshot(zone, NR_FREE_PAGES); 6612 } 6613 6614 /* If there are no reserves (unexpected config) then do not throttle */ 6615 if (!pfmemalloc_reserve) 6616 return true; 6617 6618 wmark_ok = free_pages > pfmemalloc_reserve / 2; 6619 6620 /* kswapd must be awake if processes are being throttled */ 6621 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) { 6622 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL) 6623 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL); 6624 6625 wake_up_interruptible(&pgdat->kswapd_wait); 6626 } 6627 6628 return wmark_ok; 6629 } 6630 6631 /* 6632 * Throttle direct reclaimers if backing storage is backed by the network 6633 * and the PFMEMALLOC reserve for the preferred node is getting dangerously 6634 * depleted. kswapd will continue to make progress and wake the processes 6635 * when the low watermark is reached. 6636 * 6637 * Returns true if a fatal signal was delivered during throttling. If this 6638 * happens, the page allocator should not consider triggering the OOM killer. 6639 */ 6640 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist, 6641 nodemask_t *nodemask) 6642 { 6643 struct zoneref *z; 6644 struct zone *zone; 6645 pg_data_t *pgdat = NULL; 6646 6647 /* 6648 * Kernel threads should not be throttled as they may be indirectly 6649 * responsible for cleaning pages necessary for reclaim to make forward 6650 * progress. kjournald for example may enter direct reclaim while 6651 * committing a transaction where throttling it could forcing other 6652 * processes to block on log_wait_commit(). 6653 */ 6654 if (current->flags & PF_KTHREAD) 6655 goto out; 6656 6657 /* 6658 * If a fatal signal is pending, this process should not throttle. 6659 * It should return quickly so it can exit and free its memory 6660 */ 6661 if (fatal_signal_pending(current)) 6662 goto out; 6663 6664 /* 6665 * Check if the pfmemalloc reserves are ok by finding the first node 6666 * with a usable ZONE_NORMAL or lower zone. The expectation is that 6667 * GFP_KERNEL will be required for allocating network buffers when 6668 * swapping over the network so ZONE_HIGHMEM is unusable. 6669 * 6670 * Throttling is based on the first usable node and throttled processes 6671 * wait on a queue until kswapd makes progress and wakes them. There 6672 * is an affinity then between processes waking up and where reclaim 6673 * progress has been made assuming the process wakes on the same node. 6674 * More importantly, processes running on remote nodes will not compete 6675 * for remote pfmemalloc reserves and processes on different nodes 6676 * should make reasonable progress. 6677 */ 6678 for_each_zone_zonelist_nodemask(zone, z, zonelist, 6679 gfp_zone(gfp_mask), nodemask) { 6680 if (zone_idx(zone) > ZONE_NORMAL) 6681 continue; 6682 6683 /* Throttle based on the first usable node */ 6684 pgdat = zone->zone_pgdat; 6685 if (allow_direct_reclaim(pgdat)) 6686 goto out; 6687 break; 6688 } 6689 6690 /* If no zone was usable by the allocation flags then do not throttle */ 6691 if (!pgdat) 6692 goto out; 6693 6694 /* Account for the throttling */ 6695 count_vm_event(PGSCAN_DIRECT_THROTTLE); 6696 6697 /* 6698 * If the caller cannot enter the filesystem, it's possible that it 6699 * is due to the caller holding an FS lock or performing a journal 6700 * transaction in the case of a filesystem like ext[3|4]. In this case, 6701 * it is not safe to block on pfmemalloc_wait as kswapd could be 6702 * blocked waiting on the same lock. Instead, throttle for up to a 6703 * second before continuing. 6704 */ 6705 if (!(gfp_mask & __GFP_FS)) 6706 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait, 6707 allow_direct_reclaim(pgdat), HZ); 6708 else 6709 /* Throttle until kswapd wakes the process */ 6710 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait, 6711 allow_direct_reclaim(pgdat)); 6712 6713 if (fatal_signal_pending(current)) 6714 return true; 6715 6716 out: 6717 return false; 6718 } 6719 6720 unsigned long try_to_free_pages(struct zonelist *zonelist, int order, 6721 gfp_t gfp_mask, nodemask_t *nodemask) 6722 { 6723 unsigned long nr_reclaimed; 6724 struct scan_control sc = { 6725 .nr_to_reclaim = SWAP_CLUSTER_MAX, 6726 .gfp_mask = current_gfp_context(gfp_mask), 6727 .reclaim_idx = gfp_zone(gfp_mask), 6728 .order = order, 6729 .nodemask = nodemask, 6730 .priority = DEF_PRIORITY, 6731 .may_writepage = 1, 6732 .may_unmap = 1, 6733 .may_swap = 1, 6734 }; 6735 6736 /* 6737 * scan_control uses s8 fields for order, priority, and reclaim_idx. 6738 * Confirm they are large enough for max values. 6739 */ 6740 BUILD_BUG_ON(MAX_PAGE_ORDER >= S8_MAX); 6741 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX); 6742 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX); 6743 6744 /* 6745 * Do not enter reclaim if fatal signal was delivered while throttled. 6746 * 1 is returned so that the page allocator does not OOM kill at this 6747 * point. 6748 */ 6749 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask)) 6750 return 1; 6751 6752 set_task_reclaim_state(current, &sc.reclaim_state); 6753 trace_mm_vmscan_direct_reclaim_begin(sc.gfp_mask, order, 0); 6754 6755 nr_reclaimed = do_try_to_free_pages(zonelist, &sc); 6756 6757 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed, 0); 6758 set_task_reclaim_state(current, NULL); 6759 6760 return nr_reclaimed; 6761 } 6762 6763 #ifdef CONFIG_MEMCG 6764 6765 /* Only used by soft limit reclaim. Do not reuse for anything else. */ 6766 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg, 6767 gfp_t gfp_mask, bool noswap, 6768 pg_data_t *pgdat, 6769 unsigned long *nr_scanned) 6770 { 6771 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat); 6772 struct scan_control sc = { 6773 .nr_to_reclaim = SWAP_CLUSTER_MAX, 6774 .target_mem_cgroup = memcg, 6775 .may_writepage = 1, 6776 .may_unmap = 1, 6777 .reclaim_idx = MAX_NR_ZONES - 1, 6778 .may_swap = !noswap, 6779 }; 6780 6781 WARN_ON_ONCE(!current->reclaim_state); 6782 6783 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) | 6784 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK); 6785 6786 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.gfp_mask, 6787 sc.order, 6788 memcg); 6789 6790 /* 6791 * NOTE: Although we can get the priority field, using it 6792 * here is not a good idea, since it limits the pages we can scan. 6793 * if we don't reclaim here, the shrink_node from balance_pgdat 6794 * will pick up pages from other mem cgroup's as well. We hack 6795 * the priority and make it zero. 6796 */ 6797 shrink_lruvec(lruvec, &sc); 6798 6799 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed, memcg); 6800 6801 *nr_scanned = sc.nr_scanned; 6802 6803 return sc.nr_reclaimed; 6804 } 6805 6806 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg, 6807 unsigned long nr_pages, 6808 gfp_t gfp_mask, 6809 unsigned int reclaim_options, 6810 int *swappiness) 6811 { 6812 unsigned long nr_reclaimed; 6813 unsigned int noreclaim_flag; 6814 struct scan_control sc = { 6815 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX), 6816 .proactive_swappiness = swappiness, 6817 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) | 6818 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK), 6819 .reclaim_idx = MAX_NR_ZONES - 1, 6820 .target_mem_cgroup = memcg, 6821 .priority = DEF_PRIORITY, 6822 .may_writepage = 1, 6823 .may_unmap = 1, 6824 .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP), 6825 .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE), 6826 }; 6827 /* 6828 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put 6829 * equal pressure on all the nodes. This is based on the assumption that 6830 * the reclaim does not bail out early. 6831 */ 6832 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask); 6833 6834 set_task_reclaim_state(current, &sc.reclaim_state); 6835 trace_mm_vmscan_memcg_reclaim_begin(sc.gfp_mask, 0, memcg); 6836 noreclaim_flag = memalloc_noreclaim_save(); 6837 6838 nr_reclaimed = do_try_to_free_pages(zonelist, &sc); 6839 6840 memalloc_noreclaim_restore(noreclaim_flag); 6841 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed, memcg); 6842 set_task_reclaim_state(current, NULL); 6843 6844 return nr_reclaimed; 6845 } 6846 #else 6847 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg, 6848 unsigned long nr_pages, 6849 gfp_t gfp_mask, 6850 unsigned int reclaim_options, 6851 int *swappiness) 6852 { 6853 return 0; 6854 } 6855 #endif 6856 6857 static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc) 6858 { 6859 struct mem_cgroup *memcg; 6860 struct lruvec *lruvec; 6861 6862 if (lru_gen_enabled() || lru_gen_switching()) { 6863 lru_gen_age_node(pgdat, sc); 6864 6865 if (!lru_gen_switching()) 6866 return; 6867 6868 } 6869 6870 lruvec = mem_cgroup_lruvec(NULL, pgdat); 6871 if (!can_age_anon_pages(lruvec, sc)) 6872 return; 6873 6874 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON)) 6875 return; 6876 6877 memcg = mem_cgroup_iter(NULL, NULL, NULL); 6878 do { 6879 lruvec = mem_cgroup_lruvec(memcg, pgdat); 6880 shrink_active_list(SWAP_CLUSTER_MAX, lruvec, 6881 sc, LRU_ACTIVE_ANON); 6882 memcg = mem_cgroup_iter(NULL, memcg, NULL); 6883 } while (memcg); 6884 } 6885 6886 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx) 6887 { 6888 int i; 6889 struct zone *zone; 6890 6891 /* 6892 * Check for watermark boosts top-down as the higher zones 6893 * are more likely to be boosted. Both watermarks and boosts 6894 * should not be checked at the same time as reclaim would 6895 * start prematurely when there is no boosting and a lower 6896 * zone is balanced. 6897 */ 6898 for (i = highest_zoneidx; i >= 0; i--) { 6899 zone = pgdat->node_zones + i; 6900 if (!managed_zone(zone)) 6901 continue; 6902 6903 if (zone->watermark_boost) 6904 return true; 6905 } 6906 6907 return false; 6908 } 6909 6910 /* 6911 * Returns true if there is an eligible zone balanced for the request order 6912 * and highest_zoneidx 6913 */ 6914 static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx) 6915 { 6916 int i; 6917 unsigned long mark = -1; 6918 struct zone *zone; 6919 6920 /* 6921 * Check watermarks bottom-up as lower zones are more likely to 6922 * meet watermarks. 6923 */ 6924 for_each_managed_zone_pgdat(zone, pgdat, i, highest_zoneidx) { 6925 enum zone_stat_item item; 6926 unsigned long free_pages; 6927 6928 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) 6929 mark = promo_wmark_pages(zone); 6930 else 6931 mark = high_wmark_pages(zone); 6932 6933 /* 6934 * In defrag_mode, watermarks must be met in whole 6935 * blocks to avoid polluting allocator fallbacks. 6936 * 6937 * However, kswapd usually cannot accomplish this on 6938 * its own and needs kcompactd support. Once it's 6939 * reclaimed a compaction gap, and kswapd_shrink_node 6940 * has dropped order, simply ensure there are enough 6941 * base pages for compaction, wake kcompactd & sleep. 6942 */ 6943 if (defrag_mode && order) 6944 item = NR_FREE_PAGES_BLOCKS; 6945 else 6946 item = NR_FREE_PAGES; 6947 6948 /* 6949 * When there is a high number of CPUs in the system, 6950 * the cumulative error from the vmstat per-cpu cache 6951 * can blur the line between the watermarks. In that 6952 * case, be safe and get an accurate snapshot. 6953 * 6954 * TODO: NR_FREE_PAGES_BLOCKS moves in steps of 6955 * pageblock_nr_pages, while the vmstat pcp threshold 6956 * is limited to 125. On many configurations that 6957 * counter won't actually be per-cpu cached. But keep 6958 * things simple for now; revisit when somebody cares. 6959 */ 6960 free_pages = zone_page_state(zone, item); 6961 if (zone->percpu_drift_mark && free_pages < zone->percpu_drift_mark) 6962 free_pages = zone_page_state_snapshot(zone, item); 6963 6964 if (__zone_watermark_ok(zone, order, mark, highest_zoneidx, 6965 0, free_pages)) 6966 return true; 6967 } 6968 6969 /* 6970 * If a node has no managed zone within highest_zoneidx, it does not 6971 * need balancing by definition. This can happen if a zone-restricted 6972 * allocation tries to wake a remote kswapd. 6973 */ 6974 if (mark == -1) 6975 return true; 6976 6977 return false; 6978 } 6979 6980 /* Clear pgdat state for congested, dirty or under writeback. */ 6981 static void clear_pgdat_congested(pg_data_t *pgdat) 6982 { 6983 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat); 6984 6985 clear_bit(LRUVEC_NODE_CONGESTED, &lruvec->flags); 6986 clear_bit(LRUVEC_CGROUP_CONGESTED, &lruvec->flags); 6987 clear_bit(PGDAT_WRITEBACK, &pgdat->flags); 6988 } 6989 6990 /* 6991 * Prepare kswapd for sleeping. This verifies that there are no processes 6992 * waiting in throttle_direct_reclaim() and that watermarks have been met. 6993 * 6994 * Returns true if kswapd is ready to sleep 6995 */ 6996 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, 6997 int highest_zoneidx) 6998 { 6999 /* 7000 * The throttled processes are normally woken up in balance_pgdat() as 7001 * soon as allow_direct_reclaim() is true. But there is a potential 7002 * race between when kswapd checks the watermarks and a process gets 7003 * throttled. There is also a potential race if processes get 7004 * throttled, kswapd wakes, a large process exits thereby balancing the 7005 * zones, which causes kswapd to exit balance_pgdat() before reaching 7006 * the wake up checks. If kswapd is going to sleep, no process should 7007 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If 7008 * the wake up is premature, processes will wake kswapd and get 7009 * throttled again. The difference from wake ups in balance_pgdat() is 7010 * that here we are under prepare_to_wait(). 7011 */ 7012 if (waitqueue_active(&pgdat->pfmemalloc_wait)) 7013 wake_up_all(&pgdat->pfmemalloc_wait); 7014 7015 /* Hopeless node, leave it to direct reclaim */ 7016 if (kswapd_test_hopeless(pgdat)) 7017 return true; 7018 7019 if (pgdat_balanced(pgdat, order, highest_zoneidx)) { 7020 clear_pgdat_congested(pgdat); 7021 return true; 7022 } 7023 7024 return false; 7025 } 7026 7027 /* 7028 * kswapd shrinks a node of pages that are at or below the highest usable 7029 * zone that is currently unbalanced. 7030 * 7031 * Returns true if kswapd scanned at least the requested number of pages to 7032 * reclaim or if the lack of progress was due to pages under writeback. 7033 * This is used to determine if the scanning priority needs to be raised. 7034 */ 7035 static bool kswapd_shrink_node(pg_data_t *pgdat, 7036 struct scan_control *sc) 7037 { 7038 struct zone *zone; 7039 int z; 7040 unsigned long nr_reclaimed = sc->nr_reclaimed; 7041 7042 /* Reclaim a number of pages proportional to the number of zones */ 7043 sc->nr_to_reclaim = 0; 7044 for_each_managed_zone_pgdat(zone, pgdat, z, sc->reclaim_idx) { 7045 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX); 7046 } 7047 7048 /* 7049 * Historically care was taken to put equal pressure on all zones but 7050 * now pressure is applied based on node LRU order. 7051 */ 7052 shrink_node(pgdat, sc); 7053 7054 /* 7055 * Fragmentation may mean that the system cannot be rebalanced for 7056 * high-order allocations. If twice the allocation size has been 7057 * reclaimed then recheck watermarks only at order-0 to prevent 7058 * excessive reclaim. Assume that a process requested a high-order 7059 * can direct reclaim/compact. 7060 */ 7061 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order)) 7062 sc->order = 0; 7063 7064 /* account for progress from mm_account_reclaimed_pages() */ 7065 return max(sc->nr_scanned, sc->nr_reclaimed - nr_reclaimed) >= sc->nr_to_reclaim; 7066 } 7067 7068 /* Page allocator PCP high watermark is lowered if reclaim is active. */ 7069 static inline void 7070 update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active) 7071 { 7072 int i; 7073 struct zone *zone; 7074 7075 for_each_managed_zone_pgdat(zone, pgdat, i, highest_zoneidx) { 7076 if (active) 7077 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags); 7078 else 7079 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags); 7080 } 7081 } 7082 7083 static inline void 7084 set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx) 7085 { 7086 update_reclaim_active(pgdat, highest_zoneidx, true); 7087 } 7088 7089 static inline void 7090 clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx) 7091 { 7092 update_reclaim_active(pgdat, highest_zoneidx, false); 7093 } 7094 7095 /* 7096 * For kswapd, balance_pgdat() will reclaim pages across a node from zones 7097 * that are eligible for use by the caller until at least one zone is 7098 * balanced. 7099 * 7100 * Returns the order kswapd finished reclaiming at. 7101 * 7102 * kswapd scans the zones in the highmem->normal->dma direction. It skips 7103 * zones which have free_pages > high_wmark_pages(zone), but once a zone is 7104 * found to have free_pages <= high_wmark_pages(zone), any page in that zone 7105 * or lower is eligible for reclaim until at least one usable zone is 7106 * balanced. 7107 */ 7108 static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx) 7109 { 7110 int i; 7111 unsigned long nr_soft_reclaimed; 7112 unsigned long nr_soft_scanned; 7113 unsigned long pflags; 7114 unsigned long nr_boost_reclaim; 7115 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, }; 7116 bool boosted; 7117 struct zone *zone; 7118 struct scan_control sc = { 7119 .gfp_mask = GFP_KERNEL, 7120 .order = order, 7121 .may_unmap = 1, 7122 }; 7123 7124 set_task_reclaim_state(current, &sc.reclaim_state); 7125 psi_memstall_enter(&pflags); 7126 __fs_reclaim_acquire(_THIS_IP_); 7127 7128 count_vm_event(PAGEOUTRUN); 7129 7130 /* 7131 * Account for the reclaim boost. Note that the zone boost is left in 7132 * place so that parallel allocations that are near the watermark will 7133 * stall or direct reclaim until kswapd is finished. 7134 */ 7135 nr_boost_reclaim = 0; 7136 for_each_managed_zone_pgdat(zone, pgdat, i, highest_zoneidx) { 7137 nr_boost_reclaim += zone->watermark_boost; 7138 zone_boosts[i] = zone->watermark_boost; 7139 } 7140 boosted = nr_boost_reclaim; 7141 7142 restart: 7143 set_reclaim_active(pgdat, highest_zoneidx); 7144 sc.priority = DEF_PRIORITY; 7145 do { 7146 unsigned long nr_reclaimed = sc.nr_reclaimed; 7147 bool raise_priority = true; 7148 bool balanced; 7149 bool ret; 7150 bool was_frozen; 7151 7152 sc.reclaim_idx = highest_zoneidx; 7153 7154 /* 7155 * If the number of buffer_heads exceeds the maximum allowed 7156 * then consider reclaiming from all zones. This has a dual 7157 * purpose -- on 64-bit systems it is expected that 7158 * buffer_heads are stripped during active rotation. On 32-bit 7159 * systems, highmem pages can pin lowmem memory and shrinking 7160 * buffers can relieve lowmem pressure. Reclaim may still not 7161 * go ahead if all eligible zones for the original allocation 7162 * request are balanced to avoid excessive reclaim from kswapd. 7163 */ 7164 if (buffer_heads_over_limit) { 7165 for (i = MAX_NR_ZONES - 1; i >= 0; i--) { 7166 zone = pgdat->node_zones + i; 7167 if (!managed_zone(zone)) 7168 continue; 7169 7170 sc.reclaim_idx = i; 7171 break; 7172 } 7173 } 7174 7175 /* 7176 * If the pgdat is imbalanced then ignore boosting and preserve 7177 * the watermarks for a later time and restart. Note that the 7178 * zone watermarks will be still reset at the end of balancing 7179 * on the grounds that the normal reclaim should be enough to 7180 * re-evaluate if boosting is required when kswapd next wakes. 7181 */ 7182 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx); 7183 if (!balanced && nr_boost_reclaim) { 7184 nr_boost_reclaim = 0; 7185 goto restart; 7186 } 7187 7188 /* 7189 * If boosting is not active then only reclaim if there are no 7190 * eligible zones. Note that sc.reclaim_idx is not used as 7191 * buffer_heads_over_limit may have adjusted it. 7192 */ 7193 if (!nr_boost_reclaim && balanced) 7194 goto out; 7195 7196 /* Limit the priority of boosting to avoid reclaim writeback */ 7197 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2) 7198 raise_priority = false; 7199 7200 /* 7201 * Do not writeback or swap pages for boosted reclaim. The 7202 * intent is to relieve pressure not issue sub-optimal IO 7203 * from reclaim context. If no pages are reclaimed, the 7204 * reclaim will be aborted. 7205 */ 7206 sc.may_writepage = !nr_boost_reclaim; 7207 sc.may_swap = !nr_boost_reclaim; 7208 7209 /* 7210 * Do some background aging, to give pages a chance to be 7211 * referenced before reclaiming. All pages are rotated 7212 * regardless of classzone as this is about consistent aging. 7213 */ 7214 kswapd_age_node(pgdat, &sc); 7215 7216 /* Call soft limit reclaim before calling shrink_node. */ 7217 sc.nr_scanned = 0; 7218 nr_soft_scanned = 0; 7219 nr_soft_reclaimed = memcg1_soft_limit_reclaim(pgdat, sc.order, 7220 sc.gfp_mask, &nr_soft_scanned); 7221 sc.nr_reclaimed += nr_soft_reclaimed; 7222 7223 /* 7224 * There should be no need to raise the scanning priority if 7225 * enough pages are already being scanned that that high 7226 * watermark would be met at 100% efficiency. 7227 */ 7228 if (kswapd_shrink_node(pgdat, &sc)) 7229 raise_priority = false; 7230 7231 /* 7232 * If the low watermark is met there is no need for processes 7233 * to be throttled on pfmemalloc_wait as they should not be 7234 * able to safely make forward progress. Wake them 7235 */ 7236 if (waitqueue_active(&pgdat->pfmemalloc_wait) && 7237 allow_direct_reclaim(pgdat)) 7238 wake_up_all(&pgdat->pfmemalloc_wait); 7239 7240 /* Check if kswapd should be suspending */ 7241 __fs_reclaim_release(_THIS_IP_); 7242 ret = kthread_freezable_should_stop(&was_frozen); 7243 __fs_reclaim_acquire(_THIS_IP_); 7244 if (was_frozen || ret) 7245 break; 7246 7247 /* 7248 * Raise priority if scanning rate is too low or there was no 7249 * progress in reclaiming pages 7250 */ 7251 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed; 7252 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed); 7253 7254 /* 7255 * If reclaim made no progress for a boost, stop reclaim as 7256 * IO cannot be queued and it could be an infinite loop in 7257 * extreme circumstances. 7258 */ 7259 if (nr_boost_reclaim && !nr_reclaimed) 7260 break; 7261 7262 if (raise_priority || !nr_reclaimed) 7263 sc.priority--; 7264 } while (sc.priority >= 1); 7265 7266 /* 7267 * Restart only if it went through the priority loop all the way, 7268 * but cache_trim_mode didn't work. 7269 */ 7270 if (!sc.nr_reclaimed && sc.priority < 1 && 7271 !sc.no_cache_trim_mode && sc.cache_trim_mode_failed) { 7272 sc.no_cache_trim_mode = 1; 7273 goto restart; 7274 } 7275 7276 /* 7277 * If the reclaim was boosted, we might still be far from the 7278 * watermark_high at this point. We need to avoid increasing the 7279 * failure count to prevent the kswapd thread from stopping. 7280 */ 7281 if (!sc.nr_reclaimed && !boosted) { 7282 int fail_cnt = atomic_inc_return(&pgdat->kswapd_failures); 7283 /* kswapd context, low overhead to trace every failure */ 7284 trace_mm_vmscan_kswapd_reclaim_fail(pgdat->node_id, fail_cnt); 7285 } 7286 7287 out: 7288 clear_reclaim_active(pgdat, highest_zoneidx); 7289 7290 /* If reclaim was boosted, account for the reclaim done in this pass */ 7291 if (boosted) { 7292 unsigned long flags; 7293 7294 for (i = 0; i <= highest_zoneidx; i++) { 7295 if (!zone_boosts[i]) 7296 continue; 7297 7298 /* Increments are under the zone lock */ 7299 zone = pgdat->node_zones + i; 7300 spin_lock_irqsave(&zone->lock, flags); 7301 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]); 7302 spin_unlock_irqrestore(&zone->lock, flags); 7303 } 7304 7305 /* 7306 * As there is now likely space, wakeup kcompact to defragment 7307 * pageblocks. 7308 */ 7309 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx); 7310 } 7311 7312 snapshot_refaults(NULL, pgdat); 7313 __fs_reclaim_release(_THIS_IP_); 7314 psi_memstall_leave(&pflags); 7315 set_task_reclaim_state(current, NULL); 7316 7317 /* 7318 * Return the order kswapd stopped reclaiming at as 7319 * prepare_kswapd_sleep() takes it into account. If another caller 7320 * entered the allocator slow path while kswapd was awake, order will 7321 * remain at the higher level. 7322 */ 7323 return sc.order; 7324 } 7325 7326 /* 7327 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to 7328 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is 7329 * not a valid index then either kswapd runs for first time or kswapd couldn't 7330 * sleep after previous reclaim attempt (node is still unbalanced). In that 7331 * case return the zone index of the previous kswapd reclaim cycle. 7332 */ 7333 static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat, 7334 enum zone_type prev_highest_zoneidx) 7335 { 7336 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx); 7337 7338 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx; 7339 } 7340 7341 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order, 7342 unsigned int highest_zoneidx) 7343 { 7344 long remaining = 0; 7345 DEFINE_WAIT(wait); 7346 7347 if (freezing(current) || kthread_should_stop()) 7348 return; 7349 7350 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE); 7351 7352 /* 7353 * Try to sleep for a short interval. Note that kcompactd will only be 7354 * woken if it is possible to sleep for a short interval. This is 7355 * deliberate on the assumption that if reclaim cannot keep an 7356 * eligible zone balanced that it's also unlikely that compaction will 7357 * succeed. 7358 */ 7359 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) { 7360 /* 7361 * Compaction records what page blocks it recently failed to 7362 * isolate pages from and skips them in the future scanning. 7363 * When kswapd is going to sleep, it is reasonable to assume 7364 * that pages and compaction may succeed so reset the cache. 7365 */ 7366 reset_isolation_suitable(pgdat); 7367 7368 /* 7369 * We have freed the memory, now we should compact it to make 7370 * allocation of the requested order possible. 7371 */ 7372 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx); 7373 7374 remaining = schedule_timeout(HZ/10); 7375 7376 /* 7377 * If woken prematurely then reset kswapd_highest_zoneidx and 7378 * order. The values will either be from a wakeup request or 7379 * the previous request that slept prematurely. 7380 */ 7381 if (remaining) { 7382 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, 7383 kswapd_highest_zoneidx(pgdat, 7384 highest_zoneidx)); 7385 7386 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order) 7387 WRITE_ONCE(pgdat->kswapd_order, reclaim_order); 7388 } 7389 7390 finish_wait(&pgdat->kswapd_wait, &wait); 7391 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE); 7392 } 7393 7394 /* 7395 * After a short sleep, check if it was a premature sleep. If not, then 7396 * go fully to sleep until explicitly woken up. 7397 */ 7398 if (!remaining && 7399 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) { 7400 trace_mm_vmscan_kswapd_sleep(pgdat->node_id); 7401 7402 /* 7403 * vmstat counters are not perfectly accurate and the estimated 7404 * value for counters such as NR_FREE_PAGES can deviate from the 7405 * true value by nr_online_cpus * threshold. To avoid the zone 7406 * watermarks being breached while under pressure, we reduce the 7407 * per-cpu vmstat threshold while kswapd is awake and restore 7408 * them before going back to sleep. 7409 */ 7410 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold); 7411 7412 if (!kthread_should_stop()) 7413 schedule(); 7414 7415 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold); 7416 } else { 7417 if (remaining) 7418 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY); 7419 else 7420 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY); 7421 } 7422 finish_wait(&pgdat->kswapd_wait, &wait); 7423 } 7424 7425 /* 7426 * The background pageout daemon, started as a kernel thread 7427 * from the init process. 7428 * 7429 * This basically trickles out pages so that we have _some_ 7430 * free memory available even if there is no other activity 7431 * that frees anything up. This is needed for things like routing 7432 * etc, where we otherwise might have all activity going on in 7433 * asynchronous contexts that cannot page things out. 7434 * 7435 * If there are applications that are active memory-allocators 7436 * (most normal use), this basically shouldn't matter. 7437 */ 7438 static int kswapd(void *p) 7439 { 7440 unsigned int alloc_order, reclaim_order; 7441 unsigned int highest_zoneidx = MAX_NR_ZONES - 1; 7442 pg_data_t *pgdat = (pg_data_t *)p; 7443 struct task_struct *tsk = current; 7444 7445 /* 7446 * Tell the memory management that we're a "memory allocator", 7447 * and that if we need more memory we should get access to it 7448 * regardless (see "__alloc_pages()"). "kswapd" should 7449 * never get caught in the normal page freeing logic. 7450 * 7451 * (Kswapd normally doesn't need memory anyway, but sometimes 7452 * you need a small amount of memory in order to be able to 7453 * page out something else, and this flag essentially protects 7454 * us from recursively trying to free more memory as we're 7455 * trying to free the first piece of memory in the first place). 7456 */ 7457 tsk->flags |= PF_MEMALLOC | PF_KSWAPD; 7458 set_freezable(); 7459 7460 WRITE_ONCE(pgdat->kswapd_order, 0); 7461 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES); 7462 atomic_set(&pgdat->nr_writeback_throttled, 0); 7463 for ( ; ; ) { 7464 bool was_frozen; 7465 7466 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order); 7467 highest_zoneidx = kswapd_highest_zoneidx(pgdat, 7468 highest_zoneidx); 7469 7470 kswapd_try_sleep: 7471 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order, 7472 highest_zoneidx); 7473 7474 /* Read the new order and highest_zoneidx */ 7475 alloc_order = READ_ONCE(pgdat->kswapd_order); 7476 highest_zoneidx = kswapd_highest_zoneidx(pgdat, 7477 highest_zoneidx); 7478 WRITE_ONCE(pgdat->kswapd_order, 0); 7479 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES); 7480 7481 if (kthread_freezable_should_stop(&was_frozen)) 7482 break; 7483 7484 /* 7485 * We can speed up thawing tasks if we don't call balance_pgdat 7486 * after returning from the refrigerator 7487 */ 7488 if (was_frozen) 7489 continue; 7490 7491 /* 7492 * Reclaim begins at the requested order but if a high-order 7493 * reclaim fails then kswapd falls back to reclaiming for 7494 * order-0. If that happens, kswapd will consider sleeping 7495 * for the order it finished reclaiming at (reclaim_order) 7496 * but kcompactd is woken to compact for the original 7497 * request (alloc_order). 7498 */ 7499 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx, 7500 alloc_order); 7501 reclaim_order = balance_pgdat(pgdat, alloc_order, 7502 highest_zoneidx); 7503 if (reclaim_order < alloc_order) 7504 goto kswapd_try_sleep; 7505 } 7506 7507 tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD); 7508 7509 return 0; 7510 } 7511 7512 /* 7513 * A zone is low on free memory or too fragmented for high-order memory. If 7514 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's 7515 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim 7516 * has failed or is not needed, still wake up kcompactd if only compaction is 7517 * needed. 7518 */ 7519 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order, 7520 enum zone_type highest_zoneidx) 7521 { 7522 pg_data_t *pgdat; 7523 enum zone_type curr_idx; 7524 7525 if (!managed_zone(zone)) 7526 return; 7527 7528 if (!cpuset_zone_allowed(zone, gfp_flags)) 7529 return; 7530 7531 pgdat = zone->zone_pgdat; 7532 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx); 7533 7534 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx) 7535 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx); 7536 7537 if (READ_ONCE(pgdat->kswapd_order) < order) 7538 WRITE_ONCE(pgdat->kswapd_order, order); 7539 7540 if (!waitqueue_active(&pgdat->kswapd_wait)) 7541 return; 7542 7543 /* Hopeless node, leave it to direct reclaim if possible */ 7544 if (kswapd_test_hopeless(pgdat) || 7545 (pgdat_balanced(pgdat, order, highest_zoneidx) && 7546 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) { 7547 /* 7548 * There may be plenty of free memory available, but it's too 7549 * fragmented for high-order allocations. Wake up kcompactd 7550 * and rely on compaction_suitable() to determine if it's 7551 * needed. If it fails, it will defer subsequent attempts to 7552 * ratelimit its work. 7553 */ 7554 if (!(gfp_flags & __GFP_DIRECT_RECLAIM)) 7555 wakeup_kcompactd(pgdat, order, highest_zoneidx); 7556 return; 7557 } 7558 7559 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order, 7560 gfp_flags); 7561 wake_up_interruptible(&pgdat->kswapd_wait); 7562 } 7563 7564 void kswapd_clear_hopeless(pg_data_t *pgdat, enum kswapd_clear_hopeless_reason reason) 7565 { 7566 /* Only trace actual resets, not redundant zero-to-zero */ 7567 if (atomic_xchg(&pgdat->kswapd_failures, 0)) 7568 trace_mm_vmscan_kswapd_clear_hopeless(pgdat->node_id, reason); 7569 } 7570 7571 /* 7572 * Reset kswapd_failures only when the node is balanced. Without this 7573 * check, successful direct reclaim (e.g., from cgroup memory.high 7574 * throttling) can keep resetting kswapd_failures even when the node 7575 * cannot be balanced, causing kswapd to run endlessly. 7576 */ 7577 void kswapd_try_clear_hopeless(struct pglist_data *pgdat, 7578 unsigned int order, int highest_zoneidx) 7579 { 7580 if (pgdat_balanced(pgdat, order, highest_zoneidx)) 7581 kswapd_clear_hopeless(pgdat, current_is_kswapd() ? 7582 KSWAPD_CLEAR_HOPELESS_KSWAPD : KSWAPD_CLEAR_HOPELESS_DIRECT); 7583 } 7584 7585 bool kswapd_test_hopeless(pg_data_t *pgdat) 7586 { 7587 return atomic_read(&pgdat->kswapd_failures) >= MAX_RECLAIM_RETRIES; 7588 } 7589 7590 #ifdef CONFIG_HIBERNATION 7591 /* 7592 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of 7593 * freed pages. 7594 * 7595 * Rather than trying to age LRUs the aim is to preserve the overall 7596 * LRU order by reclaiming preferentially 7597 * inactive > active > active referenced > active mapped 7598 */ 7599 unsigned long shrink_all_memory(unsigned long nr_to_reclaim) 7600 { 7601 struct scan_control sc = { 7602 .nr_to_reclaim = nr_to_reclaim, 7603 .gfp_mask = GFP_HIGHUSER_MOVABLE, 7604 .reclaim_idx = MAX_NR_ZONES - 1, 7605 .priority = DEF_PRIORITY, 7606 .may_writepage = 1, 7607 .may_unmap = 1, 7608 .may_swap = 1, 7609 .hibernation_mode = 1, 7610 }; 7611 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask); 7612 unsigned long nr_reclaimed; 7613 unsigned int noreclaim_flag; 7614 7615 fs_reclaim_acquire(sc.gfp_mask); 7616 noreclaim_flag = memalloc_noreclaim_save(); 7617 set_task_reclaim_state(current, &sc.reclaim_state); 7618 7619 nr_reclaimed = do_try_to_free_pages(zonelist, &sc); 7620 7621 set_task_reclaim_state(current, NULL); 7622 memalloc_noreclaim_restore(noreclaim_flag); 7623 fs_reclaim_release(sc.gfp_mask); 7624 7625 return nr_reclaimed; 7626 } 7627 #endif /* CONFIG_HIBERNATION */ 7628 7629 /* 7630 * This kswapd start function will be called by init and node-hot-add. 7631 */ 7632 void __meminit kswapd_run(int nid) 7633 { 7634 pg_data_t *pgdat = NODE_DATA(nid); 7635 7636 pgdat_kswapd_lock(pgdat); 7637 if (!pgdat->kswapd) { 7638 pgdat->kswapd = kthread_create_on_node(kswapd, pgdat, nid, "kswapd%d", nid); 7639 if (IS_ERR(pgdat->kswapd)) { 7640 /* failure at boot is fatal */ 7641 pr_err("Failed to start kswapd on node %d, ret=%pe\n", 7642 nid, pgdat->kswapd); 7643 BUG_ON(system_state < SYSTEM_RUNNING); 7644 pgdat->kswapd = NULL; 7645 } else { 7646 wake_up_process(pgdat->kswapd); 7647 } 7648 } 7649 pgdat_kswapd_unlock(pgdat); 7650 } 7651 7652 /* 7653 * Called by memory hotplug when all memory in a node is offlined. Caller must 7654 * be holding mem_hotplug_begin/done(). 7655 */ 7656 void __meminit kswapd_stop(int nid) 7657 { 7658 pg_data_t *pgdat = NODE_DATA(nid); 7659 struct task_struct *kswapd; 7660 7661 pgdat_kswapd_lock(pgdat); 7662 kswapd = pgdat->kswapd; 7663 if (kswapd) { 7664 kthread_stop(kswapd); 7665 pgdat->kswapd = NULL; 7666 } 7667 pgdat_kswapd_unlock(pgdat); 7668 } 7669 7670 static const struct ctl_table vmscan_sysctl_table[] = { 7671 { 7672 .procname = "swappiness", 7673 .data = &vm_swappiness, 7674 .maxlen = sizeof(vm_swappiness), 7675 .mode = 0644, 7676 .proc_handler = proc_dointvec_minmax, 7677 .extra1 = SYSCTL_ZERO, 7678 .extra2 = SYSCTL_TWO_HUNDRED, 7679 }, 7680 #ifdef CONFIG_NUMA 7681 { 7682 .procname = "zone_reclaim_mode", 7683 .data = &node_reclaim_mode, 7684 .maxlen = sizeof(node_reclaim_mode), 7685 .mode = 0644, 7686 .proc_handler = proc_dointvec_minmax, 7687 .extra1 = SYSCTL_ZERO, 7688 } 7689 #endif 7690 }; 7691 7692 static int __init kswapd_init(void) 7693 { 7694 int nid; 7695 7696 swap_setup(); 7697 for_each_node_state(nid, N_MEMORY) 7698 kswapd_run(nid); 7699 register_sysctl_init("vm", vmscan_sysctl_table); 7700 return 0; 7701 } 7702 7703 module_init(kswapd_init) 7704 7705 #ifdef CONFIG_NUMA 7706 /* 7707 * Node reclaim mode 7708 * 7709 * If non-zero call node_reclaim when the number of free pages falls below 7710 * the watermarks. 7711 */ 7712 int node_reclaim_mode __read_mostly; 7713 7714 /* 7715 * Priority for NODE_RECLAIM. This determines the fraction of pages 7716 * of a node considered for each zone_reclaim. 4 scans 1/16th of 7717 * a zone. 7718 */ 7719 #define NODE_RECLAIM_PRIORITY 4 7720 7721 /* 7722 * Percentage of pages in a zone that must be unmapped for node_reclaim to 7723 * occur. 7724 */ 7725 int sysctl_min_unmapped_ratio = 1; 7726 7727 /* 7728 * If the number of slab pages in a zone grows beyond this percentage then 7729 * slab reclaim needs to occur. 7730 */ 7731 int sysctl_min_slab_ratio = 5; 7732 7733 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat) 7734 { 7735 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED); 7736 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) + 7737 node_page_state(pgdat, NR_ACTIVE_FILE); 7738 7739 /* 7740 * It's possible for there to be more file mapped pages than 7741 * accounted for by the pages on the file LRU lists because 7742 * tmpfs pages accounted for as ANON can also be FILE_MAPPED 7743 */ 7744 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0; 7745 } 7746 7747 /* Work out how many page cache pages we can reclaim in this reclaim_mode */ 7748 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat) 7749 { 7750 unsigned long nr_pagecache_reclaimable; 7751 unsigned long delta = 0; 7752 7753 /* 7754 * If RECLAIM_UNMAP is set, then all file pages are considered 7755 * potentially reclaimable. Otherwise, we have to worry about 7756 * pages like swapcache and node_unmapped_file_pages() provides 7757 * a better estimate 7758 */ 7759 if (node_reclaim_mode & RECLAIM_UNMAP) 7760 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES); 7761 else 7762 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat); 7763 7764 /* 7765 * Since we can't clean folios through reclaim, remove dirty file 7766 * folios from consideration. 7767 */ 7768 delta += node_page_state(pgdat, NR_FILE_DIRTY); 7769 7770 /* Watch for any possible underflows due to delta */ 7771 if (unlikely(delta > nr_pagecache_reclaimable)) 7772 delta = nr_pagecache_reclaimable; 7773 7774 return nr_pagecache_reclaimable - delta; 7775 } 7776 7777 /* 7778 * Try to free up some pages from this node through reclaim. 7779 */ 7780 static unsigned long __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, 7781 unsigned long nr_pages, 7782 struct scan_control *sc) 7783 { 7784 struct task_struct *p = current; 7785 unsigned int noreclaim_flag; 7786 unsigned long pflags; 7787 7788 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, sc->order, 7789 sc->gfp_mask); 7790 7791 cond_resched(); 7792 psi_memstall_enter(&pflags); 7793 delayacct_freepages_start(); 7794 fs_reclaim_acquire(sc->gfp_mask); 7795 /* 7796 * We need to be able to allocate from the reserves for RECLAIM_UNMAP 7797 */ 7798 noreclaim_flag = memalloc_noreclaim_save(); 7799 set_task_reclaim_state(p, &sc->reclaim_state); 7800 7801 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages || 7802 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) { 7803 /* 7804 * Free memory by calling shrink node with increasing 7805 * priorities until we have enough memory freed. 7806 */ 7807 do { 7808 shrink_node(pgdat, sc); 7809 } while (sc->nr_reclaimed < nr_pages && --sc->priority >= 0); 7810 } 7811 7812 set_task_reclaim_state(p, NULL); 7813 memalloc_noreclaim_restore(noreclaim_flag); 7814 fs_reclaim_release(sc->gfp_mask); 7815 delayacct_freepages_end(); 7816 psi_memstall_leave(&pflags); 7817 7818 trace_mm_vmscan_node_reclaim_end(sc->nr_reclaimed, 0); 7819 7820 return sc->nr_reclaimed; 7821 } 7822 7823 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order) 7824 { 7825 int ret; 7826 /* Minimum pages needed in order to stay on node */ 7827 const unsigned long nr_pages = 1 << order; 7828 struct scan_control sc = { 7829 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX), 7830 .gfp_mask = current_gfp_context(gfp_mask), 7831 .order = order, 7832 .priority = NODE_RECLAIM_PRIORITY, 7833 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE), 7834 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP), 7835 .may_swap = 1, 7836 .reclaim_idx = gfp_zone(gfp_mask), 7837 }; 7838 7839 /* 7840 * Node reclaim reclaims unmapped file backed pages and 7841 * slab pages if we are over the defined limits. 7842 * 7843 * A small portion of unmapped file backed pages is needed for 7844 * file I/O otherwise pages read by file I/O will be immediately 7845 * thrown out if the node is overallocated. So we do not reclaim 7846 * if less than a specified percentage of the node is used by 7847 * unmapped file backed pages. 7848 */ 7849 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages && 7850 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <= 7851 pgdat->min_slab_pages) 7852 return NODE_RECLAIM_FULL; 7853 7854 /* 7855 * Do not scan if the allocation should not be delayed. 7856 */ 7857 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC)) 7858 return NODE_RECLAIM_NOSCAN; 7859 7860 /* 7861 * Only run node reclaim on the local node or on nodes that do not 7862 * have associated processors. This will favor the local processor 7863 * over remote processors and spread off node memory allocations 7864 * as wide as possible. 7865 */ 7866 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id()) 7867 return NODE_RECLAIM_NOSCAN; 7868 7869 if (test_and_set_bit_lock(PGDAT_RECLAIM_LOCKED, &pgdat->flags)) 7870 return NODE_RECLAIM_NOSCAN; 7871 7872 ret = __node_reclaim(pgdat, gfp_mask, nr_pages, &sc) >= nr_pages; 7873 clear_bit_unlock(PGDAT_RECLAIM_LOCKED, &pgdat->flags); 7874 7875 if (ret) 7876 count_vm_event(PGSCAN_ZONE_RECLAIM_SUCCESS); 7877 else 7878 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED); 7879 7880 return ret; 7881 } 7882 7883 #else 7884 7885 static unsigned long __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, 7886 unsigned long nr_pages, 7887 struct scan_control *sc) 7888 { 7889 return 0; 7890 } 7891 7892 #endif 7893 7894 enum { 7895 MEMORY_RECLAIM_SWAPPINESS = 0, 7896 MEMORY_RECLAIM_SWAPPINESS_MAX, 7897 MEMORY_RECLAIM_NULL, 7898 }; 7899 static const match_table_t tokens = { 7900 { MEMORY_RECLAIM_SWAPPINESS, "swappiness=%d"}, 7901 { MEMORY_RECLAIM_SWAPPINESS_MAX, "swappiness=max"}, 7902 { MEMORY_RECLAIM_NULL, NULL }, 7903 }; 7904 7905 int user_proactive_reclaim(char *buf, 7906 struct mem_cgroup *memcg, pg_data_t *pgdat) 7907 { 7908 unsigned int nr_retries = MAX_RECLAIM_RETRIES; 7909 unsigned long nr_to_reclaim, nr_reclaimed = 0; 7910 int swappiness = -1; 7911 char *old_buf, *start; 7912 substring_t args[MAX_OPT_ARGS]; 7913 gfp_t gfp_mask = GFP_KERNEL; 7914 7915 if (!buf || (!memcg && !pgdat) || (memcg && pgdat)) 7916 return -EINVAL; 7917 7918 buf = strstrip(buf); 7919 7920 old_buf = buf; 7921 nr_to_reclaim = memparse(buf, &buf) / PAGE_SIZE; 7922 if (buf == old_buf) 7923 return -EINVAL; 7924 7925 buf = strstrip(buf); 7926 7927 while ((start = strsep(&buf, " ")) != NULL) { 7928 if (!strlen(start)) 7929 continue; 7930 switch (match_token(start, tokens, args)) { 7931 case MEMORY_RECLAIM_SWAPPINESS: 7932 if (match_int(&args[0], &swappiness)) 7933 return -EINVAL; 7934 if (swappiness < MIN_SWAPPINESS || 7935 swappiness > MAX_SWAPPINESS) 7936 return -EINVAL; 7937 break; 7938 case MEMORY_RECLAIM_SWAPPINESS_MAX: 7939 swappiness = SWAPPINESS_ANON_ONLY; 7940 break; 7941 default: 7942 return -EINVAL; 7943 } 7944 } 7945 7946 while (nr_reclaimed < nr_to_reclaim) { 7947 /* Will converge on zero, but reclaim enforces a minimum */ 7948 unsigned long batch_size = (nr_to_reclaim - nr_reclaimed) / 4; 7949 unsigned long reclaimed; 7950 7951 if (signal_pending(current)) 7952 return -EINTR; 7953 7954 /* 7955 * This is the final attempt, drain percpu lru caches in the 7956 * hope of introducing more evictable pages. 7957 */ 7958 if (!nr_retries) 7959 lru_add_drain_all(); 7960 7961 if (memcg) { 7962 unsigned int reclaim_options; 7963 7964 reclaim_options = MEMCG_RECLAIM_MAY_SWAP | 7965 MEMCG_RECLAIM_PROACTIVE; 7966 reclaimed = try_to_free_mem_cgroup_pages(memcg, 7967 batch_size, gfp_mask, 7968 reclaim_options, 7969 swappiness == -1 ? NULL : &swappiness); 7970 } else { 7971 struct scan_control sc = { 7972 .gfp_mask = current_gfp_context(gfp_mask), 7973 .reclaim_idx = gfp_zone(gfp_mask), 7974 .proactive_swappiness = swappiness == -1 ? NULL : &swappiness, 7975 .priority = DEF_PRIORITY, 7976 .may_writepage = 1, 7977 .nr_to_reclaim = max(batch_size, SWAP_CLUSTER_MAX), 7978 .may_unmap = 1, 7979 .may_swap = 1, 7980 .proactive = 1, 7981 }; 7982 7983 if (test_and_set_bit_lock(PGDAT_RECLAIM_LOCKED, 7984 &pgdat->flags)) 7985 return -EBUSY; 7986 7987 reclaimed = __node_reclaim(pgdat, gfp_mask, 7988 batch_size, &sc); 7989 clear_bit_unlock(PGDAT_RECLAIM_LOCKED, &pgdat->flags); 7990 } 7991 7992 if (!reclaimed && !nr_retries--) 7993 return -EAGAIN; 7994 7995 nr_reclaimed += reclaimed; 7996 } 7997 7998 return 0; 7999 } 8000 8001 /** 8002 * check_move_unevictable_folios - Move evictable folios to appropriate zone 8003 * lru list 8004 * @fbatch: Batch of lru folios to check. 8005 * 8006 * Checks folios for evictability, if an evictable folio is in the unevictable 8007 * lru list, moves it to the appropriate evictable lru list. This function 8008 * should be only used for lru folios. 8009 */ 8010 void check_move_unevictable_folios(struct folio_batch *fbatch) 8011 { 8012 struct lruvec *lruvec = NULL; 8013 int pgscanned = 0; 8014 int pgrescued = 0; 8015 int i; 8016 8017 for (i = 0; i < fbatch->nr; i++) { 8018 struct folio *folio = fbatch->folios[i]; 8019 int nr_pages = folio_nr_pages(folio); 8020 8021 pgscanned += nr_pages; 8022 8023 /* block memcg migration while the folio moves between lrus */ 8024 if (!folio_test_clear_lru(folio)) 8025 continue; 8026 8027 lruvec = folio_lruvec_relock_irq(folio, lruvec); 8028 if (folio_evictable(folio) && folio_test_unevictable(folio)) { 8029 lruvec_del_folio(lruvec, folio); 8030 folio_clear_unevictable(folio); 8031 lruvec_add_folio(lruvec, folio); 8032 pgrescued += nr_pages; 8033 } 8034 folio_set_lru(folio); 8035 } 8036 8037 if (lruvec) { 8038 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued); 8039 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned); 8040 lruvec_unlock_irq(lruvec); 8041 } else if (pgscanned) { 8042 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned); 8043 } 8044 } 8045 EXPORT_SYMBOL_GPL(check_move_unevictable_folios); 8046 8047 #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA) 8048 static ssize_t reclaim_store(struct device *dev, 8049 struct device_attribute *attr, 8050 const char *buf, size_t count) 8051 { 8052 int ret, nid = dev->id; 8053 8054 ret = user_proactive_reclaim((char *)buf, NULL, NODE_DATA(nid)); 8055 return ret ? -EAGAIN : count; 8056 } 8057 8058 static DEVICE_ATTR_WO(reclaim); 8059 int reclaim_register_node(struct node *node) 8060 { 8061 return device_create_file(&node->dev, &dev_attr_reclaim); 8062 } 8063 8064 void reclaim_unregister_node(struct node *node) 8065 { 8066 return device_remove_file(&node->dev, &dev_attr_reclaim); 8067 } 8068 #endif 8069