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