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