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