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