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