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