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