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