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