1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds 4 * 5 * Swap reorganised 29.12.95, Stephen Tweedie. 6 * kswapd added: 7.1.96 sct 7 * Removed kswapd_ctl limits, and swap out as many pages as needed 8 * to bring the system back to freepages.high: 2.4.97, Rik van Riel. 9 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com). 10 * Multiqueue VM started 5.8.00, Rik van Riel. 11 */ 12 13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 14 15 #include <linux/mm.h> 16 #include <linux/sched/mm.h> 17 #include <linux/module.h> 18 #include <linux/gfp.h> 19 #include <linux/kernel_stat.h> 20 #include <linux/swap.h> 21 #include <linux/pagemap.h> 22 #include <linux/init.h> 23 #include <linux/highmem.h> 24 #include <linux/vmpressure.h> 25 #include <linux/vmstat.h> 26 #include <linux/file.h> 27 #include <linux/writeback.h> 28 #include <linux/blkdev.h> 29 #include <linux/buffer_head.h> /* for buffer_heads_over_limit */ 30 #include <linux/mm_inline.h> 31 #include <linux/backing-dev.h> 32 #include <linux/rmap.h> 33 #include <linux/topology.h> 34 #include <linux/cpu.h> 35 #include <linux/cpuset.h> 36 #include <linux/compaction.h> 37 #include <linux/notifier.h> 38 #include <linux/delay.h> 39 #include <linux/kthread.h> 40 #include <linux/freezer.h> 41 #include <linux/memcontrol.h> 42 #include <linux/migrate.h> 43 #include <linux/delayacct.h> 44 #include <linux/sysctl.h> 45 #include <linux/memory-tiers.h> 46 #include <linux/oom.h> 47 #include <linux/pagevec.h> 48 #include <linux/prefetch.h> 49 #include <linux/printk.h> 50 #include <linux/dax.h> 51 #include <linux/psi.h> 52 #include <linux/pagewalk.h> 53 #include <linux/shmem_fs.h> 54 #include <linux/ctype.h> 55 #include <linux/debugfs.h> 56 #include <linux/khugepaged.h> 57 #include <linux/rculist_nulls.h> 58 #include <linux/random.h> 59 #include <linux/mmu_notifier.h> 60 #include <linux/parser.h> 61 62 #include <asm/tlbflush.h> 63 #include <asm/div64.h> 64 65 #include <linux/swapops.h> 66 #include <linux/balloon_compaction.h> 67 #include <linux/sched/sysctl.h> 68 69 #include "internal.h" 70 #include "swap.h" 71 72 #define CREATE_TRACE_POINTS 73 #include <trace/events/vmscan.h> 74 75 struct scan_control { 76 /* How many pages shrink_list() should reclaim */ 77 unsigned long nr_to_reclaim; 78 79 /* 80 * Nodemask of nodes allowed by the caller. If NULL, all nodes 81 * are scanned. 82 */ 83 nodemask_t *nodemask; 84 85 /* 86 * The memory cgroup that hit its limit and as a result is the 87 * primary target of this reclaim invocation. 88 */ 89 struct mem_cgroup *target_mem_cgroup; 90 91 /* 92 * Scan pressure balancing between anon and file LRUs 93 */ 94 unsigned long anon_cost; 95 unsigned long file_cost; 96 97 /* Swappiness value for proactive reclaim. Always use sc_swappiness()! */ 98 int *proactive_swappiness; 99 100 /* Can active folios be deactivated as part of reclaim? */ 101 #define DEACTIVATE_ANON 1 102 #define DEACTIVATE_FILE 2 103 unsigned int may_deactivate:2; 104 unsigned int force_deactivate:1; 105 unsigned int skipped_deactivate:1; 106 107 /* zone_reclaim_mode, boost reclaim */ 108 unsigned int may_writepage:1; 109 110 /* zone_reclaim_mode */ 111 unsigned int may_unmap:1; 112 113 /* zome_reclaim_mode, boost reclaim, cgroup restrictions */ 114 unsigned int may_swap:1; 115 116 /* Not allow cache_trim_mode to be turned on as part of reclaim? */ 117 unsigned int no_cache_trim_mode:1; 118 119 /* Has cache_trim_mode failed at least once? */ 120 unsigned int cache_trim_mode_failed:1; 121 122 /* Proactive reclaim invoked by userspace */ 123 unsigned int proactive:1; 124 125 /* 126 * Cgroup memory below memory.low is protected as long as we 127 * don't threaten to OOM. If any cgroup is reclaimed at 128 * reduced force or passed over entirely due to its memory.low 129 * setting (memcg_low_skipped), and nothing is reclaimed as a 130 * result, then go back for one more cycle that reclaims the protected 131 * memory (memcg_low_reclaim) to avert OOM. 132 */ 133 unsigned int memcg_low_reclaim:1; 134 unsigned int memcg_low_skipped:1; 135 136 /* Shared cgroup tree walk failed, rescan the whole tree */ 137 unsigned int memcg_full_walk:1; 138 139 unsigned int hibernation_mode:1; 140 141 /* One of the zones is ready for compaction */ 142 unsigned int compaction_ready:1; 143 144 /* There is easily reclaimable cold cache in the current node */ 145 unsigned int cache_trim_mode:1; 146 147 /* The file folios on the current node are dangerously low */ 148 unsigned int file_is_tiny:1; 149 150 /* Always discard instead of demoting to lower tier memory */ 151 unsigned int no_demotion:1; 152 153 /* Allocation order */ 154 s8 order; 155 156 /* Scan (total_size >> priority) pages at once */ 157 s8 priority; 158 159 /* The highest zone to isolate folios for reclaim from */ 160 s8 reclaim_idx; 161 162 /* This context's GFP mask */ 163 gfp_t gfp_mask; 164 165 /* Incremented by the number of inactive pages that were scanned */ 166 unsigned long nr_scanned; 167 168 /* Number of pages freed so far during a call to shrink_zones() */ 169 unsigned long nr_reclaimed; 170 171 struct { 172 unsigned int dirty; 173 unsigned int unqueued_dirty; 174 unsigned int congested; 175 unsigned int writeback; 176 unsigned int immediate; 177 unsigned int file_taken; 178 unsigned int taken; 179 } nr; 180 181 /* for recording the reclaimed slab by now */ 182 struct reclaim_state reclaim_state; 183 }; 184 185 #ifdef ARCH_HAS_PREFETCHW 186 #define prefetchw_prev_lru_folio(_folio, _base, _field) \ 187 do { \ 188 if ((_folio)->lru.prev != _base) { \ 189 struct folio *prev; \ 190 \ 191 prev = lru_to_folio(&(_folio->lru)); \ 192 prefetchw(&prev->_field); \ 193 } \ 194 } while (0) 195 #else 196 #define prefetchw_prev_lru_folio(_folio, _base, _field) do { } while (0) 197 #endif 198 199 /* 200 * From 0 .. MAX_SWAPPINESS. Higher means more swappy. 201 */ 202 int vm_swappiness = 60; 203 204 #ifdef CONFIG_MEMCG 205 206 /* Returns true for reclaim through cgroup limits or cgroup interfaces. */ 207 static bool cgroup_reclaim(struct scan_control *sc) 208 { 209 return sc->target_mem_cgroup; 210 } 211 212 /* 213 * Returns true for reclaim on the root cgroup. This is true for direct 214 * allocator reclaim and reclaim through cgroup interfaces on the root cgroup. 215 */ 216 static bool root_reclaim(struct scan_control *sc) 217 { 218 return !sc->target_mem_cgroup || mem_cgroup_is_root(sc->target_mem_cgroup); 219 } 220 221 /** 222 * writeback_throttling_sane - is the usual dirty throttling mechanism available? 223 * @sc: scan_control in question 224 * 225 * The normal page dirty throttling mechanism in balance_dirty_pages() is 226 * completely broken with the legacy memcg and direct stalling in 227 * shrink_folio_list() is used for throttling instead, which lacks all the 228 * niceties such as fairness, adaptive pausing, bandwidth proportional 229 * allocation and configurability. 230 * 231 * This function tests whether the vmscan currently in progress can assume 232 * that the normal dirty throttling mechanism is operational. 233 */ 234 static bool writeback_throttling_sane(struct scan_control *sc) 235 { 236 if (!cgroup_reclaim(sc)) 237 return true; 238 #ifdef CONFIG_CGROUP_WRITEBACK 239 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) 240 return true; 241 #endif 242 return false; 243 } 244 245 static int sc_swappiness(struct scan_control *sc, struct mem_cgroup *memcg) 246 { 247 if (sc->proactive && sc->proactive_swappiness) 248 return *sc->proactive_swappiness; 249 return mem_cgroup_swappiness(memcg); 250 } 251 #else 252 static bool cgroup_reclaim(struct scan_control *sc) 253 { 254 return false; 255 } 256 257 static bool root_reclaim(struct scan_control *sc) 258 { 259 return true; 260 } 261 262 static bool writeback_throttling_sane(struct scan_control *sc) 263 { 264 return true; 265 } 266 267 static int sc_swappiness(struct scan_control *sc, struct mem_cgroup *memcg) 268 { 269 return READ_ONCE(vm_swappiness); 270 } 271 #endif 272 273 /* for_each_managed_zone_pgdat - helper macro to iterate over all managed zones in a pgdat up to 274 * and including the specified highidx 275 * @zone: The current zone in the iterator 276 * @pgdat: The pgdat which node_zones are being iterated 277 * @idx: The index variable 278 * @highidx: The index of the highest zone to return 279 * 280 * This macro iterates through all managed zones up to and including the specified highidx. 281 * The zone iterator enters an invalid state after macro call and must be reinitialized 282 * before it can be used again. 283 */ 284 #define for_each_managed_zone_pgdat(zone, pgdat, idx, highidx) \ 285 for ((idx) = 0, (zone) = (pgdat)->node_zones; \ 286 (idx) <= (highidx); \ 287 (idx)++, (zone)++) \ 288 if (!managed_zone(zone)) \ 289 continue; \ 290 else 291 292 static void set_task_reclaim_state(struct task_struct *task, 293 struct reclaim_state *rs) 294 { 295 /* Check for an overwrite */ 296 WARN_ON_ONCE(rs && task->reclaim_state); 297 298 /* Check for the nulling of an already-nulled member */ 299 WARN_ON_ONCE(!rs && !task->reclaim_state); 300 301 task->reclaim_state = rs; 302 } 303 304 /* 305 * flush_reclaim_state(): add pages reclaimed outside of LRU-based reclaim to 306 * scan_control->nr_reclaimed. 307 */ 308 static void flush_reclaim_state(struct scan_control *sc) 309 { 310 /* 311 * Currently, reclaim_state->reclaimed includes three types of pages 312 * freed outside of vmscan: 313 * (1) Slab pages. 314 * (2) Clean file pages from pruned inodes (on highmem systems). 315 * (3) XFS freed buffer pages. 316 * 317 * For all of these cases, we cannot universally link the pages to a 318 * single memcg. For example, a memcg-aware shrinker can free one object 319 * charged to the target memcg, causing an entire page to be freed. 320 * If we count the entire page as reclaimed from the memcg, we end up 321 * overestimating the reclaimed amount (potentially under-reclaiming). 322 * 323 * Only count such pages for global reclaim to prevent under-reclaiming 324 * from the target memcg; preventing unnecessary retries during memcg 325 * charging and false positives from proactive reclaim. 326 * 327 * For uncommon cases where the freed pages were actually mostly 328 * charged to the target memcg, we end up underestimating the reclaimed 329 * amount. This should be fine. The freed pages will be uncharged 330 * anyway, even if they are not counted here properly, and we will be 331 * able to make forward progress in charging (which is usually in a 332 * retry loop). 333 * 334 * We can go one step further, and report the uncharged objcg pages in 335 * memcg reclaim, to make reporting more accurate and reduce 336 * underestimation, but it's probably not worth the complexity for now. 337 */ 338 if (current->reclaim_state && root_reclaim(sc)) { 339 sc->nr_reclaimed += current->reclaim_state->reclaimed; 340 current->reclaim_state->reclaimed = 0; 341 } 342 } 343 344 static bool can_demote(int nid, struct scan_control *sc, 345 struct mem_cgroup *memcg) 346 { 347 int demotion_nid; 348 349 if (!numa_demotion_enabled) 350 return false; 351 if (sc && sc->no_demotion) 352 return false; 353 354 demotion_nid = next_demotion_node(nid); 355 if (demotion_nid == NUMA_NO_NODE) 356 return false; 357 358 /* If demotion node isn't in the cgroup's mems_allowed, fall back */ 359 return mem_cgroup_node_allowed(memcg, demotion_nid); 360 } 361 362 static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg, 363 int nid, 364 struct scan_control *sc) 365 { 366 if (memcg == NULL) { 367 /* 368 * For non-memcg reclaim, is there 369 * space in any swap device? 370 */ 371 if (get_nr_swap_pages() > 0) 372 return true; 373 } else { 374 /* Is the memcg below its swap limit? */ 375 if (mem_cgroup_get_nr_swap_pages(memcg) > 0) 376 return true; 377 } 378 379 /* 380 * The page can not be swapped. 381 * 382 * Can it be reclaimed from this node via demotion? 383 */ 384 return can_demote(nid, sc, memcg); 385 } 386 387 /* 388 * This misses isolated folios which are not accounted for to save counters. 389 * As the data only determines if reclaim or compaction continues, it is 390 * not expected that isolated folios will be a dominating factor. 391 */ 392 unsigned long zone_reclaimable_pages(struct zone *zone) 393 { 394 unsigned long nr; 395 396 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) + 397 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE); 398 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL)) 399 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) + 400 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON); 401 402 return nr; 403 } 404 405 /** 406 * lruvec_lru_size - Returns the number of pages on the given LRU list. 407 * @lruvec: lru vector 408 * @lru: lru to use 409 * @zone_idx: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list) 410 */ 411 static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, 412 int zone_idx) 413 { 414 unsigned long size = 0; 415 int zid; 416 struct zone *zone; 417 418 for_each_managed_zone_pgdat(zone, lruvec_pgdat(lruvec), zid, zone_idx) { 419 if (!mem_cgroup_disabled()) 420 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid); 421 else 422 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru); 423 } 424 return size; 425 } 426 427 static unsigned long drop_slab_node(int nid) 428 { 429 unsigned long freed = 0; 430 struct mem_cgroup *memcg = NULL; 431 432 memcg = mem_cgroup_iter(NULL, NULL, NULL); 433 do { 434 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0); 435 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL); 436 437 return freed; 438 } 439 440 void drop_slab(void) 441 { 442 int nid; 443 int shift = 0; 444 unsigned long freed; 445 446 do { 447 freed = 0; 448 for_each_online_node(nid) { 449 if (fatal_signal_pending(current)) 450 return; 451 452 freed += drop_slab_node(nid); 453 } 454 } while ((freed >> shift++) > 1); 455 } 456 457 #define CHECK_RECLAIMER_OFFSET(type) \ 458 do { \ 459 BUILD_BUG_ON(PGSTEAL_##type - PGSTEAL_KSWAPD != \ 460 PGDEMOTE_##type - PGDEMOTE_KSWAPD); \ 461 BUILD_BUG_ON(PGSTEAL_##type - PGSTEAL_KSWAPD != \ 462 PGSCAN_##type - PGSCAN_KSWAPD); \ 463 } while (0) 464 465 static int reclaimer_offset(struct scan_control *sc) 466 { 467 CHECK_RECLAIMER_OFFSET(DIRECT); 468 CHECK_RECLAIMER_OFFSET(KHUGEPAGED); 469 CHECK_RECLAIMER_OFFSET(PROACTIVE); 470 471 if (current_is_kswapd()) 472 return 0; 473 if (current_is_khugepaged()) 474 return PGSTEAL_KHUGEPAGED - PGSTEAL_KSWAPD; 475 if (sc->proactive) 476 return PGSTEAL_PROACTIVE - PGSTEAL_KSWAPD; 477 return PGSTEAL_DIRECT - PGSTEAL_KSWAPD; 478 } 479 480 /* 481 * We detected a synchronous write error writing a folio out. Probably 482 * -ENOSPC. We need to propagate that into the address_space for a subsequent 483 * fsync(), msync() or close(). 484 * 485 * The tricky part is that after writepage we cannot touch the mapping: nothing 486 * prevents it from being freed up. But we have a ref on the folio and once 487 * that folio is locked, the mapping is pinned. 488 * 489 * We're allowed to run sleeping folio_lock() here because we know the caller has 490 * __GFP_FS. 491 */ 492 static void handle_write_error(struct address_space *mapping, 493 struct folio *folio, int error) 494 { 495 folio_lock(folio); 496 if (folio_mapping(folio) == mapping) 497 mapping_set_error(mapping, error); 498 folio_unlock(folio); 499 } 500 501 static bool skip_throttle_noprogress(pg_data_t *pgdat) 502 { 503 int reclaimable = 0, write_pending = 0; 504 int i; 505 struct zone *zone; 506 /* 507 * If kswapd is disabled, reschedule if necessary but do not 508 * throttle as the system is likely near OOM. 509 */ 510 if (atomic_read(&pgdat->kswapd_failures) >= MAX_RECLAIM_RETRIES) 511 return true; 512 513 /* 514 * If there are a lot of dirty/writeback folios then do not 515 * throttle as throttling will occur when the folios cycle 516 * towards the end of the LRU if still under writeback. 517 */ 518 for_each_managed_zone_pgdat(zone, pgdat, i, MAX_NR_ZONES - 1) { 519 reclaimable += zone_reclaimable_pages(zone); 520 write_pending += zone_page_state_snapshot(zone, 521 NR_ZONE_WRITE_PENDING); 522 } 523 if (2 * write_pending <= reclaimable) 524 return true; 525 526 return false; 527 } 528 529 void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason) 530 { 531 wait_queue_head_t *wqh = &pgdat->reclaim_wait[reason]; 532 long timeout, ret; 533 DEFINE_WAIT(wait); 534 535 /* 536 * Do not throttle user workers, kthreads other than kswapd or 537 * workqueues. They may be required for reclaim to make 538 * forward progress (e.g. journalling workqueues or kthreads). 539 */ 540 if (!current_is_kswapd() && 541 current->flags & (PF_USER_WORKER|PF_KTHREAD)) { 542 cond_resched(); 543 return; 544 } 545 546 /* 547 * These figures are pulled out of thin air. 548 * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many 549 * parallel reclaimers which is a short-lived event so the timeout is 550 * short. Failing to make progress or waiting on writeback are 551 * potentially long-lived events so use a longer timeout. This is shaky 552 * logic as a failure to make progress could be due to anything from 553 * writeback to a slow device to excessive referenced folios at the tail 554 * of the inactive LRU. 555 */ 556 switch(reason) { 557 case VMSCAN_THROTTLE_WRITEBACK: 558 timeout = HZ/10; 559 560 if (atomic_inc_return(&pgdat->nr_writeback_throttled) == 1) { 561 WRITE_ONCE(pgdat->nr_reclaim_start, 562 node_page_state(pgdat, NR_THROTTLED_WRITTEN)); 563 } 564 565 break; 566 case VMSCAN_THROTTLE_CONGESTED: 567 fallthrough; 568 case VMSCAN_THROTTLE_NOPROGRESS: 569 if (skip_throttle_noprogress(pgdat)) { 570 cond_resched(); 571 return; 572 } 573 574 timeout = 1; 575 576 break; 577 case VMSCAN_THROTTLE_ISOLATED: 578 timeout = HZ/50; 579 break; 580 default: 581 WARN_ON_ONCE(1); 582 timeout = HZ; 583 break; 584 } 585 586 prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE); 587 ret = schedule_timeout(timeout); 588 finish_wait(wqh, &wait); 589 590 if (reason == VMSCAN_THROTTLE_WRITEBACK) 591 atomic_dec(&pgdat->nr_writeback_throttled); 592 593 trace_mm_vmscan_throttled(pgdat->node_id, jiffies_to_usecs(timeout), 594 jiffies_to_usecs(timeout - ret), 595 reason); 596 } 597 598 /* 599 * Account for folios written if tasks are throttled waiting on dirty 600 * folios to clean. If enough folios have been cleaned since throttling 601 * started then wakeup the throttled tasks. 602 */ 603 void __acct_reclaim_writeback(pg_data_t *pgdat, struct folio *folio, 604 int nr_throttled) 605 { 606 unsigned long nr_written; 607 608 node_stat_add_folio(folio, NR_THROTTLED_WRITTEN); 609 610 /* 611 * This is an inaccurate read as the per-cpu deltas may not 612 * be synchronised. However, given that the system is 613 * writeback throttled, it is not worth taking the penalty 614 * of getting an accurate count. At worst, the throttle 615 * timeout guarantees forward progress. 616 */ 617 nr_written = node_page_state(pgdat, NR_THROTTLED_WRITTEN) - 618 READ_ONCE(pgdat->nr_reclaim_start); 619 620 if (nr_written > SWAP_CLUSTER_MAX * nr_throttled) 621 wake_up(&pgdat->reclaim_wait[VMSCAN_THROTTLE_WRITEBACK]); 622 } 623 624 /* possible outcome of pageout() */ 625 typedef enum { 626 /* failed to write folio out, folio is locked */ 627 PAGE_KEEP, 628 /* move folio to the active list, folio is locked */ 629 PAGE_ACTIVATE, 630 /* folio has been sent to the disk successfully, folio is unlocked */ 631 PAGE_SUCCESS, 632 /* folio is clean and locked */ 633 PAGE_CLEAN, 634 } pageout_t; 635 636 static pageout_t writeout(struct folio *folio, struct address_space *mapping, 637 struct swap_iocb **plug, struct list_head *folio_list) 638 { 639 int res; 640 641 folio_set_reclaim(folio); 642 643 /* 644 * The large shmem folio can be split if CONFIG_THP_SWAP is not enabled 645 * or we failed to allocate contiguous swap entries, in which case 646 * the split out folios get added back to folio_list. 647 */ 648 if (shmem_mapping(mapping)) 649 res = shmem_writeout(folio, plug, folio_list); 650 else 651 res = swap_writeout(folio, plug); 652 653 if (res < 0) 654 handle_write_error(mapping, folio, res); 655 if (res == AOP_WRITEPAGE_ACTIVATE) { 656 folio_clear_reclaim(folio); 657 return PAGE_ACTIVATE; 658 } 659 660 /* synchronous write? */ 661 if (!folio_test_writeback(folio)) 662 folio_clear_reclaim(folio); 663 664 trace_mm_vmscan_write_folio(folio); 665 node_stat_add_folio(folio, NR_VMSCAN_WRITE); 666 return PAGE_SUCCESS; 667 } 668 669 /* 670 * pageout is called by shrink_folio_list() for each dirty folio. 671 */ 672 static pageout_t pageout(struct folio *folio, struct address_space *mapping, 673 struct swap_iocb **plug, struct list_head *folio_list) 674 { 675 /* 676 * We no longer attempt to writeback filesystem folios here, other 677 * than tmpfs/shmem. That's taken care of in page-writeback. 678 * If we find a dirty filesystem folio at the end of the LRU list, 679 * typically that means the filesystem is saturating the storage 680 * with contiguous writes and telling it to write a folio here 681 * would only make the situation worse by injecting an element 682 * of random access. 683 * 684 * If the folio is swapcache, write it back even if that would 685 * block, for some throttling. This happens by accident, because 686 * swap_backing_dev_info is bust: it doesn't reflect the 687 * congestion state of the swapdevs. Easy to fix, if needed. 688 * 689 * A freeable shmem or swapcache folio is referenced only by the 690 * caller that isolated the folio and the page cache. 691 */ 692 if (folio_ref_count(folio) != 1 + folio_nr_pages(folio) || !mapping) 693 return PAGE_KEEP; 694 if (!shmem_mapping(mapping) && !folio_test_anon(folio)) 695 return PAGE_ACTIVATE; 696 if (!folio_clear_dirty_for_io(folio)) 697 return PAGE_CLEAN; 698 return writeout(folio, mapping, plug, folio_list); 699 } 700 701 /* 702 * Same as remove_mapping, but if the folio is removed from the mapping, it 703 * gets returned with a refcount of 0. 704 */ 705 static int __remove_mapping(struct address_space *mapping, struct folio *folio, 706 bool reclaimed, struct mem_cgroup *target_memcg) 707 { 708 int refcount; 709 void *shadow = NULL; 710 struct swap_cluster_info *ci; 711 712 BUG_ON(!folio_test_locked(folio)); 713 BUG_ON(mapping != folio_mapping(folio)); 714 715 if (folio_test_swapcache(folio)) { 716 ci = swap_cluster_get_and_lock_irq(folio); 717 } else { 718 spin_lock(&mapping->host->i_lock); 719 xa_lock_irq(&mapping->i_pages); 720 } 721 722 /* 723 * The non racy check for a busy folio. 724 * 725 * Must be careful with the order of the tests. When someone has 726 * a ref to the folio, it may be possible that they dirty it then 727 * drop the reference. So if the dirty flag is tested before the 728 * refcount here, then the following race may occur: 729 * 730 * get_user_pages(&page); 731 * [user mapping goes away] 732 * write_to(page); 733 * !folio_test_dirty(folio) [good] 734 * folio_set_dirty(folio); 735 * folio_put(folio); 736 * !refcount(folio) [good, discard it] 737 * 738 * [oops, our write_to data is lost] 739 * 740 * Reversing the order of the tests ensures such a situation cannot 741 * escape unnoticed. The smp_rmb is needed to ensure the folio->flags 742 * load is not satisfied before that of folio->_refcount. 743 * 744 * Note that if the dirty flag is always set via folio_mark_dirty, 745 * and thus under the i_pages lock, then this ordering is not required. 746 */ 747 refcount = 1 + folio_nr_pages(folio); 748 if (!folio_ref_freeze(folio, refcount)) 749 goto cannot_free; 750 /* note: atomic_cmpxchg in folio_ref_freeze provides the smp_rmb */ 751 if (unlikely(folio_test_dirty(folio))) { 752 folio_ref_unfreeze(folio, refcount); 753 goto cannot_free; 754 } 755 756 if (folio_test_swapcache(folio)) { 757 swp_entry_t swap = folio->swap; 758 759 if (reclaimed && !mapping_exiting(mapping)) 760 shadow = workingset_eviction(folio, target_memcg); 761 __swap_cache_del_folio(ci, folio, swap, shadow); 762 memcg1_swapout(folio, swap); 763 swap_cluster_unlock_irq(ci); 764 put_swap_folio(folio, swap); 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) || 967 (folio_test_anon(folio) && !folio_test_swapbacked(folio))) { 968 *dirty = false; 969 *writeback = false; 970 return; 971 } 972 973 /* By default assume that the folio flags are accurate */ 974 *dirty = folio_test_dirty(folio); 975 *writeback = folio_test_writeback(folio); 976 977 /* Verify dirty/writeback state if the filesystem supports it */ 978 if (!folio_test_private(folio)) 979 return; 980 981 mapping = folio_mapping(folio); 982 if (mapping && mapping->a_ops->is_dirty_writeback) 983 mapping->a_ops->is_dirty_writeback(folio, dirty, writeback); 984 } 985 986 static struct folio *alloc_demote_folio(struct folio *src, 987 unsigned long private) 988 { 989 struct folio *dst; 990 nodemask_t *allowed_mask; 991 struct migration_target_control *mtc; 992 993 mtc = (struct migration_target_control *)private; 994 995 allowed_mask = mtc->nmask; 996 /* 997 * make sure we allocate from the target node first also trying to 998 * demote or reclaim pages from the target node via kswapd if we are 999 * low on free memory on target node. If we don't do this and if 1000 * we have free memory on the slower(lower) memtier, we would start 1001 * allocating pages from slower(lower) memory tiers without even forcing 1002 * a demotion of cold pages from the target memtier. This can result 1003 * in the kernel placing hot pages in slower(lower) memory tiers. 1004 */ 1005 mtc->nmask = NULL; 1006 mtc->gfp_mask |= __GFP_THISNODE; 1007 dst = alloc_migration_target(src, (unsigned long)mtc); 1008 if (dst) 1009 return dst; 1010 1011 mtc->gfp_mask &= ~__GFP_THISNODE; 1012 mtc->nmask = allowed_mask; 1013 1014 return alloc_migration_target(src, (unsigned long)mtc); 1015 } 1016 1017 /* 1018 * Take folios on @demote_folios and attempt to demote them to another node. 1019 * Folios which are not demoted are left on @demote_folios. 1020 */ 1021 static unsigned int demote_folio_list(struct list_head *demote_folios, 1022 struct pglist_data *pgdat) 1023 { 1024 int target_nid = next_demotion_node(pgdat->node_id); 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 .nid = target_nid, 1037 .nmask = &allowed_mask, 1038 .reason = MR_DEMOTION, 1039 }; 1040 1041 if (list_empty(demote_folios)) 1042 return 0; 1043 1044 if (target_nid == NUMA_NO_NODE) 1045 return 0; 1046 1047 node_get_allowed_targets(pgdat, &allowed_mask); 1048 1049 /* Demotion ignores all cpuset and mempolicy settings */ 1050 migrate_pages(demote_folios, alloc_demote_folio, NULL, 1051 (unsigned long)&mtc, MIGRATE_ASYNC, MR_DEMOTION, 1052 &nr_succeeded); 1053 1054 return nr_succeeded; 1055 } 1056 1057 static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask) 1058 { 1059 if (gfp_mask & __GFP_FS) 1060 return true; 1061 if (!folio_test_swapcache(folio) || !(gfp_mask & __GFP_IO)) 1062 return false; 1063 /* 1064 * We can "enter_fs" for swap-cache with only __GFP_IO 1065 * providing this isn't SWP_FS_OPS. 1066 * ->flags can be updated non-atomicially (scan_swap_map_slots), 1067 * but that will never affect SWP_FS_OPS, so the data_race 1068 * is safe. 1069 */ 1070 return !data_race(folio_swap_flags(folio) & SWP_FS_OPS); 1071 } 1072 1073 /* 1074 * shrink_folio_list() returns the number of reclaimed pages 1075 */ 1076 static unsigned int shrink_folio_list(struct list_head *folio_list, 1077 struct pglist_data *pgdat, struct scan_control *sc, 1078 struct reclaim_stat *stat, bool ignore_references, 1079 struct mem_cgroup *memcg) 1080 { 1081 struct folio_batch free_folios; 1082 LIST_HEAD(ret_folios); 1083 LIST_HEAD(demote_folios); 1084 unsigned int nr_reclaimed = 0, nr_demoted = 0; 1085 unsigned int pgactivate = 0; 1086 bool do_demote_pass; 1087 struct swap_iocb *plug = NULL; 1088 1089 folio_batch_init(&free_folios); 1090 memset(stat, 0, sizeof(*stat)); 1091 cond_resched(); 1092 do_demote_pass = can_demote(pgdat->node_id, sc, memcg); 1093 1094 retry: 1095 while (!list_empty(folio_list)) { 1096 struct address_space *mapping; 1097 struct folio *folio; 1098 enum folio_references references = FOLIOREF_RECLAIM; 1099 bool dirty, writeback; 1100 unsigned int nr_pages; 1101 1102 cond_resched(); 1103 1104 folio = lru_to_folio(folio_list); 1105 list_del(&folio->lru); 1106 1107 if (!folio_trylock(folio)) 1108 goto keep; 1109 1110 if (folio_contain_hwpoisoned_page(folio)) { 1111 /* 1112 * unmap_poisoned_folio() can't handle large 1113 * folio, just skip it. memory_failure() will 1114 * handle it if the UCE is triggered again. 1115 */ 1116 if (folio_test_large(folio)) 1117 goto keep_locked; 1118 1119 unmap_poisoned_folio(folio, folio_pfn(folio), false); 1120 folio_unlock(folio); 1121 folio_put(folio); 1122 continue; 1123 } 1124 1125 VM_BUG_ON_FOLIO(folio_test_active(folio), folio); 1126 1127 nr_pages = folio_nr_pages(folio); 1128 1129 /* Account the number of base pages */ 1130 sc->nr_scanned += nr_pages; 1131 1132 if (unlikely(!folio_evictable(folio))) 1133 goto activate_locked; 1134 1135 if (!sc->may_unmap && folio_mapped(folio)) 1136 goto keep_locked; 1137 1138 /* 1139 * The number of dirty pages determines if a node is marked 1140 * reclaim_congested. kswapd will stall and start writing 1141 * folios if the tail of the LRU is all dirty unqueued folios. 1142 */ 1143 folio_check_dirty_writeback(folio, &dirty, &writeback); 1144 if (dirty || writeback) 1145 stat->nr_dirty += nr_pages; 1146 1147 if (dirty && !writeback) 1148 stat->nr_unqueued_dirty += nr_pages; 1149 1150 /* 1151 * Treat this folio as congested if folios are cycling 1152 * through the LRU so quickly that the folios marked 1153 * for immediate reclaim are making it to the end of 1154 * the LRU a second time. 1155 */ 1156 if (writeback && folio_test_reclaim(folio)) 1157 stat->nr_congested += nr_pages; 1158 1159 /* 1160 * If a folio at the tail of the LRU is under writeback, there 1161 * are three cases to consider. 1162 * 1163 * 1) If reclaim is encountering an excessive number 1164 * of folios under writeback and this folio has both 1165 * the writeback and reclaim flags set, then it 1166 * indicates that folios are being queued for I/O but 1167 * are being recycled through the LRU before the I/O 1168 * can complete. Waiting on the folio itself risks an 1169 * indefinite stall if it is impossible to writeback 1170 * the folio due to I/O error or disconnected storage 1171 * so instead note that the LRU is being scanned too 1172 * quickly and the caller can stall after the folio 1173 * list has been processed. 1174 * 1175 * 2) Global or new memcg reclaim encounters a folio that is 1176 * not marked for immediate reclaim, or the caller does not 1177 * have __GFP_FS (or __GFP_IO if it's simply going to swap, 1178 * not to fs), or the folio belongs to a mapping where 1179 * waiting on writeback during reclaim may lead to a deadlock. 1180 * In this case mark the folio for immediate reclaim and 1181 * continue scanning. 1182 * 1183 * Require may_enter_fs() because we would wait on fs, which 1184 * may not have submitted I/O yet. And the loop driver might 1185 * enter reclaim, and deadlock if it waits on a folio for 1186 * which it is needed to do the write (loop masks off 1187 * __GFP_IO|__GFP_FS for this reason); but more thought 1188 * would probably show more reasons. 1189 * 1190 * 3) Legacy memcg encounters a folio that already has the 1191 * reclaim flag set. memcg does not have any dirty folio 1192 * throttling so we could easily OOM just because too many 1193 * folios are in writeback and there is nothing else to 1194 * reclaim. Wait for the writeback to complete. 1195 * 1196 * In cases 1) and 2) we activate the folios to get them out of 1197 * the way while we continue scanning for clean folios on the 1198 * inactive list and refilling from the active list. The 1199 * observation here is that waiting for disk writes is more 1200 * expensive than potentially causing reloads down the line. 1201 * Since they're marked for immediate reclaim, they won't put 1202 * memory pressure on the cache working set any longer than it 1203 * takes to write them to disk. 1204 */ 1205 if (folio_test_writeback(folio)) { 1206 mapping = folio_mapping(folio); 1207 1208 /* Case 1 above */ 1209 if (current_is_kswapd() && 1210 folio_test_reclaim(folio) && 1211 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) { 1212 stat->nr_immediate += nr_pages; 1213 goto activate_locked; 1214 1215 /* Case 2 above */ 1216 } else if (writeback_throttling_sane(sc) || 1217 !folio_test_reclaim(folio) || 1218 !may_enter_fs(folio, sc->gfp_mask) || 1219 (mapping && 1220 mapping_writeback_may_deadlock_on_reclaim(mapping))) { 1221 /* 1222 * This is slightly racy - 1223 * folio_end_writeback() might have 1224 * just cleared the reclaim flag, then 1225 * setting the reclaim flag here ends up 1226 * interpreted as the readahead flag - but 1227 * that does not matter enough to care. 1228 * What we do want is for this folio to 1229 * have the reclaim flag set next time 1230 * memcg reclaim reaches the tests above, 1231 * so it will then wait for writeback to 1232 * avoid OOM; and it's also appropriate 1233 * in global reclaim. 1234 */ 1235 folio_set_reclaim(folio); 1236 stat->nr_writeback += nr_pages; 1237 goto activate_locked; 1238 1239 /* Case 3 above */ 1240 } else { 1241 folio_unlock(folio); 1242 folio_wait_writeback(folio); 1243 /* then go back and try same folio again */ 1244 list_add_tail(&folio->lru, folio_list); 1245 continue; 1246 } 1247 } 1248 1249 if (!ignore_references) 1250 references = folio_check_references(folio, sc); 1251 1252 switch (references) { 1253 case FOLIOREF_ACTIVATE: 1254 goto activate_locked; 1255 case FOLIOREF_KEEP: 1256 stat->nr_ref_keep += nr_pages; 1257 goto keep_locked; 1258 case FOLIOREF_RECLAIM: 1259 case FOLIOREF_RECLAIM_CLEAN: 1260 ; /* try to reclaim the folio below */ 1261 } 1262 1263 /* 1264 * Before reclaiming the folio, try to relocate 1265 * its contents to another node. 1266 */ 1267 if (do_demote_pass && 1268 (thp_migration_supported() || !folio_test_large(folio))) { 1269 list_add(&folio->lru, &demote_folios); 1270 folio_unlock(folio); 1271 continue; 1272 } 1273 1274 /* 1275 * Anonymous process memory has backing store? 1276 * Try to allocate it some swap space here. 1277 * Lazyfree folio could be freed directly 1278 */ 1279 if (folio_test_anon(folio) && folio_test_swapbacked(folio) && 1280 !folio_test_swapcache(folio)) { 1281 if (!(sc->gfp_mask & __GFP_IO)) 1282 goto keep_locked; 1283 if (folio_maybe_dma_pinned(folio)) 1284 goto keep_locked; 1285 if (folio_test_large(folio)) { 1286 /* cannot split folio, skip it */ 1287 if (folio_expected_ref_count(folio) != 1288 folio_ref_count(folio) - 1) 1289 goto activate_locked; 1290 /* 1291 * Split partially mapped folios right away. 1292 * We can free the unmapped pages without IO. 1293 */ 1294 if (data_race(!list_empty(&folio->_deferred_list) && 1295 folio_test_partially_mapped(folio)) && 1296 split_folio_to_list(folio, folio_list)) 1297 goto activate_locked; 1298 } 1299 if (folio_alloc_swap(folio)) { 1300 int __maybe_unused order = folio_order(folio); 1301 1302 if (!folio_test_large(folio)) 1303 goto activate_locked_split; 1304 /* Fallback to swap normal pages */ 1305 if (split_folio_to_list(folio, folio_list)) 1306 goto activate_locked; 1307 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 1308 if (nr_pages >= HPAGE_PMD_NR) { 1309 count_memcg_folio_events(folio, 1310 THP_SWPOUT_FALLBACK, 1); 1311 count_vm_event(THP_SWPOUT_FALLBACK); 1312 } 1313 #endif 1314 count_mthp_stat(order, MTHP_STAT_SWPOUT_FALLBACK); 1315 if (folio_alloc_swap(folio)) 1316 goto activate_locked_split; 1317 } 1318 /* 1319 * Normally the folio will be dirtied in unmap because 1320 * its pte should be dirty. A special case is MADV_FREE 1321 * page. The page's pte could have dirty bit cleared but 1322 * the folio's SwapBacked flag is still set because 1323 * clearing the dirty bit and SwapBacked flag has no 1324 * lock protected. For such folio, unmap will not set 1325 * dirty bit for it, so folio reclaim will not write the 1326 * folio out. This can cause data corruption when the 1327 * folio is swapped in later. Always setting the dirty 1328 * flag for the folio solves the problem. 1329 */ 1330 folio_mark_dirty(folio); 1331 } 1332 1333 /* 1334 * If the folio was split above, the tail pages will make 1335 * their own pass through this function and be accounted 1336 * then. 1337 */ 1338 if ((nr_pages > 1) && !folio_test_large(folio)) { 1339 sc->nr_scanned -= (nr_pages - 1); 1340 nr_pages = 1; 1341 } 1342 1343 /* 1344 * The folio is mapped into the page tables of one or more 1345 * processes. Try to unmap it here. 1346 */ 1347 if (folio_mapped(folio)) { 1348 enum ttu_flags flags = TTU_BATCH_FLUSH; 1349 bool was_swapbacked = folio_test_swapbacked(folio); 1350 1351 if (folio_test_pmd_mappable(folio)) 1352 flags |= TTU_SPLIT_HUGE_PMD; 1353 /* 1354 * Without TTU_SYNC, try_to_unmap will only begin to 1355 * hold PTL from the first present PTE within a large 1356 * folio. Some initial PTEs might be skipped due to 1357 * races with parallel PTE writes in which PTEs can be 1358 * cleared temporarily before being written new present 1359 * values. This will lead to a large folio is still 1360 * mapped while some subpages have been partially 1361 * unmapped after try_to_unmap; TTU_SYNC helps 1362 * try_to_unmap acquire PTL from the first PTE, 1363 * eliminating the influence of temporary PTE values. 1364 */ 1365 if (folio_test_large(folio)) 1366 flags |= TTU_SYNC; 1367 1368 try_to_unmap(folio, flags); 1369 if (folio_mapped(folio)) { 1370 stat->nr_unmap_fail += nr_pages; 1371 if (!was_swapbacked && 1372 folio_test_swapbacked(folio)) 1373 stat->nr_lazyfree_fail += nr_pages; 1374 goto activate_locked; 1375 } 1376 } 1377 1378 /* 1379 * Folio is unmapped now so it cannot be newly pinned anymore. 1380 * No point in trying to reclaim folio if it is pinned. 1381 * Furthermore we don't want to reclaim underlying fs metadata 1382 * if the folio is pinned and thus potentially modified by the 1383 * pinning process as that may upset the filesystem. 1384 */ 1385 if (folio_maybe_dma_pinned(folio)) 1386 goto activate_locked; 1387 1388 mapping = folio_mapping(folio); 1389 if (folio_test_dirty(folio)) { 1390 if (folio_is_file_lru(folio)) { 1391 /* 1392 * Immediately reclaim when written back. 1393 * Similar in principle to folio_deactivate() 1394 * except we already have the folio isolated 1395 * and know it's dirty 1396 */ 1397 node_stat_mod_folio(folio, NR_VMSCAN_IMMEDIATE, 1398 nr_pages); 1399 if (!folio_test_reclaim(folio)) 1400 folio_set_reclaim(folio); 1401 1402 goto activate_locked; 1403 } 1404 1405 if (references == FOLIOREF_RECLAIM_CLEAN) 1406 goto keep_locked; 1407 if (!may_enter_fs(folio, sc->gfp_mask)) 1408 goto keep_locked; 1409 if (!sc->may_writepage) 1410 goto keep_locked; 1411 1412 /* 1413 * Folio is dirty. Flush the TLB if a writable entry 1414 * potentially exists to avoid CPU writes after I/O 1415 * starts and then write it out here. 1416 */ 1417 try_to_unmap_flush_dirty(); 1418 switch (pageout(folio, mapping, &plug, folio_list)) { 1419 case PAGE_KEEP: 1420 goto keep_locked; 1421 case PAGE_ACTIVATE: 1422 /* 1423 * If shmem folio is split when writeback to swap, 1424 * the tail pages will make their own pass through 1425 * this function and be accounted then. 1426 */ 1427 if (nr_pages > 1 && !folio_test_large(folio)) { 1428 sc->nr_scanned -= (nr_pages - 1); 1429 nr_pages = 1; 1430 } 1431 goto activate_locked; 1432 case PAGE_SUCCESS: 1433 if (nr_pages > 1 && !folio_test_large(folio)) { 1434 sc->nr_scanned -= (nr_pages - 1); 1435 nr_pages = 1; 1436 } 1437 stat->nr_pageout += nr_pages; 1438 1439 if (folio_test_writeback(folio)) 1440 goto keep; 1441 if (folio_test_dirty(folio)) 1442 goto keep; 1443 1444 /* 1445 * A synchronous write - probably a ramdisk. Go 1446 * ahead and try to reclaim the folio. 1447 */ 1448 if (!folio_trylock(folio)) 1449 goto keep; 1450 if (folio_test_dirty(folio) || 1451 folio_test_writeback(folio)) 1452 goto keep_locked; 1453 mapping = folio_mapping(folio); 1454 fallthrough; 1455 case PAGE_CLEAN: 1456 ; /* try to free the folio below */ 1457 } 1458 } 1459 1460 /* 1461 * If the folio has buffers, try to free the buffer 1462 * mappings associated with this folio. If we succeed 1463 * we try to free the folio as well. 1464 * 1465 * We do this even if the folio is dirty. 1466 * filemap_release_folio() does not perform I/O, but it 1467 * is possible for a folio to have the dirty flag set, 1468 * but it is actually clean (all its buffers are clean). 1469 * This happens if the buffers were written out directly, 1470 * with submit_bh(). ext3 will do this, as well as 1471 * the blockdev mapping. filemap_release_folio() will 1472 * discover that cleanness and will drop the buffers 1473 * and mark the folio clean - it can be freed. 1474 * 1475 * Rarely, folios can have buffers and no ->mapping. 1476 * These are the folios which were not successfully 1477 * invalidated in truncate_cleanup_folio(). We try to 1478 * drop those buffers here and if that worked, and the 1479 * folio is no longer mapped into process address space 1480 * (refcount == 1) it can be freed. Otherwise, leave 1481 * the folio on the LRU so it is swappable. 1482 */ 1483 if (folio_needs_release(folio)) { 1484 if (!filemap_release_folio(folio, sc->gfp_mask)) 1485 goto activate_locked; 1486 if (!mapping && folio_ref_count(folio) == 1) { 1487 folio_unlock(folio); 1488 if (folio_put_testzero(folio)) 1489 goto free_it; 1490 else { 1491 /* 1492 * rare race with speculative reference. 1493 * the speculative reference will free 1494 * this folio shortly, so we may 1495 * increment nr_reclaimed here (and 1496 * leave it off the LRU). 1497 */ 1498 nr_reclaimed += nr_pages; 1499 continue; 1500 } 1501 } 1502 } 1503 1504 if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) { 1505 /* follow __remove_mapping for reference */ 1506 if (!folio_ref_freeze(folio, 1)) 1507 goto keep_locked; 1508 /* 1509 * The folio has only one reference left, which is 1510 * from the isolation. After the caller puts the 1511 * folio back on the lru and drops the reference, the 1512 * folio will be freed anyway. It doesn't matter 1513 * which lru it goes on. So we don't bother checking 1514 * the dirty flag here. 1515 */ 1516 count_vm_events(PGLAZYFREED, nr_pages); 1517 count_memcg_folio_events(folio, PGLAZYFREED, nr_pages); 1518 } else if (!mapping || !__remove_mapping(mapping, folio, true, 1519 sc->target_mem_cgroup)) 1520 goto keep_locked; 1521 1522 folio_unlock(folio); 1523 free_it: 1524 /* 1525 * Folio may get swapped out as a whole, need to account 1526 * all pages in it. 1527 */ 1528 nr_reclaimed += nr_pages; 1529 1530 folio_unqueue_deferred_split(folio); 1531 if (folio_batch_add(&free_folios, folio) == 0) { 1532 mem_cgroup_uncharge_folios(&free_folios); 1533 try_to_unmap_flush(); 1534 free_unref_folios(&free_folios); 1535 } 1536 continue; 1537 1538 activate_locked_split: 1539 /* 1540 * The tail pages that are failed to add into swap cache 1541 * reach here. Fixup nr_scanned and nr_pages. 1542 */ 1543 if (nr_pages > 1) { 1544 sc->nr_scanned -= (nr_pages - 1); 1545 nr_pages = 1; 1546 } 1547 activate_locked: 1548 /* Not a candidate for swapping, so reclaim swap space. */ 1549 if (folio_test_swapcache(folio) && 1550 (mem_cgroup_swap_full(folio) || folio_test_mlocked(folio))) 1551 folio_free_swap(folio); 1552 VM_BUG_ON_FOLIO(folio_test_active(folio), folio); 1553 if (!folio_test_mlocked(folio)) { 1554 int type = folio_is_file_lru(folio); 1555 folio_set_active(folio); 1556 stat->nr_activate[type] += nr_pages; 1557 count_memcg_folio_events(folio, PGACTIVATE, nr_pages); 1558 } 1559 keep_locked: 1560 folio_unlock(folio); 1561 keep: 1562 list_add(&folio->lru, &ret_folios); 1563 VM_BUG_ON_FOLIO(folio_test_lru(folio) || 1564 folio_test_unevictable(folio), folio); 1565 } 1566 /* 'folio_list' is always empty here */ 1567 1568 /* Migrate folios selected for demotion */ 1569 nr_demoted = demote_folio_list(&demote_folios, pgdat); 1570 nr_reclaimed += nr_demoted; 1571 stat->nr_demoted += nr_demoted; 1572 /* Folios that could not be demoted are still in @demote_folios */ 1573 if (!list_empty(&demote_folios)) { 1574 /* Folios which weren't demoted go back on @folio_list */ 1575 list_splice_init(&demote_folios, folio_list); 1576 1577 /* 1578 * goto retry to reclaim the undemoted folios in folio_list if 1579 * desired. 1580 * 1581 * Reclaiming directly from top tier nodes is not often desired 1582 * due to it breaking the LRU ordering: in general memory 1583 * should be reclaimed from lower tier nodes and demoted from 1584 * top tier nodes. 1585 * 1586 * However, disabling reclaim from top tier nodes entirely 1587 * would cause ooms in edge scenarios where lower tier memory 1588 * is unreclaimable for whatever reason, eg memory being 1589 * mlocked or too hot to reclaim. We can disable reclaim 1590 * from top tier nodes in proactive reclaim though as that is 1591 * not real memory pressure. 1592 */ 1593 if (!sc->proactive) { 1594 do_demote_pass = false; 1595 goto retry; 1596 } 1597 } 1598 1599 pgactivate = stat->nr_activate[0] + stat->nr_activate[1]; 1600 1601 mem_cgroup_uncharge_folios(&free_folios); 1602 try_to_unmap_flush(); 1603 free_unref_folios(&free_folios); 1604 1605 list_splice(&ret_folios, folio_list); 1606 count_vm_events(PGACTIVATE, pgactivate); 1607 1608 if (plug) 1609 swap_write_unplug(plug); 1610 return nr_reclaimed; 1611 } 1612 1613 unsigned int reclaim_clean_pages_from_list(struct zone *zone, 1614 struct list_head *folio_list) 1615 { 1616 struct scan_control sc = { 1617 .gfp_mask = GFP_KERNEL, 1618 .may_unmap = 1, 1619 }; 1620 struct reclaim_stat stat; 1621 unsigned int nr_reclaimed; 1622 struct folio *folio, *next; 1623 LIST_HEAD(clean_folios); 1624 unsigned int noreclaim_flag; 1625 1626 list_for_each_entry_safe(folio, next, folio_list, lru) { 1627 /* TODO: these pages should not even appear in this list. */ 1628 if (page_has_movable_ops(&folio->page)) 1629 continue; 1630 if (!folio_test_hugetlb(folio) && folio_is_file_lru(folio) && 1631 !folio_test_dirty(folio) && !folio_test_unevictable(folio)) { 1632 folio_clear_active(folio); 1633 list_move(&folio->lru, &clean_folios); 1634 } 1635 } 1636 1637 /* 1638 * We should be safe here since we are only dealing with file pages and 1639 * we are not kswapd and therefore cannot write dirty file pages. But 1640 * call memalloc_noreclaim_save() anyway, just in case these conditions 1641 * change in the future. 1642 */ 1643 noreclaim_flag = memalloc_noreclaim_save(); 1644 nr_reclaimed = shrink_folio_list(&clean_folios, zone->zone_pgdat, &sc, 1645 &stat, true, NULL); 1646 memalloc_noreclaim_restore(noreclaim_flag); 1647 1648 list_splice(&clean_folios, folio_list); 1649 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, 1650 -(long)nr_reclaimed); 1651 /* 1652 * Since lazyfree pages are isolated from file LRU from the beginning, 1653 * they will rotate back to anonymous LRU in the end if it failed to 1654 * discard so isolated count will be mismatched. 1655 * Compensate the isolated count for both LRU lists. 1656 */ 1657 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON, 1658 stat.nr_lazyfree_fail); 1659 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, 1660 -(long)stat.nr_lazyfree_fail); 1661 return nr_reclaimed; 1662 } 1663 1664 /* 1665 * Update LRU sizes after isolating pages. The LRU size updates must 1666 * be complete before mem_cgroup_update_lru_size due to a sanity check. 1667 */ 1668 static __always_inline void update_lru_sizes(struct lruvec *lruvec, 1669 enum lru_list lru, unsigned long *nr_zone_taken) 1670 { 1671 int zid; 1672 1673 for (zid = 0; zid < MAX_NR_ZONES; zid++) { 1674 if (!nr_zone_taken[zid]) 1675 continue; 1676 1677 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]); 1678 } 1679 1680 } 1681 1682 /* 1683 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times. 1684 * 1685 * lruvec->lru_lock is heavily contended. Some of the functions that 1686 * shrink the lists perform better by taking out a batch of pages 1687 * and working on them outside the LRU lock. 1688 * 1689 * For pagecache intensive workloads, this function is the hottest 1690 * spot in the kernel (apart from copy_*_user functions). 1691 * 1692 * Lru_lock must be held before calling this function. 1693 * 1694 * @nr_to_scan: The number of eligible pages to look through on the list. 1695 * @lruvec: The LRU vector to pull pages from. 1696 * @dst: The temp list to put pages on to. 1697 * @nr_scanned: The number of pages that were scanned. 1698 * @sc: The scan_control struct for this reclaim session 1699 * @lru: LRU list id for isolating 1700 * 1701 * returns how many pages were moved onto *@dst. 1702 */ 1703 static unsigned long isolate_lru_folios(unsigned long nr_to_scan, 1704 struct lruvec *lruvec, struct list_head *dst, 1705 unsigned long *nr_scanned, struct scan_control *sc, 1706 enum lru_list lru) 1707 { 1708 struct list_head *src = &lruvec->lists[lru]; 1709 unsigned long nr_taken = 0; 1710 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 }; 1711 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, }; 1712 unsigned long skipped = 0, total_scan = 0, scan = 0; 1713 unsigned long nr_pages; 1714 unsigned long max_nr_skipped = 0; 1715 LIST_HEAD(folios_skipped); 1716 1717 while (scan < nr_to_scan && !list_empty(src)) { 1718 struct list_head *move_to = src; 1719 struct folio *folio; 1720 1721 folio = lru_to_folio(src); 1722 prefetchw_prev_lru_folio(folio, src, flags); 1723 1724 nr_pages = folio_nr_pages(folio); 1725 total_scan += nr_pages; 1726 1727 /* Using max_nr_skipped to prevent hard LOCKUP*/ 1728 if (max_nr_skipped < SWAP_CLUSTER_MAX_SKIPPED && 1729 (folio_zonenum(folio) > sc->reclaim_idx)) { 1730 nr_skipped[folio_zonenum(folio)] += nr_pages; 1731 move_to = &folios_skipped; 1732 max_nr_skipped++; 1733 goto move; 1734 } 1735 1736 /* 1737 * Do not count skipped folios because that makes the function 1738 * return with no isolated folios if the LRU mostly contains 1739 * ineligible folios. This causes the VM to not reclaim any 1740 * folios, triggering a premature OOM. 1741 * Account all pages in a folio. 1742 */ 1743 scan += nr_pages; 1744 1745 if (!folio_test_lru(folio)) 1746 goto move; 1747 if (!sc->may_unmap && folio_mapped(folio)) 1748 goto move; 1749 1750 /* 1751 * Be careful not to clear the lru flag until after we're 1752 * sure the folio is not being freed elsewhere -- the 1753 * folio release code relies on it. 1754 */ 1755 if (unlikely(!folio_try_get(folio))) 1756 goto move; 1757 1758 if (!folio_test_clear_lru(folio)) { 1759 /* Another thread is already isolating this folio */ 1760 folio_put(folio); 1761 goto move; 1762 } 1763 1764 nr_taken += nr_pages; 1765 nr_zone_taken[folio_zonenum(folio)] += nr_pages; 1766 move_to = dst; 1767 move: 1768 list_move(&folio->lru, move_to); 1769 } 1770 1771 /* 1772 * Splice any skipped folios to the start of the LRU list. Note that 1773 * this disrupts the LRU order when reclaiming for lower zones but 1774 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX 1775 * scanning would soon rescan the same folios to skip and waste lots 1776 * of cpu cycles. 1777 */ 1778 if (!list_empty(&folios_skipped)) { 1779 int zid; 1780 1781 list_splice(&folios_skipped, src); 1782 for (zid = 0; zid < MAX_NR_ZONES; zid++) { 1783 if (!nr_skipped[zid]) 1784 continue; 1785 1786 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]); 1787 skipped += nr_skipped[zid]; 1788 } 1789 } 1790 *nr_scanned = total_scan; 1791 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan, 1792 total_scan, skipped, nr_taken, lru); 1793 update_lru_sizes(lruvec, lru, nr_zone_taken); 1794 return nr_taken; 1795 } 1796 1797 /** 1798 * folio_isolate_lru() - Try to isolate a folio from its LRU list. 1799 * @folio: Folio to isolate from its LRU list. 1800 * 1801 * Isolate a @folio from an LRU list and adjust the vmstat statistic 1802 * corresponding to whatever LRU list the folio was on. 1803 * 1804 * The folio will have its LRU flag cleared. If it was found on the 1805 * active list, it will have the Active flag set. If it was found on the 1806 * unevictable list, it will have the Unevictable flag set. These flags 1807 * may need to be cleared by the caller before letting the page go. 1808 * 1809 * Context: 1810 * 1811 * (1) Must be called with an elevated refcount on the folio. This is a 1812 * fundamental difference from isolate_lru_folios() (which is called 1813 * without a stable reference). 1814 * (2) The lru_lock must not be held. 1815 * (3) Interrupts must be enabled. 1816 * 1817 * Return: true if the folio was removed from an LRU list. 1818 * false if the folio was not on an LRU list. 1819 */ 1820 bool folio_isolate_lru(struct folio *folio) 1821 { 1822 bool ret = false; 1823 1824 VM_BUG_ON_FOLIO(!folio_ref_count(folio), folio); 1825 1826 if (folio_test_clear_lru(folio)) { 1827 struct lruvec *lruvec; 1828 1829 folio_get(folio); 1830 lruvec = folio_lruvec_lock_irq(folio); 1831 lruvec_del_folio(lruvec, folio); 1832 unlock_page_lruvec_irq(lruvec); 1833 ret = true; 1834 } 1835 1836 return ret; 1837 } 1838 1839 /* 1840 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and 1841 * then get rescheduled. When there are massive number of tasks doing page 1842 * allocation, such sleeping direct reclaimers may keep piling up on each CPU, 1843 * the LRU list will go small and be scanned faster than necessary, leading to 1844 * unnecessary swapping, thrashing and OOM. 1845 */ 1846 static bool too_many_isolated(struct pglist_data *pgdat, int file, 1847 struct scan_control *sc) 1848 { 1849 unsigned long inactive, isolated; 1850 bool too_many; 1851 1852 if (current_is_kswapd()) 1853 return false; 1854 1855 if (!writeback_throttling_sane(sc)) 1856 return false; 1857 1858 if (file) { 1859 inactive = node_page_state(pgdat, NR_INACTIVE_FILE); 1860 isolated = node_page_state(pgdat, NR_ISOLATED_FILE); 1861 } else { 1862 inactive = node_page_state(pgdat, NR_INACTIVE_ANON); 1863 isolated = node_page_state(pgdat, NR_ISOLATED_ANON); 1864 } 1865 1866 /* 1867 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they 1868 * won't get blocked by normal direct-reclaimers, forming a circular 1869 * deadlock. 1870 */ 1871 if (gfp_has_io_fs(sc->gfp_mask)) 1872 inactive >>= 3; 1873 1874 too_many = isolated > inactive; 1875 1876 /* Wake up tasks throttled due to too_many_isolated. */ 1877 if (!too_many) 1878 wake_throttle_isolated(pgdat); 1879 1880 return too_many; 1881 } 1882 1883 /* 1884 * move_folios_to_lru() moves folios from private @list to appropriate LRU list. 1885 * 1886 * Returns the number of pages moved to the given lruvec. 1887 */ 1888 static unsigned int move_folios_to_lru(struct lruvec *lruvec, 1889 struct list_head *list) 1890 { 1891 int nr_pages, nr_moved = 0; 1892 struct folio_batch free_folios; 1893 1894 folio_batch_init(&free_folios); 1895 while (!list_empty(list)) { 1896 struct folio *folio = lru_to_folio(list); 1897 1898 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio); 1899 list_del(&folio->lru); 1900 if (unlikely(!folio_evictable(folio))) { 1901 spin_unlock_irq(&lruvec->lru_lock); 1902 folio_putback_lru(folio); 1903 spin_lock_irq(&lruvec->lru_lock); 1904 continue; 1905 } 1906 1907 /* 1908 * The folio_set_lru needs to be kept here for list integrity. 1909 * Otherwise: 1910 * #0 move_folios_to_lru #1 release_pages 1911 * if (!folio_put_testzero()) 1912 * if (folio_put_testzero()) 1913 * !lru //skip lru_lock 1914 * folio_set_lru() 1915 * list_add(&folio->lru,) 1916 * list_add(&folio->lru,) 1917 */ 1918 folio_set_lru(folio); 1919 1920 if (unlikely(folio_put_testzero(folio))) { 1921 __folio_clear_lru_flags(folio); 1922 1923 folio_unqueue_deferred_split(folio); 1924 if (folio_batch_add(&free_folios, folio) == 0) { 1925 spin_unlock_irq(&lruvec->lru_lock); 1926 mem_cgroup_uncharge_folios(&free_folios); 1927 free_unref_folios(&free_folios); 1928 spin_lock_irq(&lruvec->lru_lock); 1929 } 1930 1931 continue; 1932 } 1933 1934 /* 1935 * All pages were isolated from the same lruvec (and isolation 1936 * inhibits memcg migration). 1937 */ 1938 VM_BUG_ON_FOLIO(!folio_matches_lruvec(folio, lruvec), folio); 1939 lruvec_add_folio(lruvec, folio); 1940 nr_pages = folio_nr_pages(folio); 1941 nr_moved += nr_pages; 1942 if (folio_test_active(folio)) 1943 workingset_age_nonresident(lruvec, nr_pages); 1944 } 1945 1946 if (free_folios.nr) { 1947 spin_unlock_irq(&lruvec->lru_lock); 1948 mem_cgroup_uncharge_folios(&free_folios); 1949 free_unref_folios(&free_folios); 1950 spin_lock_irq(&lruvec->lru_lock); 1951 } 1952 1953 return nr_moved; 1954 } 1955 1956 /* 1957 * If a kernel thread (such as nfsd for loop-back mounts) services a backing 1958 * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case 1959 * we should not throttle. Otherwise it is safe to do so. 1960 */ 1961 static int current_may_throttle(void) 1962 { 1963 return !(current->flags & PF_LOCAL_THROTTLE); 1964 } 1965 1966 /* 1967 * shrink_inactive_list() is a helper for shrink_node(). It returns the number 1968 * of reclaimed pages 1969 */ 1970 static unsigned long shrink_inactive_list(unsigned long nr_to_scan, 1971 struct lruvec *lruvec, struct scan_control *sc, 1972 enum lru_list lru) 1973 { 1974 LIST_HEAD(folio_list); 1975 unsigned long nr_scanned; 1976 unsigned int nr_reclaimed = 0; 1977 unsigned long nr_taken; 1978 struct reclaim_stat stat; 1979 bool file = is_file_lru(lru); 1980 enum vm_event_item item; 1981 struct pglist_data *pgdat = lruvec_pgdat(lruvec); 1982 bool stalled = false; 1983 1984 while (unlikely(too_many_isolated(pgdat, file, sc))) { 1985 if (stalled) 1986 return 0; 1987 1988 /* wait a bit for the reclaimer. */ 1989 stalled = true; 1990 reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED); 1991 1992 /* We are about to die and free our memory. Return now. */ 1993 if (fatal_signal_pending(current)) 1994 return SWAP_CLUSTER_MAX; 1995 } 1996 1997 lru_add_drain(); 1998 1999 spin_lock_irq(&lruvec->lru_lock); 2000 2001 nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &folio_list, 2002 &nr_scanned, sc, lru); 2003 2004 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken); 2005 item = PGSCAN_KSWAPD + reclaimer_offset(sc); 2006 if (!cgroup_reclaim(sc)) 2007 __count_vm_events(item, nr_scanned); 2008 count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned); 2009 __count_vm_events(PGSCAN_ANON + file, nr_scanned); 2010 2011 spin_unlock_irq(&lruvec->lru_lock); 2012 2013 if (nr_taken == 0) 2014 return 0; 2015 2016 nr_reclaimed = shrink_folio_list(&folio_list, pgdat, sc, &stat, false, 2017 lruvec_memcg(lruvec)); 2018 2019 spin_lock_irq(&lruvec->lru_lock); 2020 move_folios_to_lru(lruvec, &folio_list); 2021 2022 mod_lruvec_state(lruvec, PGDEMOTE_KSWAPD + reclaimer_offset(sc), 2023 stat.nr_demoted); 2024 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken); 2025 item = PGSTEAL_KSWAPD + reclaimer_offset(sc); 2026 if (!cgroup_reclaim(sc)) 2027 __count_vm_events(item, nr_reclaimed); 2028 count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed); 2029 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed); 2030 2031 lru_note_cost_unlock_irq(lruvec, file, stat.nr_pageout, 2032 nr_scanned - nr_reclaimed); 2033 2034 /* 2035 * If dirty folios are scanned that are not queued for IO, it 2036 * implies that flushers are not doing their job. This can 2037 * happen when memory pressure pushes dirty folios to the end of 2038 * the LRU before the dirty limits are breached and the dirty 2039 * data has expired. It can also happen when the proportion of 2040 * dirty folios grows not through writes but through memory 2041 * pressure reclaiming all the clean cache. And in some cases, 2042 * the flushers simply cannot keep up with the allocation 2043 * rate. Nudge the flusher threads in case they are asleep. 2044 */ 2045 if (stat.nr_unqueued_dirty == nr_taken) { 2046 wakeup_flusher_threads(WB_REASON_VMSCAN); 2047 /* 2048 * For cgroupv1 dirty throttling is achieved by waking up 2049 * the kernel flusher here and later waiting on folios 2050 * which are in writeback to finish (see shrink_folio_list()). 2051 * 2052 * Flusher may not be able to issue writeback quickly 2053 * enough for cgroupv1 writeback throttling to work 2054 * on a large system. 2055 */ 2056 if (!writeback_throttling_sane(sc)) 2057 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK); 2058 } 2059 2060 sc->nr.dirty += stat.nr_dirty; 2061 sc->nr.congested += stat.nr_congested; 2062 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty; 2063 sc->nr.writeback += stat.nr_writeback; 2064 sc->nr.immediate += stat.nr_immediate; 2065 sc->nr.taken += nr_taken; 2066 if (file) 2067 sc->nr.file_taken += nr_taken; 2068 2069 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id, 2070 nr_scanned, nr_reclaimed, &stat, sc->priority, file); 2071 return nr_reclaimed; 2072 } 2073 2074 /* 2075 * shrink_active_list() moves folios from the active LRU to the inactive LRU. 2076 * 2077 * We move them the other way if the folio is referenced by one or more 2078 * processes. 2079 * 2080 * If the folios are mostly unmapped, the processing is fast and it is 2081 * appropriate to hold lru_lock across the whole operation. But if 2082 * the folios are mapped, the processing is slow (folio_referenced()), so 2083 * we should drop lru_lock around each folio. It's impossible to balance 2084 * this, so instead we remove the folios from the LRU while processing them. 2085 * It is safe to rely on the active flag against the non-LRU folios in here 2086 * because nobody will play with that bit on a non-LRU folio. 2087 * 2088 * The downside is that we have to touch folio->_refcount against each folio. 2089 * But we had to alter folio->flags anyway. 2090 */ 2091 static void shrink_active_list(unsigned long nr_to_scan, 2092 struct lruvec *lruvec, 2093 struct scan_control *sc, 2094 enum lru_list lru) 2095 { 2096 unsigned long nr_taken; 2097 unsigned long nr_scanned; 2098 vm_flags_t vm_flags; 2099 LIST_HEAD(l_hold); /* The folios which were snipped off */ 2100 LIST_HEAD(l_active); 2101 LIST_HEAD(l_inactive); 2102 unsigned nr_deactivate, nr_activate; 2103 unsigned nr_rotated = 0; 2104 bool file = is_file_lru(lru); 2105 struct pglist_data *pgdat = lruvec_pgdat(lruvec); 2106 2107 lru_add_drain(); 2108 2109 spin_lock_irq(&lruvec->lru_lock); 2110 2111 nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &l_hold, 2112 &nr_scanned, sc, lru); 2113 2114 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken); 2115 2116 if (!cgroup_reclaim(sc)) 2117 __count_vm_events(PGREFILL, nr_scanned); 2118 count_memcg_events(lruvec_memcg(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(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN); 3818 } 3819 3820 current->reclaim_state->mm_walk = walk; 3821 3822 return walk; 3823 } 3824 3825 static void clear_mm_walk(void) 3826 { 3827 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk; 3828 3829 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages))); 3830 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats))); 3831 3832 current->reclaim_state->mm_walk = NULL; 3833 3834 if (!current_is_kswapd()) 3835 kfree(walk); 3836 } 3837 3838 static bool inc_min_seq(struct lruvec *lruvec, int type, int swappiness) 3839 { 3840 int zone; 3841 int remaining = MAX_LRU_BATCH; 3842 struct lru_gen_folio *lrugen = &lruvec->lrugen; 3843 int hist = lru_hist_from_seq(lrugen->min_seq[type]); 3844 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]); 3845 3846 /* For file type, skip the check if swappiness is anon only */ 3847 if (type && (swappiness == SWAPPINESS_ANON_ONLY)) 3848 goto done; 3849 3850 /* For anon type, skip the check if swappiness is zero (file only) */ 3851 if (!type && !swappiness) 3852 goto done; 3853 3854 /* prevent cold/hot inversion if the type is evictable */ 3855 for (zone = 0; zone < MAX_NR_ZONES; zone++) { 3856 struct list_head *head = &lrugen->folios[old_gen][type][zone]; 3857 3858 while (!list_empty(head)) { 3859 struct folio *folio = lru_to_folio(head); 3860 int refs = folio_lru_refs(folio); 3861 bool workingset = folio_test_workingset(folio); 3862 3863 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio); 3864 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio); 3865 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio); 3866 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio); 3867 3868 new_gen = folio_inc_gen(lruvec, folio, false); 3869 list_move_tail(&folio->lru, &lrugen->folios[new_gen][type][zone]); 3870 3871 /* don't count the workingset being lazily promoted */ 3872 if (refs + workingset != BIT(LRU_REFS_WIDTH) + 1) { 3873 int tier = lru_tier_from_refs(refs, workingset); 3874 int delta = folio_nr_pages(folio); 3875 3876 WRITE_ONCE(lrugen->protected[hist][type][tier], 3877 lrugen->protected[hist][type][tier] + delta); 3878 } 3879 3880 if (!--remaining) 3881 return false; 3882 } 3883 } 3884 done: 3885 reset_ctrl_pos(lruvec, type, true); 3886 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1); 3887 3888 return true; 3889 } 3890 3891 static bool try_to_inc_min_seq(struct lruvec *lruvec, int swappiness) 3892 { 3893 int gen, type, zone; 3894 bool success = false; 3895 bool seq_inc_flag = false; 3896 struct lru_gen_folio *lrugen = &lruvec->lrugen; 3897 DEFINE_MIN_SEQ(lruvec); 3898 3899 VM_WARN_ON_ONCE(!seq_is_valid(lruvec)); 3900 3901 /* find the oldest populated generation */ 3902 for_each_evictable_type(type, swappiness) { 3903 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) { 3904 gen = lru_gen_from_seq(min_seq[type]); 3905 3906 for (zone = 0; zone < MAX_NR_ZONES; zone++) { 3907 if (!list_empty(&lrugen->folios[gen][type][zone])) 3908 goto next; 3909 } 3910 3911 min_seq[type]++; 3912 seq_inc_flag = true; 3913 } 3914 next: 3915 ; 3916 } 3917 3918 /* 3919 * If min_seq[type] of both anonymous and file is not increased, 3920 * we can directly return false to avoid unnecessary checking 3921 * overhead later. 3922 */ 3923 if (!seq_inc_flag) 3924 return success; 3925 3926 /* see the comment on lru_gen_folio */ 3927 if (swappiness && swappiness <= MAX_SWAPPINESS) { 3928 unsigned long seq = lrugen->max_seq - MIN_NR_GENS; 3929 3930 if (min_seq[LRU_GEN_ANON] > seq && min_seq[LRU_GEN_FILE] < seq) 3931 min_seq[LRU_GEN_ANON] = seq; 3932 else if (min_seq[LRU_GEN_FILE] > seq && min_seq[LRU_GEN_ANON] < seq) 3933 min_seq[LRU_GEN_FILE] = seq; 3934 } 3935 3936 for_each_evictable_type(type, swappiness) { 3937 if (min_seq[type] <= lrugen->min_seq[type]) 3938 continue; 3939 3940 reset_ctrl_pos(lruvec, type, true); 3941 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]); 3942 success = true; 3943 } 3944 3945 return success; 3946 } 3947 3948 static bool inc_max_seq(struct lruvec *lruvec, unsigned long seq, int swappiness) 3949 { 3950 bool success; 3951 int prev, next; 3952 int type, zone; 3953 struct lru_gen_folio *lrugen = &lruvec->lrugen; 3954 restart: 3955 if (seq < READ_ONCE(lrugen->max_seq)) 3956 return false; 3957 3958 spin_lock_irq(&lruvec->lru_lock); 3959 3960 VM_WARN_ON_ONCE(!seq_is_valid(lruvec)); 3961 3962 success = seq == lrugen->max_seq; 3963 if (!success) 3964 goto unlock; 3965 3966 for (type = 0; type < ANON_AND_FILE; type++) { 3967 if (get_nr_gens(lruvec, type) != MAX_NR_GENS) 3968 continue; 3969 3970 if (inc_min_seq(lruvec, type, swappiness)) 3971 continue; 3972 3973 spin_unlock_irq(&lruvec->lru_lock); 3974 cond_resched(); 3975 goto restart; 3976 } 3977 3978 /* 3979 * Update the active/inactive LRU sizes for compatibility. Both sides of 3980 * the current max_seq need to be covered, since max_seq+1 can overlap 3981 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do 3982 * overlap, cold/hot inversion happens. 3983 */ 3984 prev = lru_gen_from_seq(lrugen->max_seq - 1); 3985 next = lru_gen_from_seq(lrugen->max_seq + 1); 3986 3987 for (type = 0; type < ANON_AND_FILE; type++) { 3988 for (zone = 0; zone < MAX_NR_ZONES; zone++) { 3989 enum lru_list lru = type * LRU_INACTIVE_FILE; 3990 long delta = lrugen->nr_pages[prev][type][zone] - 3991 lrugen->nr_pages[next][type][zone]; 3992 3993 if (!delta) 3994 continue; 3995 3996 __update_lru_size(lruvec, lru, zone, delta); 3997 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta); 3998 } 3999 } 4000 4001 for (type = 0; type < ANON_AND_FILE; type++) 4002 reset_ctrl_pos(lruvec, type, false); 4003 4004 WRITE_ONCE(lrugen->timestamps[next], jiffies); 4005 /* make sure preceding modifications appear */ 4006 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1); 4007 unlock: 4008 spin_unlock_irq(&lruvec->lru_lock); 4009 4010 return success; 4011 } 4012 4013 static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long seq, 4014 int swappiness, bool force_scan) 4015 { 4016 bool success; 4017 struct lru_gen_mm_walk *walk; 4018 struct mm_struct *mm = NULL; 4019 struct lru_gen_folio *lrugen = &lruvec->lrugen; 4020 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec); 4021 4022 VM_WARN_ON_ONCE(seq > READ_ONCE(lrugen->max_seq)); 4023 4024 if (!mm_state) 4025 return inc_max_seq(lruvec, seq, swappiness); 4026 4027 /* see the comment in iterate_mm_list() */ 4028 if (seq <= READ_ONCE(mm_state->seq)) 4029 return false; 4030 4031 /* 4032 * If the hardware doesn't automatically set the accessed bit, fallback 4033 * to lru_gen_look_around(), which only clears the accessed bit in a 4034 * handful of PTEs. Spreading the work out over a period of time usually 4035 * is less efficient, but it avoids bursty page faults. 4036 */ 4037 if (!should_walk_mmu()) { 4038 success = iterate_mm_list_nowalk(lruvec, seq); 4039 goto done; 4040 } 4041 4042 walk = set_mm_walk(NULL, true); 4043 if (!walk) { 4044 success = iterate_mm_list_nowalk(lruvec, seq); 4045 goto done; 4046 } 4047 4048 walk->lruvec = lruvec; 4049 walk->seq = seq; 4050 walk->swappiness = swappiness; 4051 walk->force_scan = force_scan; 4052 4053 do { 4054 success = iterate_mm_list(walk, &mm); 4055 if (mm) 4056 walk_mm(mm, walk); 4057 } while (mm); 4058 done: 4059 if (success) { 4060 success = inc_max_seq(lruvec, seq, swappiness); 4061 WARN_ON_ONCE(!success); 4062 } 4063 4064 return success; 4065 } 4066 4067 /****************************************************************************** 4068 * working set protection 4069 ******************************************************************************/ 4070 4071 static void set_initial_priority(struct pglist_data *pgdat, struct scan_control *sc) 4072 { 4073 int priority; 4074 unsigned long reclaimable; 4075 4076 if (sc->priority != DEF_PRIORITY || sc->nr_to_reclaim < MIN_LRU_BATCH) 4077 return; 4078 /* 4079 * Determine the initial priority based on 4080 * (total >> priority) * reclaimed_to_scanned_ratio = nr_to_reclaim, 4081 * where reclaimed_to_scanned_ratio = inactive / total. 4082 */ 4083 reclaimable = node_page_state(pgdat, NR_INACTIVE_FILE); 4084 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc)) 4085 reclaimable += node_page_state(pgdat, NR_INACTIVE_ANON); 4086 4087 /* round down reclaimable and round up sc->nr_to_reclaim */ 4088 priority = fls_long(reclaimable) - 1 - fls_long(sc->nr_to_reclaim - 1); 4089 4090 /* 4091 * The estimation is based on LRU pages only, so cap it to prevent 4092 * overshoots of shrinker objects by large margins. 4093 */ 4094 sc->priority = clamp(priority, DEF_PRIORITY / 2, DEF_PRIORITY); 4095 } 4096 4097 static bool lruvec_is_sizable(struct lruvec *lruvec, struct scan_control *sc) 4098 { 4099 int gen, type, zone; 4100 unsigned long total = 0; 4101 int swappiness = get_swappiness(lruvec, sc); 4102 struct lru_gen_folio *lrugen = &lruvec->lrugen; 4103 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 4104 DEFINE_MAX_SEQ(lruvec); 4105 DEFINE_MIN_SEQ(lruvec); 4106 4107 for_each_evictable_type(type, swappiness) { 4108 unsigned long seq; 4109 4110 for (seq = min_seq[type]; seq <= max_seq; seq++) { 4111 gen = lru_gen_from_seq(seq); 4112 4113 for (zone = 0; zone < MAX_NR_ZONES; zone++) 4114 total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L); 4115 } 4116 } 4117 4118 /* whether the size is big enough to be helpful */ 4119 return mem_cgroup_online(memcg) ? (total >> sc->priority) : total; 4120 } 4121 4122 static bool lruvec_is_reclaimable(struct lruvec *lruvec, struct scan_control *sc, 4123 unsigned long min_ttl) 4124 { 4125 int gen; 4126 unsigned long birth; 4127 int swappiness = get_swappiness(lruvec, sc); 4128 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 4129 DEFINE_MIN_SEQ(lruvec); 4130 4131 if (mem_cgroup_below_min(NULL, memcg)) 4132 return false; 4133 4134 if (!lruvec_is_sizable(lruvec, sc)) 4135 return false; 4136 4137 gen = lru_gen_from_seq(evictable_min_seq(min_seq, swappiness)); 4138 birth = READ_ONCE(lruvec->lrugen.timestamps[gen]); 4139 4140 return time_is_before_jiffies(birth + min_ttl); 4141 } 4142 4143 /* to protect the working set of the last N jiffies */ 4144 static unsigned long lru_gen_min_ttl __read_mostly; 4145 4146 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc) 4147 { 4148 struct mem_cgroup *memcg; 4149 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl); 4150 bool reclaimable = !min_ttl; 4151 4152 VM_WARN_ON_ONCE(!current_is_kswapd()); 4153 4154 set_initial_priority(pgdat, sc); 4155 4156 memcg = mem_cgroup_iter(NULL, NULL, NULL); 4157 do { 4158 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat); 4159 4160 mem_cgroup_calculate_protection(NULL, memcg); 4161 4162 if (!reclaimable) 4163 reclaimable = lruvec_is_reclaimable(lruvec, sc, min_ttl); 4164 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL))); 4165 4166 /* 4167 * The main goal is to OOM kill if every generation from all memcgs is 4168 * younger than min_ttl. However, another possibility is all memcgs are 4169 * either too small or below min. 4170 */ 4171 if (!reclaimable && mutex_trylock(&oom_lock)) { 4172 struct oom_control oc = { 4173 .gfp_mask = sc->gfp_mask, 4174 }; 4175 4176 out_of_memory(&oc); 4177 4178 mutex_unlock(&oom_lock); 4179 } 4180 } 4181 4182 /****************************************************************************** 4183 * rmap/PT walk feedback 4184 ******************************************************************************/ 4185 4186 /* 4187 * This function exploits spatial locality when shrink_folio_list() walks the 4188 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If 4189 * the scan was done cacheline efficiently, it adds the PMD entry pointing to 4190 * the PTE table to the Bloom filter. This forms a feedback loop between the 4191 * eviction and the aging. 4192 */ 4193 bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw) 4194 { 4195 int i; 4196 bool dirty; 4197 unsigned long start; 4198 unsigned long end; 4199 struct lru_gen_mm_walk *walk; 4200 struct folio *last = NULL; 4201 int young = 1; 4202 pte_t *pte = pvmw->pte; 4203 unsigned long addr = pvmw->address; 4204 struct vm_area_struct *vma = pvmw->vma; 4205 struct folio *folio = pfn_folio(pvmw->pfn); 4206 struct mem_cgroup *memcg = folio_memcg(folio); 4207 struct pglist_data *pgdat = folio_pgdat(folio); 4208 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat); 4209 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec); 4210 DEFINE_MAX_SEQ(lruvec); 4211 int gen = lru_gen_from_seq(max_seq); 4212 4213 lockdep_assert_held(pvmw->ptl); 4214 VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio); 4215 4216 if (!ptep_clear_young_notify(vma, addr, pte)) 4217 return false; 4218 4219 if (spin_is_contended(pvmw->ptl)) 4220 return true; 4221 4222 /* exclude special VMAs containing anon pages from COW */ 4223 if (vma->vm_flags & VM_SPECIAL) 4224 return true; 4225 4226 /* avoid taking the LRU lock under the PTL when possible */ 4227 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL; 4228 4229 start = max(addr & PMD_MASK, vma->vm_start); 4230 end = min(addr | ~PMD_MASK, vma->vm_end - 1) + 1; 4231 4232 if (end - start == PAGE_SIZE) 4233 return true; 4234 4235 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) { 4236 if (addr - start < MIN_LRU_BATCH * PAGE_SIZE / 2) 4237 end = start + MIN_LRU_BATCH * PAGE_SIZE; 4238 else if (end - addr < MIN_LRU_BATCH * PAGE_SIZE / 2) 4239 start = end - MIN_LRU_BATCH * PAGE_SIZE; 4240 else { 4241 start = addr - MIN_LRU_BATCH * PAGE_SIZE / 2; 4242 end = addr + MIN_LRU_BATCH * PAGE_SIZE / 2; 4243 } 4244 } 4245 4246 lazy_mmu_mode_enable(); 4247 4248 pte -= (addr - start) / PAGE_SIZE; 4249 4250 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) { 4251 unsigned long pfn; 4252 pte_t ptent = ptep_get(pte + i); 4253 4254 pfn = get_pte_pfn(ptent, vma, addr, pgdat); 4255 if (pfn == -1) 4256 continue; 4257 4258 folio = get_pfn_folio(pfn, memcg, pgdat); 4259 if (!folio) 4260 continue; 4261 4262 if (!ptep_clear_young_notify(vma, addr, pte + i)) 4263 continue; 4264 4265 if (last != folio) { 4266 walk_update_folio(walk, last, gen, dirty); 4267 4268 last = folio; 4269 dirty = false; 4270 } 4271 4272 if (pte_dirty(ptent)) 4273 dirty = true; 4274 4275 young++; 4276 } 4277 4278 walk_update_folio(walk, last, gen, dirty); 4279 4280 lazy_mmu_mode_disable(); 4281 4282 /* feedback from rmap walkers to page table walkers */ 4283 if (mm_state && suitable_to_scan(i, young)) 4284 update_bloom_filter(mm_state, max_seq, pvmw->pmd); 4285 4286 return true; 4287 } 4288 4289 /****************************************************************************** 4290 * memcg LRU 4291 ******************************************************************************/ 4292 4293 /* see the comment on MEMCG_NR_GENS */ 4294 enum { 4295 MEMCG_LRU_NOP, 4296 MEMCG_LRU_HEAD, 4297 MEMCG_LRU_TAIL, 4298 MEMCG_LRU_OLD, 4299 MEMCG_LRU_YOUNG, 4300 }; 4301 4302 static void lru_gen_rotate_memcg(struct lruvec *lruvec, int op) 4303 { 4304 int seg; 4305 int old, new; 4306 unsigned long flags; 4307 int bin = get_random_u32_below(MEMCG_NR_BINS); 4308 struct pglist_data *pgdat = lruvec_pgdat(lruvec); 4309 4310 spin_lock_irqsave(&pgdat->memcg_lru.lock, flags); 4311 4312 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list)); 4313 4314 seg = 0; 4315 new = old = lruvec->lrugen.gen; 4316 4317 /* see the comment on MEMCG_NR_GENS */ 4318 if (op == MEMCG_LRU_HEAD) 4319 seg = MEMCG_LRU_HEAD; 4320 else if (op == MEMCG_LRU_TAIL) 4321 seg = MEMCG_LRU_TAIL; 4322 else if (op == MEMCG_LRU_OLD) 4323 new = get_memcg_gen(pgdat->memcg_lru.seq); 4324 else if (op == MEMCG_LRU_YOUNG) 4325 new = get_memcg_gen(pgdat->memcg_lru.seq + 1); 4326 else 4327 VM_WARN_ON_ONCE(true); 4328 4329 WRITE_ONCE(lruvec->lrugen.seg, seg); 4330 WRITE_ONCE(lruvec->lrugen.gen, new); 4331 4332 hlist_nulls_del_rcu(&lruvec->lrugen.list); 4333 4334 if (op == MEMCG_LRU_HEAD || op == MEMCG_LRU_OLD) 4335 hlist_nulls_add_head_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]); 4336 else 4337 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]); 4338 4339 pgdat->memcg_lru.nr_memcgs[old]--; 4340 pgdat->memcg_lru.nr_memcgs[new]++; 4341 4342 if (!pgdat->memcg_lru.nr_memcgs[old] && old == get_memcg_gen(pgdat->memcg_lru.seq)) 4343 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1); 4344 4345 spin_unlock_irqrestore(&pgdat->memcg_lru.lock, flags); 4346 } 4347 4348 #ifdef CONFIG_MEMCG 4349 4350 void lru_gen_online_memcg(struct mem_cgroup *memcg) 4351 { 4352 int gen; 4353 int nid; 4354 int bin = get_random_u32_below(MEMCG_NR_BINS); 4355 4356 for_each_node(nid) { 4357 struct pglist_data *pgdat = NODE_DATA(nid); 4358 struct lruvec *lruvec = get_lruvec(memcg, nid); 4359 4360 spin_lock_irq(&pgdat->memcg_lru.lock); 4361 4362 VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec->lrugen.list)); 4363 4364 gen = get_memcg_gen(pgdat->memcg_lru.seq); 4365 4366 lruvec->lrugen.gen = gen; 4367 4368 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[gen][bin]); 4369 pgdat->memcg_lru.nr_memcgs[gen]++; 4370 4371 spin_unlock_irq(&pgdat->memcg_lru.lock); 4372 } 4373 } 4374 4375 void lru_gen_offline_memcg(struct mem_cgroup *memcg) 4376 { 4377 int nid; 4378 4379 for_each_node(nid) { 4380 struct lruvec *lruvec = get_lruvec(memcg, nid); 4381 4382 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_OLD); 4383 } 4384 } 4385 4386 void lru_gen_release_memcg(struct mem_cgroup *memcg) 4387 { 4388 int gen; 4389 int nid; 4390 4391 for_each_node(nid) { 4392 struct pglist_data *pgdat = NODE_DATA(nid); 4393 struct lruvec *lruvec = get_lruvec(memcg, nid); 4394 4395 spin_lock_irq(&pgdat->memcg_lru.lock); 4396 4397 if (hlist_nulls_unhashed(&lruvec->lrugen.list)) 4398 goto unlock; 4399 4400 gen = lruvec->lrugen.gen; 4401 4402 hlist_nulls_del_init_rcu(&lruvec->lrugen.list); 4403 pgdat->memcg_lru.nr_memcgs[gen]--; 4404 4405 if (!pgdat->memcg_lru.nr_memcgs[gen] && gen == get_memcg_gen(pgdat->memcg_lru.seq)) 4406 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1); 4407 unlock: 4408 spin_unlock_irq(&pgdat->memcg_lru.lock); 4409 } 4410 } 4411 4412 void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid) 4413 { 4414 struct lruvec *lruvec = get_lruvec(memcg, nid); 4415 4416 /* see the comment on MEMCG_NR_GENS */ 4417 if (READ_ONCE(lruvec->lrugen.seg) != MEMCG_LRU_HEAD) 4418 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_HEAD); 4419 } 4420 4421 #endif /* CONFIG_MEMCG */ 4422 4423 /****************************************************************************** 4424 * the eviction 4425 ******************************************************************************/ 4426 4427 static bool sort_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc, 4428 int tier_idx) 4429 { 4430 bool success; 4431 bool dirty, writeback; 4432 int gen = folio_lru_gen(folio); 4433 int type = folio_is_file_lru(folio); 4434 int zone = folio_zonenum(folio); 4435 int delta = folio_nr_pages(folio); 4436 int refs = folio_lru_refs(folio); 4437 bool workingset = folio_test_workingset(folio); 4438 int tier = lru_tier_from_refs(refs, workingset); 4439 struct lru_gen_folio *lrugen = &lruvec->lrugen; 4440 4441 VM_WARN_ON_ONCE_FOLIO(gen >= MAX_NR_GENS, folio); 4442 4443 /* unevictable */ 4444 if (!folio_evictable(folio)) { 4445 success = lru_gen_del_folio(lruvec, folio, true); 4446 VM_WARN_ON_ONCE_FOLIO(!success, folio); 4447 folio_set_unevictable(folio); 4448 lruvec_add_folio(lruvec, folio); 4449 __count_vm_events(UNEVICTABLE_PGCULLED, delta); 4450 return true; 4451 } 4452 4453 /* promoted */ 4454 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) { 4455 list_move(&folio->lru, &lrugen->folios[gen][type][zone]); 4456 return true; 4457 } 4458 4459 /* protected */ 4460 if (tier > tier_idx || refs + workingset == BIT(LRU_REFS_WIDTH) + 1) { 4461 gen = folio_inc_gen(lruvec, folio, false); 4462 list_move(&folio->lru, &lrugen->folios[gen][type][zone]); 4463 4464 /* don't count the workingset being lazily promoted */ 4465 if (refs + workingset != BIT(LRU_REFS_WIDTH) + 1) { 4466 int hist = lru_hist_from_seq(lrugen->min_seq[type]); 4467 4468 WRITE_ONCE(lrugen->protected[hist][type][tier], 4469 lrugen->protected[hist][type][tier] + delta); 4470 } 4471 return true; 4472 } 4473 4474 /* ineligible */ 4475 if (zone > sc->reclaim_idx) { 4476 gen = folio_inc_gen(lruvec, folio, false); 4477 list_move_tail(&folio->lru, &lrugen->folios[gen][type][zone]); 4478 return true; 4479 } 4480 4481 dirty = folio_test_dirty(folio); 4482 writeback = folio_test_writeback(folio); 4483 if (type == LRU_GEN_FILE && dirty) { 4484 sc->nr.file_taken += delta; 4485 if (!writeback) 4486 sc->nr.unqueued_dirty += delta; 4487 } 4488 4489 /* waiting for writeback */ 4490 if (writeback || (type == LRU_GEN_FILE && dirty)) { 4491 gen = folio_inc_gen(lruvec, folio, true); 4492 list_move(&folio->lru, &lrugen->folios[gen][type][zone]); 4493 return true; 4494 } 4495 4496 return false; 4497 } 4498 4499 static bool isolate_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc) 4500 { 4501 bool success; 4502 4503 /* swap constrained */ 4504 if (!(sc->gfp_mask & __GFP_IO) && 4505 (folio_test_dirty(folio) || 4506 (folio_test_anon(folio) && !folio_test_swapcache(folio)))) 4507 return false; 4508 4509 /* raced with release_pages() */ 4510 if (!folio_try_get(folio)) 4511 return false; 4512 4513 /* raced with another isolation */ 4514 if (!folio_test_clear_lru(folio)) { 4515 folio_put(folio); 4516 return false; 4517 } 4518 4519 /* see the comment on LRU_REFS_FLAGS */ 4520 if (!folio_test_referenced(folio)) 4521 set_mask_bits(&folio->flags.f, LRU_REFS_MASK, 0); 4522 4523 /* for shrink_folio_list() */ 4524 folio_clear_reclaim(folio); 4525 4526 success = lru_gen_del_folio(lruvec, folio, true); 4527 VM_WARN_ON_ONCE_FOLIO(!success, folio); 4528 4529 return true; 4530 } 4531 4532 static int scan_folios(unsigned long nr_to_scan, struct lruvec *lruvec, 4533 struct scan_control *sc, int type, int tier, 4534 struct list_head *list) 4535 { 4536 int i; 4537 int gen; 4538 enum vm_event_item item; 4539 int sorted = 0; 4540 int scanned = 0; 4541 int isolated = 0; 4542 int skipped = 0; 4543 int scan_batch = min(nr_to_scan, MAX_LRU_BATCH); 4544 int remaining = scan_batch; 4545 struct lru_gen_folio *lrugen = &lruvec->lrugen; 4546 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 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 if (!cgroup_reclaim(sc)) { 4598 __count_vm_events(item, isolated); 4599 __count_vm_events(PGREFILL, sorted); 4600 } 4601 count_memcg_events(memcg, item, isolated); 4602 count_memcg_events(memcg, PGREFILL, sorted); 4603 __count_vm_events(PGSCAN_ANON + type, isolated); 4604 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, scan_batch, 4605 scanned, skipped, isolated, 4606 type ? LRU_INACTIVE_FILE : LRU_INACTIVE_ANON); 4607 if (type == LRU_GEN_FILE) 4608 sc->nr.file_taken += isolated; 4609 /* 4610 * There might not be eligible folios due to reclaim_idx. Check the 4611 * remaining to prevent livelock if it's not making progress. 4612 */ 4613 return isolated || !remaining ? scanned : 0; 4614 } 4615 4616 static int get_tier_idx(struct lruvec *lruvec, int type) 4617 { 4618 int tier; 4619 struct ctrl_pos sp, pv; 4620 4621 /* 4622 * To leave a margin for fluctuations, use a larger gain factor (2:3). 4623 * This value is chosen because any other tier would have at least twice 4624 * as many refaults as the first tier. 4625 */ 4626 read_ctrl_pos(lruvec, type, 0, 2, &sp); 4627 for (tier = 1; tier < MAX_NR_TIERS; tier++) { 4628 read_ctrl_pos(lruvec, type, tier, 3, &pv); 4629 if (!positive_ctrl_err(&sp, &pv)) 4630 break; 4631 } 4632 4633 return tier - 1; 4634 } 4635 4636 static int get_type_to_scan(struct lruvec *lruvec, int swappiness) 4637 { 4638 struct ctrl_pos sp, pv; 4639 4640 if (swappiness <= MIN_SWAPPINESS + 1) 4641 return LRU_GEN_FILE; 4642 4643 if (swappiness >= MAX_SWAPPINESS) 4644 return LRU_GEN_ANON; 4645 /* 4646 * Compare the sum of all tiers of anon with that of file to determine 4647 * which type to scan. 4648 */ 4649 read_ctrl_pos(lruvec, LRU_GEN_ANON, MAX_NR_TIERS, swappiness, &sp); 4650 read_ctrl_pos(lruvec, LRU_GEN_FILE, MAX_NR_TIERS, MAX_SWAPPINESS - swappiness, &pv); 4651 4652 return positive_ctrl_err(&sp, &pv); 4653 } 4654 4655 static int isolate_folios(unsigned long nr_to_scan, struct lruvec *lruvec, 4656 struct scan_control *sc, int swappiness, 4657 int *type_scanned, struct list_head *list) 4658 { 4659 int i; 4660 int type = get_type_to_scan(lruvec, swappiness); 4661 4662 for_each_evictable_type(i, swappiness) { 4663 int scanned; 4664 int tier = get_tier_idx(lruvec, type); 4665 4666 *type_scanned = type; 4667 4668 scanned = scan_folios(nr_to_scan, lruvec, sc, type, tier, list); 4669 if (scanned) 4670 return scanned; 4671 4672 type = !type; 4673 } 4674 4675 return 0; 4676 } 4677 4678 static int evict_folios(unsigned long nr_to_scan, struct lruvec *lruvec, 4679 struct scan_control *sc, int swappiness) 4680 { 4681 int type; 4682 int scanned; 4683 int reclaimed; 4684 LIST_HEAD(list); 4685 LIST_HEAD(clean); 4686 struct folio *folio; 4687 struct folio *next; 4688 enum vm_event_item item; 4689 struct reclaim_stat stat; 4690 struct lru_gen_mm_walk *walk; 4691 bool skip_retry = false; 4692 struct lru_gen_folio *lrugen = &lruvec->lrugen; 4693 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 4694 struct pglist_data *pgdat = lruvec_pgdat(lruvec); 4695 4696 spin_lock_irq(&lruvec->lru_lock); 4697 4698 scanned = isolate_folios(nr_to_scan, lruvec, sc, swappiness, &type, &list); 4699 4700 scanned += try_to_inc_min_seq(lruvec, swappiness); 4701 4702 if (evictable_min_seq(lrugen->min_seq, swappiness) + MIN_NR_GENS > lrugen->max_seq) 4703 scanned = 0; 4704 4705 spin_unlock_irq(&lruvec->lru_lock); 4706 4707 if (list_empty(&list)) 4708 return scanned; 4709 retry: 4710 reclaimed = shrink_folio_list(&list, pgdat, sc, &stat, false, memcg); 4711 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty; 4712 sc->nr_reclaimed += reclaimed; 4713 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id, 4714 scanned, reclaimed, &stat, sc->priority, 4715 type ? LRU_INACTIVE_FILE : LRU_INACTIVE_ANON); 4716 4717 list_for_each_entry_safe_reverse(folio, next, &list, lru) { 4718 DEFINE_MIN_SEQ(lruvec); 4719 4720 if (!folio_evictable(folio)) { 4721 list_del(&folio->lru); 4722 folio_putback_lru(folio); 4723 continue; 4724 } 4725 4726 /* retry folios that may have missed folio_rotate_reclaimable() */ 4727 if (!skip_retry && !folio_test_active(folio) && !folio_mapped(folio) && 4728 !folio_test_dirty(folio) && !folio_test_writeback(folio)) { 4729 list_move(&folio->lru, &clean); 4730 continue; 4731 } 4732 4733 /* don't add rejected folios to the oldest generation */ 4734 if (lru_gen_folio_seq(lruvec, folio, false) == min_seq[type]) 4735 set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS, BIT(PG_active)); 4736 } 4737 4738 spin_lock_irq(&lruvec->lru_lock); 4739 4740 move_folios_to_lru(lruvec, &list); 4741 4742 walk = current->reclaim_state->mm_walk; 4743 if (walk && walk->batched) { 4744 walk->lruvec = lruvec; 4745 reset_batch_size(walk); 4746 } 4747 4748 mod_lruvec_state(lruvec, PGDEMOTE_KSWAPD + reclaimer_offset(sc), 4749 stat.nr_demoted); 4750 4751 item = PGSTEAL_KSWAPD + reclaimer_offset(sc); 4752 if (!cgroup_reclaim(sc)) 4753 __count_vm_events(item, reclaimed); 4754 count_memcg_events(memcg, item, reclaimed); 4755 __count_vm_events(PGSTEAL_ANON + type, reclaimed); 4756 4757 spin_unlock_irq(&lruvec->lru_lock); 4758 4759 list_splice_init(&clean, &list); 4760 4761 if (!list_empty(&list)) { 4762 skip_retry = true; 4763 goto retry; 4764 } 4765 4766 return scanned; 4767 } 4768 4769 static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, 4770 int swappiness, unsigned long *nr_to_scan) 4771 { 4772 int gen, type, zone; 4773 unsigned long size = 0; 4774 struct lru_gen_folio *lrugen = &lruvec->lrugen; 4775 DEFINE_MIN_SEQ(lruvec); 4776 4777 *nr_to_scan = 0; 4778 /* have to run aging, since eviction is not possible anymore */ 4779 if (evictable_min_seq(min_seq, swappiness) + MIN_NR_GENS > max_seq) 4780 return true; 4781 4782 for_each_evictable_type(type, swappiness) { 4783 unsigned long seq; 4784 4785 for (seq = min_seq[type]; seq <= max_seq; seq++) { 4786 gen = lru_gen_from_seq(seq); 4787 4788 for (zone = 0; zone < MAX_NR_ZONES; zone++) 4789 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L); 4790 } 4791 } 4792 4793 *nr_to_scan = size; 4794 /* better to run aging even though eviction is still possible */ 4795 return evictable_min_seq(min_seq, swappiness) + MIN_NR_GENS == max_seq; 4796 } 4797 4798 /* 4799 * For future optimizations: 4800 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg 4801 * reclaim. 4802 */ 4803 static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, int swappiness) 4804 { 4805 bool success; 4806 unsigned long nr_to_scan; 4807 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 4808 DEFINE_MAX_SEQ(lruvec); 4809 4810 if (mem_cgroup_below_min(sc->target_mem_cgroup, memcg)) 4811 return -1; 4812 4813 success = should_run_aging(lruvec, max_seq, swappiness, &nr_to_scan); 4814 4815 /* try to scrape all its memory if this memcg was deleted */ 4816 if (nr_to_scan && !mem_cgroup_online(memcg)) 4817 return nr_to_scan; 4818 4819 nr_to_scan = apply_proportional_protection(memcg, sc, nr_to_scan); 4820 4821 /* try to get away with not aging at the default priority */ 4822 if (!success || sc->priority == DEF_PRIORITY) 4823 return nr_to_scan >> sc->priority; 4824 4825 /* stop scanning this lruvec as it's low on cold folios */ 4826 return try_to_inc_max_seq(lruvec, max_seq, swappiness, false) ? -1 : 0; 4827 } 4828 4829 static bool should_abort_scan(struct lruvec *lruvec, struct scan_control *sc) 4830 { 4831 int i; 4832 enum zone_watermarks mark; 4833 4834 /* don't abort memcg reclaim to ensure fairness */ 4835 if (!root_reclaim(sc)) 4836 return false; 4837 4838 if (sc->nr_reclaimed >= max(sc->nr_to_reclaim, compact_gap(sc->order))) 4839 return true; 4840 4841 /* check the order to exclude compaction-induced reclaim */ 4842 if (!current_is_kswapd() || sc->order) 4843 return false; 4844 4845 mark = sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ? 4846 WMARK_PROMO : WMARK_HIGH; 4847 4848 for (i = 0; i <= sc->reclaim_idx; i++) { 4849 struct zone *zone = lruvec_pgdat(lruvec)->node_zones + i; 4850 unsigned long size = wmark_pages(zone, mark) + MIN_LRU_BATCH; 4851 4852 if (managed_zone(zone) && !zone_watermark_ok(zone, 0, size, sc->reclaim_idx, 0)) 4853 return false; 4854 } 4855 4856 /* kswapd should abort if all eligible zones are safe */ 4857 return true; 4858 } 4859 4860 static bool try_to_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc) 4861 { 4862 long nr_to_scan; 4863 unsigned long scanned = 0; 4864 int swappiness = get_swappiness(lruvec, sc); 4865 4866 while (true) { 4867 int delta; 4868 4869 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness); 4870 if (nr_to_scan <= 0) 4871 break; 4872 4873 delta = evict_folios(nr_to_scan, lruvec, sc, swappiness); 4874 if (!delta) 4875 break; 4876 4877 scanned += delta; 4878 if (scanned >= nr_to_scan) 4879 break; 4880 4881 if (should_abort_scan(lruvec, sc)) 4882 break; 4883 4884 cond_resched(); 4885 } 4886 4887 /* 4888 * If too many file cache in the coldest generation can't be evicted 4889 * due to being dirty, wake up the flusher. 4890 */ 4891 if (sc->nr.unqueued_dirty && sc->nr.unqueued_dirty == sc->nr.file_taken) 4892 wakeup_flusher_threads(WB_REASON_VMSCAN); 4893 4894 /* whether this lruvec should be rotated */ 4895 return nr_to_scan < 0; 4896 } 4897 4898 static int shrink_one(struct lruvec *lruvec, struct scan_control *sc) 4899 { 4900 bool success; 4901 unsigned long scanned = sc->nr_scanned; 4902 unsigned long reclaimed = sc->nr_reclaimed; 4903 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 4904 struct pglist_data *pgdat = lruvec_pgdat(lruvec); 4905 4906 /* lru_gen_age_node() called mem_cgroup_calculate_protection() */ 4907 if (mem_cgroup_below_min(NULL, memcg)) 4908 return MEMCG_LRU_YOUNG; 4909 4910 if (mem_cgroup_below_low(NULL, memcg)) { 4911 /* see the comment on MEMCG_NR_GENS */ 4912 if (READ_ONCE(lruvec->lrugen.seg) != MEMCG_LRU_TAIL) 4913 return MEMCG_LRU_TAIL; 4914 4915 memcg_memory_event(memcg, MEMCG_LOW); 4916 } 4917 4918 success = try_to_shrink_lruvec(lruvec, sc); 4919 4920 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, sc->priority); 4921 4922 if (!sc->proactive) 4923 vmpressure(sc->gfp_mask, memcg, false, sc->nr_scanned - scanned, 4924 sc->nr_reclaimed - reclaimed); 4925 4926 flush_reclaim_state(sc); 4927 4928 if (success && mem_cgroup_online(memcg)) 4929 return MEMCG_LRU_YOUNG; 4930 4931 if (!success && lruvec_is_sizable(lruvec, sc)) 4932 return 0; 4933 4934 /* one retry if offlined or too small */ 4935 return READ_ONCE(lruvec->lrugen.seg) != MEMCG_LRU_TAIL ? 4936 MEMCG_LRU_TAIL : MEMCG_LRU_YOUNG; 4937 } 4938 4939 static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc) 4940 { 4941 int op; 4942 int gen; 4943 int bin; 4944 int first_bin; 4945 struct lruvec *lruvec; 4946 struct lru_gen_folio *lrugen; 4947 struct mem_cgroup *memcg; 4948 struct hlist_nulls_node *pos; 4949 4950 gen = get_memcg_gen(READ_ONCE(pgdat->memcg_lru.seq)); 4951 bin = first_bin = get_random_u32_below(MEMCG_NR_BINS); 4952 restart: 4953 op = 0; 4954 memcg = NULL; 4955 4956 rcu_read_lock(); 4957 4958 hlist_nulls_for_each_entry_rcu(lrugen, pos, &pgdat->memcg_lru.fifo[gen][bin], list) { 4959 if (op) { 4960 lru_gen_rotate_memcg(lruvec, op); 4961 op = 0; 4962 } 4963 4964 mem_cgroup_put(memcg); 4965 memcg = NULL; 4966 4967 if (gen != READ_ONCE(lrugen->gen)) 4968 continue; 4969 4970 lruvec = container_of(lrugen, struct lruvec, lrugen); 4971 memcg = lruvec_memcg(lruvec); 4972 4973 if (!mem_cgroup_tryget(memcg)) { 4974 lru_gen_release_memcg(memcg); 4975 memcg = NULL; 4976 continue; 4977 } 4978 4979 rcu_read_unlock(); 4980 4981 op = shrink_one(lruvec, sc); 4982 4983 rcu_read_lock(); 4984 4985 if (should_abort_scan(lruvec, sc)) 4986 break; 4987 } 4988 4989 rcu_read_unlock(); 4990 4991 if (op) 4992 lru_gen_rotate_memcg(lruvec, op); 4993 4994 mem_cgroup_put(memcg); 4995 4996 if (!is_a_nulls(pos)) 4997 return; 4998 4999 /* restart if raced with lru_gen_rotate_memcg() */ 5000 if (gen != get_nulls_value(pos)) 5001 goto restart; 5002 5003 /* try the rest of the bins of the current generation */ 5004 bin = get_memcg_bin(bin + 1); 5005 if (bin != first_bin) 5006 goto restart; 5007 } 5008 5009 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc) 5010 { 5011 struct blk_plug plug; 5012 5013 VM_WARN_ON_ONCE(root_reclaim(sc)); 5014 VM_WARN_ON_ONCE(!sc->may_writepage || !sc->may_unmap); 5015 5016 lru_add_drain(); 5017 5018 blk_start_plug(&plug); 5019 5020 set_mm_walk(NULL, sc->proactive); 5021 5022 if (try_to_shrink_lruvec(lruvec, sc)) 5023 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_YOUNG); 5024 5025 clear_mm_walk(); 5026 5027 blk_finish_plug(&plug); 5028 } 5029 5030 static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc) 5031 { 5032 struct blk_plug plug; 5033 unsigned long reclaimed = sc->nr_reclaimed; 5034 5035 VM_WARN_ON_ONCE(!root_reclaim(sc)); 5036 5037 /* 5038 * Unmapped clean folios are already prioritized. Scanning for more of 5039 * them is likely futile and can cause high reclaim latency when there 5040 * is a large number of memcgs. 5041 */ 5042 if (!sc->may_writepage || !sc->may_unmap) 5043 goto done; 5044 5045 lru_add_drain(); 5046 5047 blk_start_plug(&plug); 5048 5049 set_mm_walk(pgdat, sc->proactive); 5050 5051 set_initial_priority(pgdat, sc); 5052 5053 if (current_is_kswapd()) 5054 sc->nr_reclaimed = 0; 5055 5056 if (mem_cgroup_disabled()) 5057 shrink_one(&pgdat->__lruvec, sc); 5058 else 5059 shrink_many(pgdat, sc); 5060 5061 if (current_is_kswapd()) 5062 sc->nr_reclaimed += reclaimed; 5063 5064 clear_mm_walk(); 5065 5066 blk_finish_plug(&plug); 5067 done: 5068 if (sc->nr_reclaimed > reclaimed) 5069 atomic_set(&pgdat->kswapd_failures, 0); 5070 } 5071 5072 /****************************************************************************** 5073 * state change 5074 ******************************************************************************/ 5075 5076 static bool __maybe_unused state_is_valid(struct lruvec *lruvec) 5077 { 5078 struct lru_gen_folio *lrugen = &lruvec->lrugen; 5079 5080 if (lrugen->enabled) { 5081 enum lru_list lru; 5082 5083 for_each_evictable_lru(lru) { 5084 if (!list_empty(&lruvec->lists[lru])) 5085 return false; 5086 } 5087 } else { 5088 int gen, type, zone; 5089 5090 for_each_gen_type_zone(gen, type, zone) { 5091 if (!list_empty(&lrugen->folios[gen][type][zone])) 5092 return false; 5093 } 5094 } 5095 5096 return true; 5097 } 5098 5099 static bool fill_evictable(struct lruvec *lruvec) 5100 { 5101 enum lru_list lru; 5102 int remaining = MAX_LRU_BATCH; 5103 5104 for_each_evictable_lru(lru) { 5105 int type = is_file_lru(lru); 5106 bool active = is_active_lru(lru); 5107 struct list_head *head = &lruvec->lists[lru]; 5108 5109 while (!list_empty(head)) { 5110 bool success; 5111 struct folio *folio = lru_to_folio(head); 5112 5113 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio); 5114 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio) != active, folio); 5115 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio); 5116 VM_WARN_ON_ONCE_FOLIO(folio_lru_gen(folio) != -1, folio); 5117 5118 lruvec_del_folio(lruvec, folio); 5119 success = lru_gen_add_folio(lruvec, folio, false); 5120 VM_WARN_ON_ONCE(!success); 5121 5122 if (!--remaining) 5123 return false; 5124 } 5125 } 5126 5127 return true; 5128 } 5129 5130 static bool drain_evictable(struct lruvec *lruvec) 5131 { 5132 int gen, type, zone; 5133 int remaining = MAX_LRU_BATCH; 5134 5135 for_each_gen_type_zone(gen, type, zone) { 5136 struct list_head *head = &lruvec->lrugen.folios[gen][type][zone]; 5137 5138 while (!list_empty(head)) { 5139 bool success; 5140 struct folio *folio = lru_to_folio(head); 5141 5142 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio); 5143 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio); 5144 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio); 5145 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio); 5146 5147 success = lru_gen_del_folio(lruvec, folio, false); 5148 VM_WARN_ON_ONCE(!success); 5149 lruvec_add_folio(lruvec, folio); 5150 5151 if (!--remaining) 5152 return false; 5153 } 5154 } 5155 5156 return true; 5157 } 5158 5159 static void lru_gen_change_state(bool enabled) 5160 { 5161 static DEFINE_MUTEX(state_mutex); 5162 5163 struct mem_cgroup *memcg; 5164 5165 cgroup_lock(); 5166 cpus_read_lock(); 5167 get_online_mems(); 5168 mutex_lock(&state_mutex); 5169 5170 if (enabled == lru_gen_enabled()) 5171 goto unlock; 5172 5173 if (enabled) 5174 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]); 5175 else 5176 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]); 5177 5178 memcg = mem_cgroup_iter(NULL, NULL, NULL); 5179 do { 5180 int nid; 5181 5182 for_each_node(nid) { 5183 struct lruvec *lruvec = get_lruvec(memcg, nid); 5184 5185 spin_lock_irq(&lruvec->lru_lock); 5186 5187 VM_WARN_ON_ONCE(!seq_is_valid(lruvec)); 5188 VM_WARN_ON_ONCE(!state_is_valid(lruvec)); 5189 5190 lruvec->lrugen.enabled = enabled; 5191 5192 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) { 5193 spin_unlock_irq(&lruvec->lru_lock); 5194 cond_resched(); 5195 spin_lock_irq(&lruvec->lru_lock); 5196 } 5197 5198 spin_unlock_irq(&lruvec->lru_lock); 5199 } 5200 5201 cond_resched(); 5202 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL))); 5203 unlock: 5204 mutex_unlock(&state_mutex); 5205 put_online_mems(); 5206 cpus_read_unlock(); 5207 cgroup_unlock(); 5208 } 5209 5210 /****************************************************************************** 5211 * sysfs interface 5212 ******************************************************************************/ 5213 5214 static ssize_t min_ttl_ms_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) 5215 { 5216 return sysfs_emit(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl))); 5217 } 5218 5219 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */ 5220 static ssize_t min_ttl_ms_store(struct kobject *kobj, struct kobj_attribute *attr, 5221 const char *buf, size_t len) 5222 { 5223 unsigned int msecs; 5224 5225 if (kstrtouint(buf, 0, &msecs)) 5226 return -EINVAL; 5227 5228 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs)); 5229 5230 return len; 5231 } 5232 5233 static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR_RW(min_ttl_ms); 5234 5235 static ssize_t enabled_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) 5236 { 5237 unsigned int caps = 0; 5238 5239 if (get_cap(LRU_GEN_CORE)) 5240 caps |= BIT(LRU_GEN_CORE); 5241 5242 if (should_walk_mmu()) 5243 caps |= BIT(LRU_GEN_MM_WALK); 5244 5245 if (should_clear_pmd_young()) 5246 caps |= BIT(LRU_GEN_NONLEAF_YOUNG); 5247 5248 return sysfs_emit(buf, "0x%04x\n", caps); 5249 } 5250 5251 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */ 5252 static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr, 5253 const char *buf, size_t len) 5254 { 5255 int i; 5256 unsigned int caps; 5257 5258 if (tolower(*buf) == 'n') 5259 caps = 0; 5260 else if (tolower(*buf) == 'y') 5261 caps = -1; 5262 else if (kstrtouint(buf, 0, &caps)) 5263 return -EINVAL; 5264 5265 for (i = 0; i < NR_LRU_GEN_CAPS; i++) { 5266 bool enabled = caps & BIT(i); 5267 5268 if (i == LRU_GEN_CORE) 5269 lru_gen_change_state(enabled); 5270 else if (enabled) 5271 static_branch_enable(&lru_gen_caps[i]); 5272 else 5273 static_branch_disable(&lru_gen_caps[i]); 5274 } 5275 5276 return len; 5277 } 5278 5279 static struct kobj_attribute lru_gen_enabled_attr = __ATTR_RW(enabled); 5280 5281 static struct attribute *lru_gen_attrs[] = { 5282 &lru_gen_min_ttl_attr.attr, 5283 &lru_gen_enabled_attr.attr, 5284 NULL 5285 }; 5286 5287 static const struct attribute_group lru_gen_attr_group = { 5288 .name = "lru_gen", 5289 .attrs = lru_gen_attrs, 5290 }; 5291 5292 /****************************************************************************** 5293 * debugfs interface 5294 ******************************************************************************/ 5295 5296 static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos) 5297 { 5298 struct mem_cgroup *memcg; 5299 loff_t nr_to_skip = *pos; 5300 5301 m->private = kvmalloc(PATH_MAX, GFP_KERNEL); 5302 if (!m->private) 5303 return ERR_PTR(-ENOMEM); 5304 5305 memcg = mem_cgroup_iter(NULL, NULL, NULL); 5306 do { 5307 int nid; 5308 5309 for_each_node_state(nid, N_MEMORY) { 5310 if (!nr_to_skip--) 5311 return get_lruvec(memcg, nid); 5312 } 5313 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL))); 5314 5315 return NULL; 5316 } 5317 5318 static void lru_gen_seq_stop(struct seq_file *m, void *v) 5319 { 5320 if (!IS_ERR_OR_NULL(v)) 5321 mem_cgroup_iter_break(NULL, lruvec_memcg(v)); 5322 5323 kvfree(m->private); 5324 m->private = NULL; 5325 } 5326 5327 static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos) 5328 { 5329 int nid = lruvec_pgdat(v)->node_id; 5330 struct mem_cgroup *memcg = lruvec_memcg(v); 5331 5332 ++*pos; 5333 5334 nid = next_memory_node(nid); 5335 if (nid == MAX_NUMNODES) { 5336 memcg = mem_cgroup_iter(NULL, memcg, NULL); 5337 if (!memcg) 5338 return NULL; 5339 5340 nid = first_memory_node; 5341 } 5342 5343 return get_lruvec(memcg, nid); 5344 } 5345 5346 static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec, 5347 unsigned long max_seq, unsigned long *min_seq, 5348 unsigned long seq) 5349 { 5350 int i; 5351 int type, tier; 5352 int hist = lru_hist_from_seq(seq); 5353 struct lru_gen_folio *lrugen = &lruvec->lrugen; 5354 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec); 5355 5356 for (tier = 0; tier < MAX_NR_TIERS; tier++) { 5357 seq_printf(m, " %10d", tier); 5358 for (type = 0; type < ANON_AND_FILE; type++) { 5359 const char *s = "xxx"; 5360 unsigned long n[3] = {}; 5361 5362 if (seq == max_seq) { 5363 s = "RTx"; 5364 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]); 5365 n[1] = READ_ONCE(lrugen->avg_total[type][tier]); 5366 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) { 5367 s = "rep"; 5368 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]); 5369 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]); 5370 n[2] = READ_ONCE(lrugen->protected[hist][type][tier]); 5371 } 5372 5373 for (i = 0; i < 3; i++) 5374 seq_printf(m, " %10lu%c", n[i], s[i]); 5375 } 5376 seq_putc(m, '\n'); 5377 } 5378 5379 if (!mm_state) 5380 return; 5381 5382 seq_puts(m, " "); 5383 for (i = 0; i < NR_MM_STATS; i++) { 5384 const char *s = "xxxx"; 5385 unsigned long n = 0; 5386 5387 if (seq == max_seq && NR_HIST_GENS == 1) { 5388 s = "TYFA"; 5389 n = READ_ONCE(mm_state->stats[hist][i]); 5390 } else if (seq != max_seq && NR_HIST_GENS > 1) { 5391 s = "tyfa"; 5392 n = READ_ONCE(mm_state->stats[hist][i]); 5393 } 5394 5395 seq_printf(m, " %10lu%c", n, s[i]); 5396 } 5397 seq_putc(m, '\n'); 5398 } 5399 5400 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */ 5401 static int lru_gen_seq_show(struct seq_file *m, void *v) 5402 { 5403 unsigned long seq; 5404 bool full = debugfs_get_aux_num(m->file); 5405 struct lruvec *lruvec = v; 5406 struct lru_gen_folio *lrugen = &lruvec->lrugen; 5407 int nid = lruvec_pgdat(lruvec)->node_id; 5408 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 5409 DEFINE_MAX_SEQ(lruvec); 5410 DEFINE_MIN_SEQ(lruvec); 5411 5412 if (nid == first_memory_node) { 5413 const char *path = memcg ? m->private : ""; 5414 5415 #ifdef CONFIG_MEMCG 5416 if (memcg) 5417 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX); 5418 #endif 5419 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path); 5420 } 5421 5422 seq_printf(m, " node %5d\n", nid); 5423 5424 if (!full) 5425 seq = evictable_min_seq(min_seq, MAX_SWAPPINESS / 2); 5426 else if (max_seq >= MAX_NR_GENS) 5427 seq = max_seq - MAX_NR_GENS + 1; 5428 else 5429 seq = 0; 5430 5431 for (; seq <= max_seq; seq++) { 5432 int type, zone; 5433 int gen = lru_gen_from_seq(seq); 5434 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]); 5435 5436 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth)); 5437 5438 for (type = 0; type < ANON_AND_FILE; type++) { 5439 unsigned long size = 0; 5440 char mark = full && seq < min_seq[type] ? 'x' : ' '; 5441 5442 for (zone = 0; zone < MAX_NR_ZONES; zone++) 5443 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L); 5444 5445 seq_printf(m, " %10lu%c", size, mark); 5446 } 5447 5448 seq_putc(m, '\n'); 5449 5450 if (full) 5451 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq); 5452 } 5453 5454 return 0; 5455 } 5456 5457 static const struct seq_operations lru_gen_seq_ops = { 5458 .start = lru_gen_seq_start, 5459 .stop = lru_gen_seq_stop, 5460 .next = lru_gen_seq_next, 5461 .show = lru_gen_seq_show, 5462 }; 5463 5464 static int run_aging(struct lruvec *lruvec, unsigned long seq, 5465 int swappiness, bool force_scan) 5466 { 5467 DEFINE_MAX_SEQ(lruvec); 5468 5469 if (seq > max_seq) 5470 return -EINVAL; 5471 5472 return try_to_inc_max_seq(lruvec, max_seq, swappiness, force_scan) ? 0 : -EEXIST; 5473 } 5474 5475 static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc, 5476 int swappiness, unsigned long nr_to_reclaim) 5477 { 5478 DEFINE_MAX_SEQ(lruvec); 5479 5480 if (seq + MIN_NR_GENS > max_seq) 5481 return -EINVAL; 5482 5483 sc->nr_reclaimed = 0; 5484 5485 while (!signal_pending(current)) { 5486 DEFINE_MIN_SEQ(lruvec); 5487 5488 if (seq < evictable_min_seq(min_seq, swappiness)) 5489 return 0; 5490 5491 if (sc->nr_reclaimed >= nr_to_reclaim) 5492 return 0; 5493 5494 if (!evict_folios(nr_to_reclaim - sc->nr_reclaimed, lruvec, sc, 5495 swappiness)) 5496 return 0; 5497 5498 cond_resched(); 5499 } 5500 5501 return -EINTR; 5502 } 5503 5504 static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq, 5505 struct scan_control *sc, int swappiness, unsigned long opt) 5506 { 5507 struct lruvec *lruvec; 5508 int err = -EINVAL; 5509 struct mem_cgroup *memcg = NULL; 5510 5511 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY)) 5512 return -EINVAL; 5513 5514 if (!mem_cgroup_disabled()) { 5515 rcu_read_lock(); 5516 5517 memcg = mem_cgroup_from_id(memcg_id); 5518 if (!mem_cgroup_tryget(memcg)) 5519 memcg = NULL; 5520 5521 rcu_read_unlock(); 5522 5523 if (!memcg) 5524 return -EINVAL; 5525 } 5526 5527 if (memcg_id != mem_cgroup_id(memcg)) 5528 goto done; 5529 5530 sc->target_mem_cgroup = memcg; 5531 lruvec = get_lruvec(memcg, nid); 5532 5533 if (swappiness < MIN_SWAPPINESS) 5534 swappiness = get_swappiness(lruvec, sc); 5535 else if (swappiness > SWAPPINESS_ANON_ONLY) 5536 goto done; 5537 5538 switch (cmd) { 5539 case '+': 5540 err = run_aging(lruvec, seq, swappiness, opt); 5541 break; 5542 case '-': 5543 err = run_eviction(lruvec, seq, sc, swappiness, opt); 5544 break; 5545 } 5546 done: 5547 mem_cgroup_put(memcg); 5548 5549 return err; 5550 } 5551 5552 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */ 5553 static ssize_t lru_gen_seq_write(struct file *file, const char __user *src, 5554 size_t len, loff_t *pos) 5555 { 5556 void *buf; 5557 char *cur, *next; 5558 unsigned int flags; 5559 struct blk_plug plug; 5560 int err = -EINVAL; 5561 struct scan_control sc = { 5562 .may_writepage = true, 5563 .may_unmap = true, 5564 .may_swap = true, 5565 .reclaim_idx = MAX_NR_ZONES - 1, 5566 .gfp_mask = GFP_KERNEL, 5567 .proactive = true, 5568 }; 5569 5570 buf = kvmalloc(len + 1, GFP_KERNEL); 5571 if (!buf) 5572 return -ENOMEM; 5573 5574 if (copy_from_user(buf, src, len)) { 5575 kvfree(buf); 5576 return -EFAULT; 5577 } 5578 5579 set_task_reclaim_state(current, &sc.reclaim_state); 5580 flags = memalloc_noreclaim_save(); 5581 blk_start_plug(&plug); 5582 if (!set_mm_walk(NULL, true)) { 5583 err = -ENOMEM; 5584 goto done; 5585 } 5586 5587 next = buf; 5588 next[len] = '\0'; 5589 5590 while ((cur = strsep(&next, ",;\n"))) { 5591 int n; 5592 int end; 5593 char cmd, swap_string[5]; 5594 unsigned int memcg_id; 5595 unsigned int nid; 5596 unsigned long seq; 5597 unsigned int swappiness; 5598 unsigned long opt = -1; 5599 5600 cur = skip_spaces(cur); 5601 if (!*cur) 5602 continue; 5603 5604 n = sscanf(cur, "%c %u %u %lu %n %4s %n %lu %n", &cmd, &memcg_id, &nid, 5605 &seq, &end, swap_string, &end, &opt, &end); 5606 if (n < 4 || cur[end]) { 5607 err = -EINVAL; 5608 break; 5609 } 5610 5611 if (n == 4) { 5612 swappiness = -1; 5613 } else if (!strcmp("max", swap_string)) { 5614 /* set by userspace for anonymous memory only */ 5615 swappiness = SWAPPINESS_ANON_ONLY; 5616 } else { 5617 err = kstrtouint(swap_string, 0, &swappiness); 5618 if (err) 5619 break; 5620 } 5621 5622 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt); 5623 if (err) 5624 break; 5625 } 5626 done: 5627 clear_mm_walk(); 5628 blk_finish_plug(&plug); 5629 memalloc_noreclaim_restore(flags); 5630 set_task_reclaim_state(current, NULL); 5631 5632 kvfree(buf); 5633 5634 return err ? : len; 5635 } 5636 5637 static int lru_gen_seq_open(struct inode *inode, struct file *file) 5638 { 5639 return seq_open(file, &lru_gen_seq_ops); 5640 } 5641 5642 static const struct file_operations lru_gen_rw_fops = { 5643 .open = lru_gen_seq_open, 5644 .read = seq_read, 5645 .write = lru_gen_seq_write, 5646 .llseek = seq_lseek, 5647 .release = seq_release, 5648 }; 5649 5650 static const struct file_operations lru_gen_ro_fops = { 5651 .open = lru_gen_seq_open, 5652 .read = seq_read, 5653 .llseek = seq_lseek, 5654 .release = seq_release, 5655 }; 5656 5657 /****************************************************************************** 5658 * initialization 5659 ******************************************************************************/ 5660 5661 void lru_gen_init_pgdat(struct pglist_data *pgdat) 5662 { 5663 int i, j; 5664 5665 spin_lock_init(&pgdat->memcg_lru.lock); 5666 5667 for (i = 0; i < MEMCG_NR_GENS; i++) { 5668 for (j = 0; j < MEMCG_NR_BINS; j++) 5669 INIT_HLIST_NULLS_HEAD(&pgdat->memcg_lru.fifo[i][j], i); 5670 } 5671 } 5672 5673 void lru_gen_init_lruvec(struct lruvec *lruvec) 5674 { 5675 int i; 5676 int gen, type, zone; 5677 struct lru_gen_folio *lrugen = &lruvec->lrugen; 5678 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec); 5679 5680 lrugen->max_seq = MIN_NR_GENS + 1; 5681 lrugen->enabled = lru_gen_enabled(); 5682 5683 for (i = 0; i <= MIN_NR_GENS + 1; i++) 5684 lrugen->timestamps[i] = jiffies; 5685 5686 for_each_gen_type_zone(gen, type, zone) 5687 INIT_LIST_HEAD(&lrugen->folios[gen][type][zone]); 5688 5689 if (mm_state) 5690 mm_state->seq = MIN_NR_GENS; 5691 } 5692 5693 #ifdef CONFIG_MEMCG 5694 5695 void lru_gen_init_memcg(struct mem_cgroup *memcg) 5696 { 5697 struct lru_gen_mm_list *mm_list = get_mm_list(memcg); 5698 5699 if (!mm_list) 5700 return; 5701 5702 INIT_LIST_HEAD(&mm_list->fifo); 5703 spin_lock_init(&mm_list->lock); 5704 } 5705 5706 void lru_gen_exit_memcg(struct mem_cgroup *memcg) 5707 { 5708 int i; 5709 int nid; 5710 struct lru_gen_mm_list *mm_list = get_mm_list(memcg); 5711 5712 VM_WARN_ON_ONCE(mm_list && !list_empty(&mm_list->fifo)); 5713 5714 for_each_node(nid) { 5715 struct lruvec *lruvec = get_lruvec(memcg, nid); 5716 struct lru_gen_mm_state *mm_state = get_mm_state(lruvec); 5717 5718 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0, 5719 sizeof(lruvec->lrugen.nr_pages))); 5720 5721 lruvec->lrugen.list.next = LIST_POISON1; 5722 5723 if (!mm_state) 5724 continue; 5725 5726 for (i = 0; i < NR_BLOOM_FILTERS; i++) { 5727 bitmap_free(mm_state->filters[i]); 5728 mm_state->filters[i] = NULL; 5729 } 5730 } 5731 } 5732 5733 #endif /* CONFIG_MEMCG */ 5734 5735 static int __init init_lru_gen(void) 5736 { 5737 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS); 5738 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS); 5739 5740 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group)) 5741 pr_err("lru_gen: failed to create sysfs group\n"); 5742 5743 debugfs_create_file_aux_num("lru_gen", 0644, NULL, NULL, false, 5744 &lru_gen_rw_fops); 5745 debugfs_create_file_aux_num("lru_gen_full", 0444, NULL, NULL, true, 5746 &lru_gen_ro_fops); 5747 5748 return 0; 5749 }; 5750 late_initcall(init_lru_gen); 5751 5752 #else /* !CONFIG_LRU_GEN */ 5753 5754 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc) 5755 { 5756 BUILD_BUG(); 5757 } 5758 5759 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc) 5760 { 5761 BUILD_BUG(); 5762 } 5763 5764 static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc) 5765 { 5766 BUILD_BUG(); 5767 } 5768 5769 #endif /* CONFIG_LRU_GEN */ 5770 5771 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc) 5772 { 5773 unsigned long nr[NR_LRU_LISTS]; 5774 unsigned long targets[NR_LRU_LISTS]; 5775 unsigned long nr_to_scan; 5776 enum lru_list lru; 5777 unsigned long nr_reclaimed = 0; 5778 unsigned long nr_to_reclaim = sc->nr_to_reclaim; 5779 bool proportional_reclaim; 5780 struct blk_plug plug; 5781 5782 if (lru_gen_enabled() && !root_reclaim(sc)) { 5783 lru_gen_shrink_lruvec(lruvec, sc); 5784 return; 5785 } 5786 5787 get_scan_count(lruvec, sc, nr); 5788 5789 /* Record the original scan target for proportional adjustments later */ 5790 memcpy(targets, nr, sizeof(nr)); 5791 5792 /* 5793 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal 5794 * event that can occur when there is little memory pressure e.g. 5795 * multiple streaming readers/writers. Hence, we do not abort scanning 5796 * when the requested number of pages are reclaimed when scanning at 5797 * DEF_PRIORITY on the assumption that the fact we are direct 5798 * reclaiming implies that kswapd is not keeping up and it is best to 5799 * do a batch of work at once. For memcg reclaim one check is made to 5800 * abort proportional reclaim if either the file or anon lru has already 5801 * dropped to zero at the first pass. 5802 */ 5803 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() && 5804 sc->priority == DEF_PRIORITY); 5805 5806 blk_start_plug(&plug); 5807 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] || 5808 nr[LRU_INACTIVE_FILE]) { 5809 unsigned long nr_anon, nr_file, percentage; 5810 unsigned long nr_scanned; 5811 5812 for_each_evictable_lru(lru) { 5813 if (nr[lru]) { 5814 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX); 5815 nr[lru] -= nr_to_scan; 5816 5817 nr_reclaimed += shrink_list(lru, nr_to_scan, 5818 lruvec, sc); 5819 } 5820 } 5821 5822 cond_resched(); 5823 5824 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim) 5825 continue; 5826 5827 /* 5828 * For kswapd and memcg, reclaim at least the number of pages 5829 * requested. Ensure that the anon and file LRUs are scanned 5830 * proportionally what was requested by get_scan_count(). We 5831 * stop reclaiming one LRU and reduce the amount scanning 5832 * proportional to the original scan target. 5833 */ 5834 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE]; 5835 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON]; 5836 5837 /* 5838 * It's just vindictive to attack the larger once the smaller 5839 * has gone to zero. And given the way we stop scanning the 5840 * smaller below, this makes sure that we only make one nudge 5841 * towards proportionality once we've got nr_to_reclaim. 5842 */ 5843 if (!nr_file || !nr_anon) 5844 break; 5845 5846 if (nr_file > nr_anon) { 5847 unsigned long scan_target = targets[LRU_INACTIVE_ANON] + 5848 targets[LRU_ACTIVE_ANON] + 1; 5849 lru = LRU_BASE; 5850 percentage = nr_anon * 100 / scan_target; 5851 } else { 5852 unsigned long scan_target = targets[LRU_INACTIVE_FILE] + 5853 targets[LRU_ACTIVE_FILE] + 1; 5854 lru = LRU_FILE; 5855 percentage = nr_file * 100 / scan_target; 5856 } 5857 5858 /* Stop scanning the smaller of the LRU */ 5859 nr[lru] = 0; 5860 nr[lru + LRU_ACTIVE] = 0; 5861 5862 /* 5863 * Recalculate the other LRU scan count based on its original 5864 * scan target and the percentage scanning already complete 5865 */ 5866 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE; 5867 nr_scanned = targets[lru] - nr[lru]; 5868 nr[lru] = targets[lru] * (100 - percentage) / 100; 5869 nr[lru] -= min(nr[lru], nr_scanned); 5870 5871 lru += LRU_ACTIVE; 5872 nr_scanned = targets[lru] - nr[lru]; 5873 nr[lru] = targets[lru] * (100 - percentage) / 100; 5874 nr[lru] -= min(nr[lru], nr_scanned); 5875 } 5876 blk_finish_plug(&plug); 5877 sc->nr_reclaimed += nr_reclaimed; 5878 5879 /* 5880 * Even if we did not try to evict anon pages at all, we want to 5881 * rebalance the anon lru active/inactive ratio. 5882 */ 5883 if (can_age_anon_pages(lruvec, sc) && 5884 inactive_is_low(lruvec, LRU_INACTIVE_ANON)) 5885 shrink_active_list(SWAP_CLUSTER_MAX, lruvec, 5886 sc, LRU_ACTIVE_ANON); 5887 } 5888 5889 /* Use reclaim/compaction for costly allocs or under memory pressure */ 5890 static bool in_reclaim_compaction(struct scan_control *sc) 5891 { 5892 if (gfp_compaction_allowed(sc->gfp_mask) && sc->order && 5893 (sc->order > PAGE_ALLOC_COSTLY_ORDER || 5894 sc->priority < DEF_PRIORITY - 2)) 5895 return true; 5896 5897 return false; 5898 } 5899 5900 /* 5901 * Reclaim/compaction is used for high-order allocation requests. It reclaims 5902 * order-0 pages before compacting the zone. should_continue_reclaim() returns 5903 * true if more pages should be reclaimed such that when the page allocator 5904 * calls try_to_compact_pages() that it will have enough free pages to succeed. 5905 * It will give up earlier than that if there is difficulty reclaiming pages. 5906 */ 5907 static inline bool should_continue_reclaim(struct pglist_data *pgdat, 5908 unsigned long nr_reclaimed, 5909 struct scan_control *sc) 5910 { 5911 unsigned long pages_for_compaction; 5912 unsigned long inactive_lru_pages; 5913 int z; 5914 struct zone *zone; 5915 5916 /* If not in reclaim/compaction mode, stop */ 5917 if (!in_reclaim_compaction(sc)) 5918 return false; 5919 5920 /* 5921 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX 5922 * number of pages that were scanned. This will return to the caller 5923 * with the risk reclaim/compaction and the resulting allocation attempt 5924 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL 5925 * allocations through requiring that the full LRU list has been scanned 5926 * first, by assuming that zero delta of sc->nr_scanned means full LRU 5927 * scan, but that approximation was wrong, and there were corner cases 5928 * where always a non-zero amount of pages were scanned. 5929 */ 5930 if (!nr_reclaimed) 5931 return false; 5932 5933 /* If compaction would go ahead or the allocation would succeed, stop */ 5934 for_each_managed_zone_pgdat(zone, pgdat, z, sc->reclaim_idx) { 5935 unsigned long watermark = min_wmark_pages(zone); 5936 5937 /* Allocation can already succeed, nothing to do */ 5938 if (zone_watermark_ok(zone, sc->order, watermark, 5939 sc->reclaim_idx, 0)) 5940 return false; 5941 5942 if (compaction_suitable(zone, sc->order, watermark, 5943 sc->reclaim_idx)) 5944 return false; 5945 } 5946 5947 /* 5948 * If we have not reclaimed enough pages for compaction and the 5949 * inactive lists are large enough, continue reclaiming 5950 */ 5951 pages_for_compaction = compact_gap(sc->order); 5952 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE); 5953 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc)) 5954 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON); 5955 5956 return inactive_lru_pages > pages_for_compaction; 5957 } 5958 5959 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc) 5960 { 5961 struct mem_cgroup *target_memcg = sc->target_mem_cgroup; 5962 struct mem_cgroup_reclaim_cookie reclaim = { 5963 .pgdat = pgdat, 5964 }; 5965 struct mem_cgroup_reclaim_cookie *partial = &reclaim; 5966 struct mem_cgroup *memcg; 5967 5968 /* 5969 * In most cases, direct reclaimers can do partial walks 5970 * through the cgroup tree, using an iterator state that 5971 * persists across invocations. This strikes a balance between 5972 * fairness and allocation latency. 5973 * 5974 * For kswapd, reliable forward progress is more important 5975 * than a quick return to idle. Always do full walks. 5976 */ 5977 if (current_is_kswapd() || sc->memcg_full_walk) 5978 partial = NULL; 5979 5980 memcg = mem_cgroup_iter(target_memcg, NULL, partial); 5981 do { 5982 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat); 5983 unsigned long reclaimed; 5984 unsigned long scanned; 5985 5986 /* 5987 * This loop can become CPU-bound when target memcgs 5988 * aren't eligible for reclaim - either because they 5989 * don't have any reclaimable pages, or because their 5990 * memory is explicitly protected. Avoid soft lockups. 5991 */ 5992 cond_resched(); 5993 5994 mem_cgroup_calculate_protection(target_memcg, memcg); 5995 5996 if (mem_cgroup_below_min(target_memcg, memcg)) { 5997 /* 5998 * Hard protection. 5999 * If there is no reclaimable memory, OOM. 6000 */ 6001 continue; 6002 } else if (mem_cgroup_below_low(target_memcg, memcg)) { 6003 /* 6004 * Soft protection. 6005 * Respect the protection only as long as 6006 * there is an unprotected supply 6007 * of reclaimable memory from other cgroups. 6008 */ 6009 if (!sc->memcg_low_reclaim) { 6010 sc->memcg_low_skipped = 1; 6011 continue; 6012 } 6013 memcg_memory_event(memcg, MEMCG_LOW); 6014 } 6015 6016 reclaimed = sc->nr_reclaimed; 6017 scanned = sc->nr_scanned; 6018 6019 shrink_lruvec(lruvec, sc); 6020 6021 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, 6022 sc->priority); 6023 6024 /* Record the group's reclaim efficiency */ 6025 if (!sc->proactive) 6026 vmpressure(sc->gfp_mask, memcg, false, 6027 sc->nr_scanned - scanned, 6028 sc->nr_reclaimed - reclaimed); 6029 6030 /* If partial walks are allowed, bail once goal is reached */ 6031 if (partial && sc->nr_reclaimed >= sc->nr_to_reclaim) { 6032 mem_cgroup_iter_break(target_memcg, memcg); 6033 break; 6034 } 6035 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, partial))); 6036 } 6037 6038 static void shrink_node(pg_data_t *pgdat, struct scan_control *sc) 6039 { 6040 unsigned long nr_reclaimed, nr_scanned, nr_node_reclaimed; 6041 struct lruvec *target_lruvec; 6042 bool reclaimable = false; 6043 6044 if (lru_gen_enabled() && root_reclaim(sc)) { 6045 memset(&sc->nr, 0, sizeof(sc->nr)); 6046 lru_gen_shrink_node(pgdat, sc); 6047 return; 6048 } 6049 6050 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat); 6051 6052 again: 6053 memset(&sc->nr, 0, sizeof(sc->nr)); 6054 6055 nr_reclaimed = sc->nr_reclaimed; 6056 nr_scanned = sc->nr_scanned; 6057 6058 prepare_scan_control(pgdat, sc); 6059 6060 shrink_node_memcgs(pgdat, sc); 6061 6062 flush_reclaim_state(sc); 6063 6064 nr_node_reclaimed = sc->nr_reclaimed - nr_reclaimed; 6065 6066 /* Record the subtree's reclaim efficiency */ 6067 if (!sc->proactive) 6068 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true, 6069 sc->nr_scanned - nr_scanned, nr_node_reclaimed); 6070 6071 if (nr_node_reclaimed) 6072 reclaimable = true; 6073 6074 if (current_is_kswapd()) { 6075 /* 6076 * If reclaim is isolating dirty pages under writeback, 6077 * it implies that the long-lived page allocation rate 6078 * is exceeding the page laundering rate. Either the 6079 * global limits are not being effective at throttling 6080 * processes due to the page distribution throughout 6081 * zones or there is heavy usage of a slow backing 6082 * device. The only option is to throttle from reclaim 6083 * context which is not ideal as there is no guarantee 6084 * the dirtying process is throttled in the same way 6085 * balance_dirty_pages() manages. 6086 * 6087 * Once a node is flagged PGDAT_WRITEBACK, kswapd will 6088 * count the number of pages under pages flagged for 6089 * immediate reclaim and stall if any are encountered 6090 * in the nr_immediate check below. 6091 */ 6092 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken) 6093 set_bit(PGDAT_WRITEBACK, &pgdat->flags); 6094 6095 /* 6096 * If kswapd scans pages marked for immediate 6097 * reclaim and under writeback (nr_immediate), it 6098 * implies that pages are cycling through the LRU 6099 * faster than they are written so forcibly stall 6100 * until some pages complete writeback. 6101 */ 6102 if (sc->nr.immediate) 6103 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK); 6104 } 6105 6106 /* 6107 * Tag a node/memcg as congested if all the dirty pages were marked 6108 * for writeback and immediate reclaim (counted in nr.congested). 6109 * 6110 * Legacy memcg will stall in page writeback so avoid forcibly 6111 * stalling in reclaim_throttle(). 6112 */ 6113 if (sc->nr.dirty && sc->nr.dirty == sc->nr.congested) { 6114 if (cgroup_reclaim(sc) && writeback_throttling_sane(sc)) 6115 set_bit(LRUVEC_CGROUP_CONGESTED, &target_lruvec->flags); 6116 6117 if (current_is_kswapd()) 6118 set_bit(LRUVEC_NODE_CONGESTED, &target_lruvec->flags); 6119 } 6120 6121 /* 6122 * Stall direct reclaim for IO completions if the lruvec is 6123 * node is congested. Allow kswapd to continue until it 6124 * starts encountering unqueued dirty pages or cycling through 6125 * the LRU too quickly. 6126 */ 6127 if (!current_is_kswapd() && current_may_throttle() && 6128 !sc->hibernation_mode && 6129 (test_bit(LRUVEC_CGROUP_CONGESTED, &target_lruvec->flags) || 6130 test_bit(LRUVEC_NODE_CONGESTED, &target_lruvec->flags))) 6131 reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED); 6132 6133 if (should_continue_reclaim(pgdat, nr_node_reclaimed, sc)) 6134 goto again; 6135 6136 /* 6137 * Kswapd gives up on balancing particular nodes after too 6138 * many failures to reclaim anything from them and goes to 6139 * sleep. On reclaim progress, reset the failure counter. A 6140 * successful direct reclaim run will revive a dormant kswapd. 6141 */ 6142 if (reclaimable) 6143 atomic_set(&pgdat->kswapd_failures, 0); 6144 else if (sc->cache_trim_mode) 6145 sc->cache_trim_mode_failed = 1; 6146 } 6147 6148 /* 6149 * Returns true if compaction should go ahead for a costly-order request, or 6150 * the allocation would already succeed without compaction. Return false if we 6151 * should reclaim first. 6152 */ 6153 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc) 6154 { 6155 unsigned long watermark; 6156 6157 if (!gfp_compaction_allowed(sc->gfp_mask)) 6158 return false; 6159 6160 /* Allocation can already succeed, nothing to do */ 6161 if (zone_watermark_ok(zone, sc->order, min_wmark_pages(zone), 6162 sc->reclaim_idx, 0)) 6163 return true; 6164 6165 /* 6166 * Direct reclaim usually targets the min watermark, but compaction 6167 * takes time to run and there are potentially other callers using the 6168 * pages just freed. So target a higher buffer to give compaction a 6169 * reasonable chance of completing and allocating the pages. 6170 * 6171 * Note that we won't actually reclaim the whole buffer in one attempt 6172 * as the target watermark in should_continue_reclaim() is lower. But if 6173 * we are already above the high+gap watermark, don't reclaim at all. 6174 */ 6175 watermark = high_wmark_pages(zone); 6176 if (compaction_suitable(zone, sc->order, watermark, sc->reclaim_idx)) 6177 return true; 6178 6179 return false; 6180 } 6181 6182 static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc) 6183 { 6184 /* 6185 * If reclaim is making progress greater than 12% efficiency then 6186 * wake all the NOPROGRESS throttled tasks. 6187 */ 6188 if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) { 6189 wait_queue_head_t *wqh; 6190 6191 wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS]; 6192 if (waitqueue_active(wqh)) 6193 wake_up(wqh); 6194 6195 return; 6196 } 6197 6198 /* 6199 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will 6200 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages 6201 * under writeback and marked for immediate reclaim at the tail of the 6202 * LRU. 6203 */ 6204 if (current_is_kswapd() || cgroup_reclaim(sc)) 6205 return; 6206 6207 /* Throttle if making no progress at high prioities. */ 6208 if (sc->priority == 1 && !sc->nr_reclaimed) 6209 reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS); 6210 } 6211 6212 /* 6213 * This is the direct reclaim path, for page-allocating processes. We only 6214 * try to reclaim pages from zones which will satisfy the caller's allocation 6215 * request. 6216 * 6217 * If a zone is deemed to be full of pinned pages then just give it a light 6218 * scan then give up on it. 6219 */ 6220 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc) 6221 { 6222 struct zoneref *z; 6223 struct zone *zone; 6224 unsigned long nr_soft_reclaimed; 6225 unsigned long nr_soft_scanned; 6226 gfp_t orig_mask; 6227 pg_data_t *last_pgdat = NULL; 6228 pg_data_t *first_pgdat = NULL; 6229 6230 /* 6231 * If the number of buffer_heads in the machine exceeds the maximum 6232 * allowed level, force direct reclaim to scan the highmem zone as 6233 * highmem pages could be pinning lowmem pages storing buffer_heads 6234 */ 6235 orig_mask = sc->gfp_mask; 6236 if (buffer_heads_over_limit) { 6237 sc->gfp_mask |= __GFP_HIGHMEM; 6238 sc->reclaim_idx = gfp_zone(sc->gfp_mask); 6239 } 6240 6241 for_each_zone_zonelist_nodemask(zone, z, zonelist, 6242 sc->reclaim_idx, sc->nodemask) { 6243 /* 6244 * Take care memory controller reclaiming has small influence 6245 * to global LRU. 6246 */ 6247 if (!cgroup_reclaim(sc)) { 6248 if (!cpuset_zone_allowed(zone, 6249 GFP_KERNEL | __GFP_HARDWALL)) 6250 continue; 6251 6252 /* 6253 * If we already have plenty of memory free for 6254 * compaction in this zone, don't free any more. 6255 * Even though compaction is invoked for any 6256 * non-zero order, only frequent costly order 6257 * reclamation is disruptive enough to become a 6258 * noticeable problem, like transparent huge 6259 * page allocations. 6260 */ 6261 if (IS_ENABLED(CONFIG_COMPACTION) && 6262 sc->order > PAGE_ALLOC_COSTLY_ORDER && 6263 compaction_ready(zone, sc)) { 6264 sc->compaction_ready = true; 6265 continue; 6266 } 6267 6268 /* 6269 * Shrink each node in the zonelist once. If the 6270 * zonelist is ordered by zone (not the default) then a 6271 * node may be shrunk multiple times but in that case 6272 * the user prefers lower zones being preserved. 6273 */ 6274 if (zone->zone_pgdat == last_pgdat) 6275 continue; 6276 6277 /* 6278 * This steals pages from memory cgroups over softlimit 6279 * and returns the number of reclaimed pages and 6280 * scanned pages. This works for global memory pressure 6281 * and balancing, not for a memcg's limit. 6282 */ 6283 nr_soft_scanned = 0; 6284 nr_soft_reclaimed = memcg1_soft_limit_reclaim(zone->zone_pgdat, 6285 sc->order, sc->gfp_mask, 6286 &nr_soft_scanned); 6287 sc->nr_reclaimed += nr_soft_reclaimed; 6288 sc->nr_scanned += nr_soft_scanned; 6289 /* need some check for avoid more shrink_zone() */ 6290 } 6291 6292 if (!first_pgdat) 6293 first_pgdat = zone->zone_pgdat; 6294 6295 /* See comment about same check for global reclaim above */ 6296 if (zone->zone_pgdat == last_pgdat) 6297 continue; 6298 last_pgdat = zone->zone_pgdat; 6299 shrink_node(zone->zone_pgdat, sc); 6300 } 6301 6302 if (first_pgdat) 6303 consider_reclaim_throttle(first_pgdat, sc); 6304 6305 /* 6306 * Restore to original mask to avoid the impact on the caller if we 6307 * promoted it to __GFP_HIGHMEM. 6308 */ 6309 sc->gfp_mask = orig_mask; 6310 } 6311 6312 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat) 6313 { 6314 struct lruvec *target_lruvec; 6315 unsigned long refaults; 6316 6317 if (lru_gen_enabled()) 6318 return; 6319 6320 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat); 6321 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON); 6322 target_lruvec->refaults[WORKINGSET_ANON] = refaults; 6323 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE); 6324 target_lruvec->refaults[WORKINGSET_FILE] = refaults; 6325 } 6326 6327 /* 6328 * This is the main entry point to direct page reclaim. 6329 * 6330 * If a full scan of the inactive list fails to free enough memory then we 6331 * are "out of memory" and something needs to be killed. 6332 * 6333 * If the caller is !__GFP_FS then the probability of a failure is reasonably 6334 * high - the zone may be full of dirty or under-writeback pages, which this 6335 * caller can't do much about. We kick the writeback threads and take explicit 6336 * naps in the hope that some of these pages can be written. But if the 6337 * allocating task holds filesystem locks which prevent writeout this might not 6338 * work, and the allocation attempt will fail. 6339 * 6340 * returns: 0, if no pages reclaimed 6341 * else, the number of pages reclaimed 6342 */ 6343 static unsigned long do_try_to_free_pages(struct zonelist *zonelist, 6344 struct scan_control *sc) 6345 { 6346 int initial_priority = sc->priority; 6347 pg_data_t *last_pgdat; 6348 struct zoneref *z; 6349 struct zone *zone; 6350 retry: 6351 delayacct_freepages_start(); 6352 6353 if (!cgroup_reclaim(sc)) 6354 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1); 6355 6356 do { 6357 if (!sc->proactive) 6358 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup, 6359 sc->priority); 6360 sc->nr_scanned = 0; 6361 shrink_zones(zonelist, sc); 6362 6363 if (sc->nr_reclaimed >= sc->nr_to_reclaim) 6364 break; 6365 6366 if (sc->compaction_ready) 6367 break; 6368 } while (--sc->priority >= 0); 6369 6370 last_pgdat = NULL; 6371 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx, 6372 sc->nodemask) { 6373 if (zone->zone_pgdat == last_pgdat) 6374 continue; 6375 last_pgdat = zone->zone_pgdat; 6376 6377 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat); 6378 6379 if (cgroup_reclaim(sc)) { 6380 struct lruvec *lruvec; 6381 6382 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, 6383 zone->zone_pgdat); 6384 clear_bit(LRUVEC_CGROUP_CONGESTED, &lruvec->flags); 6385 } 6386 } 6387 6388 delayacct_freepages_end(); 6389 6390 if (sc->nr_reclaimed) 6391 return sc->nr_reclaimed; 6392 6393 /* Aborted reclaim to try compaction? don't OOM, then */ 6394 if (sc->compaction_ready) 6395 return 1; 6396 6397 /* 6398 * In most cases, direct reclaimers can do partial walks 6399 * through the cgroup tree to meet the reclaim goal while 6400 * keeping latency low. Since the iterator state is shared 6401 * among all direct reclaim invocations (to retain fairness 6402 * among cgroups), though, high concurrency can result in 6403 * individual threads not seeing enough cgroups to make 6404 * meaningful forward progress. Avoid false OOMs in this case. 6405 */ 6406 if (!sc->memcg_full_walk) { 6407 sc->priority = initial_priority; 6408 sc->memcg_full_walk = 1; 6409 goto retry; 6410 } 6411 6412 /* 6413 * We make inactive:active ratio decisions based on the node's 6414 * composition of memory, but a restrictive reclaim_idx or a 6415 * memory.low cgroup setting can exempt large amounts of 6416 * memory from reclaim. Neither of which are very common, so 6417 * instead of doing costly eligibility calculations of the 6418 * entire cgroup subtree up front, we assume the estimates are 6419 * good, and retry with forcible deactivation if that fails. 6420 */ 6421 if (sc->skipped_deactivate) { 6422 sc->priority = initial_priority; 6423 sc->force_deactivate = 1; 6424 sc->skipped_deactivate = 0; 6425 goto retry; 6426 } 6427 6428 /* Untapped cgroup reserves? Don't OOM, retry. */ 6429 if (sc->memcg_low_skipped) { 6430 sc->priority = initial_priority; 6431 sc->force_deactivate = 0; 6432 sc->memcg_low_reclaim = 1; 6433 sc->memcg_low_skipped = 0; 6434 goto retry; 6435 } 6436 6437 return 0; 6438 } 6439 6440 static bool allow_direct_reclaim(pg_data_t *pgdat) 6441 { 6442 struct zone *zone; 6443 unsigned long pfmemalloc_reserve = 0; 6444 unsigned long free_pages = 0; 6445 int i; 6446 bool wmark_ok; 6447 6448 if (atomic_read(&pgdat->kswapd_failures) >= MAX_RECLAIM_RETRIES) 6449 return true; 6450 6451 for_each_managed_zone_pgdat(zone, pgdat, i, ZONE_NORMAL) { 6452 if (!zone_reclaimable_pages(zone) && zone_page_state_snapshot(zone, NR_FREE_PAGES)) 6453 continue; 6454 6455 pfmemalloc_reserve += min_wmark_pages(zone); 6456 free_pages += zone_page_state_snapshot(zone, NR_FREE_PAGES); 6457 } 6458 6459 /* If there are no reserves (unexpected config) then do not throttle */ 6460 if (!pfmemalloc_reserve) 6461 return true; 6462 6463 wmark_ok = free_pages > pfmemalloc_reserve / 2; 6464 6465 /* kswapd must be awake if processes are being throttled */ 6466 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) { 6467 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL) 6468 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL); 6469 6470 wake_up_interruptible(&pgdat->kswapd_wait); 6471 } 6472 6473 return wmark_ok; 6474 } 6475 6476 /* 6477 * Throttle direct reclaimers if backing storage is backed by the network 6478 * and the PFMEMALLOC reserve for the preferred node is getting dangerously 6479 * depleted. kswapd will continue to make progress and wake the processes 6480 * when the low watermark is reached. 6481 * 6482 * Returns true if a fatal signal was delivered during throttling. If this 6483 * happens, the page allocator should not consider triggering the OOM killer. 6484 */ 6485 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist, 6486 nodemask_t *nodemask) 6487 { 6488 struct zoneref *z; 6489 struct zone *zone; 6490 pg_data_t *pgdat = NULL; 6491 6492 /* 6493 * Kernel threads should not be throttled as they may be indirectly 6494 * responsible for cleaning pages necessary for reclaim to make forward 6495 * progress. kjournald for example may enter direct reclaim while 6496 * committing a transaction where throttling it could forcing other 6497 * processes to block on log_wait_commit(). 6498 */ 6499 if (current->flags & PF_KTHREAD) 6500 goto out; 6501 6502 /* 6503 * If a fatal signal is pending, this process should not throttle. 6504 * It should return quickly so it can exit and free its memory 6505 */ 6506 if (fatal_signal_pending(current)) 6507 goto out; 6508 6509 /* 6510 * Check if the pfmemalloc reserves are ok by finding the first node 6511 * with a usable ZONE_NORMAL or lower zone. The expectation is that 6512 * GFP_KERNEL will be required for allocating network buffers when 6513 * swapping over the network so ZONE_HIGHMEM is unusable. 6514 * 6515 * Throttling is based on the first usable node and throttled processes 6516 * wait on a queue until kswapd makes progress and wakes them. There 6517 * is an affinity then between processes waking up and where reclaim 6518 * progress has been made assuming the process wakes on the same node. 6519 * More importantly, processes running on remote nodes will not compete 6520 * for remote pfmemalloc reserves and processes on different nodes 6521 * should make reasonable progress. 6522 */ 6523 for_each_zone_zonelist_nodemask(zone, z, zonelist, 6524 gfp_zone(gfp_mask), nodemask) { 6525 if (zone_idx(zone) > ZONE_NORMAL) 6526 continue; 6527 6528 /* Throttle based on the first usable node */ 6529 pgdat = zone->zone_pgdat; 6530 if (allow_direct_reclaim(pgdat)) 6531 goto out; 6532 break; 6533 } 6534 6535 /* If no zone was usable by the allocation flags then do not throttle */ 6536 if (!pgdat) 6537 goto out; 6538 6539 /* Account for the throttling */ 6540 count_vm_event(PGSCAN_DIRECT_THROTTLE); 6541 6542 /* 6543 * If the caller cannot enter the filesystem, it's possible that it 6544 * is due to the caller holding an FS lock or performing a journal 6545 * transaction in the case of a filesystem like ext[3|4]. In this case, 6546 * it is not safe to block on pfmemalloc_wait as kswapd could be 6547 * blocked waiting on the same lock. Instead, throttle for up to a 6548 * second before continuing. 6549 */ 6550 if (!(gfp_mask & __GFP_FS)) 6551 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait, 6552 allow_direct_reclaim(pgdat), HZ); 6553 else 6554 /* Throttle until kswapd wakes the process */ 6555 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait, 6556 allow_direct_reclaim(pgdat)); 6557 6558 if (fatal_signal_pending(current)) 6559 return true; 6560 6561 out: 6562 return false; 6563 } 6564 6565 unsigned long try_to_free_pages(struct zonelist *zonelist, int order, 6566 gfp_t gfp_mask, nodemask_t *nodemask) 6567 { 6568 unsigned long nr_reclaimed; 6569 struct scan_control sc = { 6570 .nr_to_reclaim = SWAP_CLUSTER_MAX, 6571 .gfp_mask = current_gfp_context(gfp_mask), 6572 .reclaim_idx = gfp_zone(gfp_mask), 6573 .order = order, 6574 .nodemask = nodemask, 6575 .priority = DEF_PRIORITY, 6576 .may_writepage = 1, 6577 .may_unmap = 1, 6578 .may_swap = 1, 6579 }; 6580 6581 /* 6582 * scan_control uses s8 fields for order, priority, and reclaim_idx. 6583 * Confirm they are large enough for max values. 6584 */ 6585 BUILD_BUG_ON(MAX_PAGE_ORDER >= S8_MAX); 6586 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX); 6587 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX); 6588 6589 /* 6590 * Do not enter reclaim if fatal signal was delivered while throttled. 6591 * 1 is returned so that the page allocator does not OOM kill at this 6592 * point. 6593 */ 6594 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask)) 6595 return 1; 6596 6597 set_task_reclaim_state(current, &sc.reclaim_state); 6598 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask); 6599 6600 nr_reclaimed = do_try_to_free_pages(zonelist, &sc); 6601 6602 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed); 6603 set_task_reclaim_state(current, NULL); 6604 6605 return nr_reclaimed; 6606 } 6607 6608 #ifdef CONFIG_MEMCG 6609 6610 /* Only used by soft limit reclaim. Do not reuse for anything else. */ 6611 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg, 6612 gfp_t gfp_mask, bool noswap, 6613 pg_data_t *pgdat, 6614 unsigned long *nr_scanned) 6615 { 6616 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat); 6617 struct scan_control sc = { 6618 .nr_to_reclaim = SWAP_CLUSTER_MAX, 6619 .target_mem_cgroup = memcg, 6620 .may_writepage = 1, 6621 .may_unmap = 1, 6622 .reclaim_idx = MAX_NR_ZONES - 1, 6623 .may_swap = !noswap, 6624 }; 6625 6626 WARN_ON_ONCE(!current->reclaim_state); 6627 6628 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) | 6629 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK); 6630 6631 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order, 6632 sc.gfp_mask); 6633 6634 /* 6635 * NOTE: Although we can get the priority field, using it 6636 * here is not a good idea, since it limits the pages we can scan. 6637 * if we don't reclaim here, the shrink_node from balance_pgdat 6638 * will pick up pages from other mem cgroup's as well. We hack 6639 * the priority and make it zero. 6640 */ 6641 shrink_lruvec(lruvec, &sc); 6642 6643 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed); 6644 6645 *nr_scanned = sc.nr_scanned; 6646 6647 return sc.nr_reclaimed; 6648 } 6649 6650 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg, 6651 unsigned long nr_pages, 6652 gfp_t gfp_mask, 6653 unsigned int reclaim_options, 6654 int *swappiness) 6655 { 6656 unsigned long nr_reclaimed; 6657 unsigned int noreclaim_flag; 6658 struct scan_control sc = { 6659 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX), 6660 .proactive_swappiness = swappiness, 6661 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) | 6662 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK), 6663 .reclaim_idx = MAX_NR_ZONES - 1, 6664 .target_mem_cgroup = memcg, 6665 .priority = DEF_PRIORITY, 6666 .may_writepage = 1, 6667 .may_unmap = 1, 6668 .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP), 6669 .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE), 6670 }; 6671 /* 6672 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put 6673 * equal pressure on all the nodes. This is based on the assumption that 6674 * the reclaim does not bail out early. 6675 */ 6676 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask); 6677 6678 set_task_reclaim_state(current, &sc.reclaim_state); 6679 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask); 6680 noreclaim_flag = memalloc_noreclaim_save(); 6681 6682 nr_reclaimed = do_try_to_free_pages(zonelist, &sc); 6683 6684 memalloc_noreclaim_restore(noreclaim_flag); 6685 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed); 6686 set_task_reclaim_state(current, NULL); 6687 6688 return nr_reclaimed; 6689 } 6690 #else 6691 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg, 6692 unsigned long nr_pages, 6693 gfp_t gfp_mask, 6694 unsigned int reclaim_options, 6695 int *swappiness) 6696 { 6697 return 0; 6698 } 6699 #endif 6700 6701 static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc) 6702 { 6703 struct mem_cgroup *memcg; 6704 struct lruvec *lruvec; 6705 6706 if (lru_gen_enabled()) { 6707 lru_gen_age_node(pgdat, sc); 6708 return; 6709 } 6710 6711 lruvec = mem_cgroup_lruvec(NULL, pgdat); 6712 if (!can_age_anon_pages(lruvec, sc)) 6713 return; 6714 6715 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON)) 6716 return; 6717 6718 memcg = mem_cgroup_iter(NULL, NULL, NULL); 6719 do { 6720 lruvec = mem_cgroup_lruvec(memcg, pgdat); 6721 shrink_active_list(SWAP_CLUSTER_MAX, lruvec, 6722 sc, LRU_ACTIVE_ANON); 6723 memcg = mem_cgroup_iter(NULL, memcg, NULL); 6724 } while (memcg); 6725 } 6726 6727 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx) 6728 { 6729 int i; 6730 struct zone *zone; 6731 6732 /* 6733 * Check for watermark boosts top-down as the higher zones 6734 * are more likely to be boosted. Both watermarks and boosts 6735 * should not be checked at the same time as reclaim would 6736 * start prematurely when there is no boosting and a lower 6737 * zone is balanced. 6738 */ 6739 for (i = highest_zoneidx; i >= 0; i--) { 6740 zone = pgdat->node_zones + i; 6741 if (!managed_zone(zone)) 6742 continue; 6743 6744 if (zone->watermark_boost) 6745 return true; 6746 } 6747 6748 return false; 6749 } 6750 6751 /* 6752 * Returns true if there is an eligible zone balanced for the request order 6753 * and highest_zoneidx 6754 */ 6755 static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx) 6756 { 6757 int i; 6758 unsigned long mark = -1; 6759 struct zone *zone; 6760 6761 /* 6762 * Check watermarks bottom-up as lower zones are more likely to 6763 * meet watermarks. 6764 */ 6765 for_each_managed_zone_pgdat(zone, pgdat, i, highest_zoneidx) { 6766 enum zone_stat_item item; 6767 unsigned long free_pages; 6768 6769 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) 6770 mark = promo_wmark_pages(zone); 6771 else 6772 mark = high_wmark_pages(zone); 6773 6774 /* 6775 * In defrag_mode, watermarks must be met in whole 6776 * blocks to avoid polluting allocator fallbacks. 6777 * 6778 * However, kswapd usually cannot accomplish this on 6779 * its own and needs kcompactd support. Once it's 6780 * reclaimed a compaction gap, and kswapd_shrink_node 6781 * has dropped order, simply ensure there are enough 6782 * base pages for compaction, wake kcompactd & sleep. 6783 */ 6784 if (defrag_mode && order) 6785 item = NR_FREE_PAGES_BLOCKS; 6786 else 6787 item = NR_FREE_PAGES; 6788 6789 /* 6790 * When there is a high number of CPUs in the system, 6791 * the cumulative error from the vmstat per-cpu cache 6792 * can blur the line between the watermarks. In that 6793 * case, be safe and get an accurate snapshot. 6794 * 6795 * TODO: NR_FREE_PAGES_BLOCKS moves in steps of 6796 * pageblock_nr_pages, while the vmstat pcp threshold 6797 * is limited to 125. On many configurations that 6798 * counter won't actually be per-cpu cached. But keep 6799 * things simple for now; revisit when somebody cares. 6800 */ 6801 free_pages = zone_page_state(zone, item); 6802 if (zone->percpu_drift_mark && free_pages < zone->percpu_drift_mark) 6803 free_pages = zone_page_state_snapshot(zone, item); 6804 6805 if (__zone_watermark_ok(zone, order, mark, highest_zoneidx, 6806 0, free_pages)) 6807 return true; 6808 } 6809 6810 /* 6811 * If a node has no managed zone within highest_zoneidx, it does not 6812 * need balancing by definition. This can happen if a zone-restricted 6813 * allocation tries to wake a remote kswapd. 6814 */ 6815 if (mark == -1) 6816 return true; 6817 6818 return false; 6819 } 6820 6821 /* Clear pgdat state for congested, dirty or under writeback. */ 6822 static void clear_pgdat_congested(pg_data_t *pgdat) 6823 { 6824 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat); 6825 6826 clear_bit(LRUVEC_NODE_CONGESTED, &lruvec->flags); 6827 clear_bit(LRUVEC_CGROUP_CONGESTED, &lruvec->flags); 6828 clear_bit(PGDAT_WRITEBACK, &pgdat->flags); 6829 } 6830 6831 /* 6832 * Prepare kswapd for sleeping. This verifies that there are no processes 6833 * waiting in throttle_direct_reclaim() and that watermarks have been met. 6834 * 6835 * Returns true if kswapd is ready to sleep 6836 */ 6837 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, 6838 int highest_zoneidx) 6839 { 6840 /* 6841 * The throttled processes are normally woken up in balance_pgdat() as 6842 * soon as allow_direct_reclaim() is true. But there is a potential 6843 * race between when kswapd checks the watermarks and a process gets 6844 * throttled. There is also a potential race if processes get 6845 * throttled, kswapd wakes, a large process exits thereby balancing the 6846 * zones, which causes kswapd to exit balance_pgdat() before reaching 6847 * the wake up checks. If kswapd is going to sleep, no process should 6848 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If 6849 * the wake up is premature, processes will wake kswapd and get 6850 * throttled again. The difference from wake ups in balance_pgdat() is 6851 * that here we are under prepare_to_wait(). 6852 */ 6853 if (waitqueue_active(&pgdat->pfmemalloc_wait)) 6854 wake_up_all(&pgdat->pfmemalloc_wait); 6855 6856 /* Hopeless node, leave it to direct reclaim */ 6857 if (atomic_read(&pgdat->kswapd_failures) >= MAX_RECLAIM_RETRIES) 6858 return true; 6859 6860 if (pgdat_balanced(pgdat, order, highest_zoneidx)) { 6861 clear_pgdat_congested(pgdat); 6862 return true; 6863 } 6864 6865 return false; 6866 } 6867 6868 /* 6869 * kswapd shrinks a node of pages that are at or below the highest usable 6870 * zone that is currently unbalanced. 6871 * 6872 * Returns true if kswapd scanned at least the requested number of pages to 6873 * reclaim or if the lack of progress was due to pages under writeback. 6874 * This is used to determine if the scanning priority needs to be raised. 6875 */ 6876 static bool kswapd_shrink_node(pg_data_t *pgdat, 6877 struct scan_control *sc) 6878 { 6879 struct zone *zone; 6880 int z; 6881 unsigned long nr_reclaimed = sc->nr_reclaimed; 6882 6883 /* Reclaim a number of pages proportional to the number of zones */ 6884 sc->nr_to_reclaim = 0; 6885 for_each_managed_zone_pgdat(zone, pgdat, z, sc->reclaim_idx) { 6886 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX); 6887 } 6888 6889 /* 6890 * Historically care was taken to put equal pressure on all zones but 6891 * now pressure is applied based on node LRU order. 6892 */ 6893 shrink_node(pgdat, sc); 6894 6895 /* 6896 * Fragmentation may mean that the system cannot be rebalanced for 6897 * high-order allocations. If twice the allocation size has been 6898 * reclaimed then recheck watermarks only at order-0 to prevent 6899 * excessive reclaim. Assume that a process requested a high-order 6900 * can direct reclaim/compact. 6901 */ 6902 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order)) 6903 sc->order = 0; 6904 6905 /* account for progress from mm_account_reclaimed_pages() */ 6906 return max(sc->nr_scanned, sc->nr_reclaimed - nr_reclaimed) >= sc->nr_to_reclaim; 6907 } 6908 6909 /* Page allocator PCP high watermark is lowered if reclaim is active. */ 6910 static inline void 6911 update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active) 6912 { 6913 int i; 6914 struct zone *zone; 6915 6916 for_each_managed_zone_pgdat(zone, pgdat, i, highest_zoneidx) { 6917 if (active) 6918 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags); 6919 else 6920 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags); 6921 } 6922 } 6923 6924 static inline void 6925 set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx) 6926 { 6927 update_reclaim_active(pgdat, highest_zoneidx, true); 6928 } 6929 6930 static inline void 6931 clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx) 6932 { 6933 update_reclaim_active(pgdat, highest_zoneidx, false); 6934 } 6935 6936 /* 6937 * For kswapd, balance_pgdat() will reclaim pages across a node from zones 6938 * that are eligible for use by the caller until at least one zone is 6939 * balanced. 6940 * 6941 * Returns the order kswapd finished reclaiming at. 6942 * 6943 * kswapd scans the zones in the highmem->normal->dma direction. It skips 6944 * zones which have free_pages > high_wmark_pages(zone), but once a zone is 6945 * found to have free_pages <= high_wmark_pages(zone), any page in that zone 6946 * or lower is eligible for reclaim until at least one usable zone is 6947 * balanced. 6948 */ 6949 static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx) 6950 { 6951 int i; 6952 unsigned long nr_soft_reclaimed; 6953 unsigned long nr_soft_scanned; 6954 unsigned long pflags; 6955 unsigned long nr_boost_reclaim; 6956 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, }; 6957 bool boosted; 6958 struct zone *zone; 6959 struct scan_control sc = { 6960 .gfp_mask = GFP_KERNEL, 6961 .order = order, 6962 .may_unmap = 1, 6963 }; 6964 6965 set_task_reclaim_state(current, &sc.reclaim_state); 6966 psi_memstall_enter(&pflags); 6967 __fs_reclaim_acquire(_THIS_IP_); 6968 6969 count_vm_event(PAGEOUTRUN); 6970 6971 /* 6972 * Account for the reclaim boost. Note that the zone boost is left in 6973 * place so that parallel allocations that are near the watermark will 6974 * stall or direct reclaim until kswapd is finished. 6975 */ 6976 nr_boost_reclaim = 0; 6977 for_each_managed_zone_pgdat(zone, pgdat, i, highest_zoneidx) { 6978 nr_boost_reclaim += zone->watermark_boost; 6979 zone_boosts[i] = zone->watermark_boost; 6980 } 6981 boosted = nr_boost_reclaim; 6982 6983 restart: 6984 set_reclaim_active(pgdat, highest_zoneidx); 6985 sc.priority = DEF_PRIORITY; 6986 do { 6987 unsigned long nr_reclaimed = sc.nr_reclaimed; 6988 bool raise_priority = true; 6989 bool balanced; 6990 bool ret; 6991 bool was_frozen; 6992 6993 sc.reclaim_idx = highest_zoneidx; 6994 6995 /* 6996 * If the number of buffer_heads exceeds the maximum allowed 6997 * then consider reclaiming from all zones. This has a dual 6998 * purpose -- on 64-bit systems it is expected that 6999 * buffer_heads are stripped during active rotation. On 32-bit 7000 * systems, highmem pages can pin lowmem memory and shrinking 7001 * buffers can relieve lowmem pressure. Reclaim may still not 7002 * go ahead if all eligible zones for the original allocation 7003 * request are balanced to avoid excessive reclaim from kswapd. 7004 */ 7005 if (buffer_heads_over_limit) { 7006 for (i = MAX_NR_ZONES - 1; i >= 0; i--) { 7007 zone = pgdat->node_zones + i; 7008 if (!managed_zone(zone)) 7009 continue; 7010 7011 sc.reclaim_idx = i; 7012 break; 7013 } 7014 } 7015 7016 /* 7017 * If the pgdat is imbalanced then ignore boosting and preserve 7018 * the watermarks for a later time and restart. Note that the 7019 * zone watermarks will be still reset at the end of balancing 7020 * on the grounds that the normal reclaim should be enough to 7021 * re-evaluate if boosting is required when kswapd next wakes. 7022 */ 7023 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx); 7024 if (!balanced && nr_boost_reclaim) { 7025 nr_boost_reclaim = 0; 7026 goto restart; 7027 } 7028 7029 /* 7030 * If boosting is not active then only reclaim if there are no 7031 * eligible zones. Note that sc.reclaim_idx is not used as 7032 * buffer_heads_over_limit may have adjusted it. 7033 */ 7034 if (!nr_boost_reclaim && balanced) 7035 goto out; 7036 7037 /* Limit the priority of boosting to avoid reclaim writeback */ 7038 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2) 7039 raise_priority = false; 7040 7041 /* 7042 * Do not writeback or swap pages for boosted reclaim. The 7043 * intent is to relieve pressure not issue sub-optimal IO 7044 * from reclaim context. If no pages are reclaimed, the 7045 * reclaim will be aborted. 7046 */ 7047 sc.may_writepage = !nr_boost_reclaim; 7048 sc.may_swap = !nr_boost_reclaim; 7049 7050 /* 7051 * Do some background aging, to give pages a chance to be 7052 * referenced before reclaiming. All pages are rotated 7053 * regardless of classzone as this is about consistent aging. 7054 */ 7055 kswapd_age_node(pgdat, &sc); 7056 7057 /* Call soft limit reclaim before calling shrink_node. */ 7058 sc.nr_scanned = 0; 7059 nr_soft_scanned = 0; 7060 nr_soft_reclaimed = memcg1_soft_limit_reclaim(pgdat, sc.order, 7061 sc.gfp_mask, &nr_soft_scanned); 7062 sc.nr_reclaimed += nr_soft_reclaimed; 7063 7064 /* 7065 * There should be no need to raise the scanning priority if 7066 * enough pages are already being scanned that that high 7067 * watermark would be met at 100% efficiency. 7068 */ 7069 if (kswapd_shrink_node(pgdat, &sc)) 7070 raise_priority = false; 7071 7072 /* 7073 * If the low watermark is met there is no need for processes 7074 * to be throttled on pfmemalloc_wait as they should not be 7075 * able to safely make forward progress. Wake them 7076 */ 7077 if (waitqueue_active(&pgdat->pfmemalloc_wait) && 7078 allow_direct_reclaim(pgdat)) 7079 wake_up_all(&pgdat->pfmemalloc_wait); 7080 7081 /* Check if kswapd should be suspending */ 7082 __fs_reclaim_release(_THIS_IP_); 7083 ret = kthread_freezable_should_stop(&was_frozen); 7084 __fs_reclaim_acquire(_THIS_IP_); 7085 if (was_frozen || ret) 7086 break; 7087 7088 /* 7089 * Raise priority if scanning rate is too low or there was no 7090 * progress in reclaiming pages 7091 */ 7092 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed; 7093 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed); 7094 7095 /* 7096 * If reclaim made no progress for a boost, stop reclaim as 7097 * IO cannot be queued and it could be an infinite loop in 7098 * extreme circumstances. 7099 */ 7100 if (nr_boost_reclaim && !nr_reclaimed) 7101 break; 7102 7103 if (raise_priority || !nr_reclaimed) 7104 sc.priority--; 7105 } while (sc.priority >= 1); 7106 7107 /* 7108 * Restart only if it went through the priority loop all the way, 7109 * but cache_trim_mode didn't work. 7110 */ 7111 if (!sc.nr_reclaimed && sc.priority < 1 && 7112 !sc.no_cache_trim_mode && sc.cache_trim_mode_failed) { 7113 sc.no_cache_trim_mode = 1; 7114 goto restart; 7115 } 7116 7117 /* 7118 * If the reclaim was boosted, we might still be far from the 7119 * watermark_high at this point. We need to avoid increasing the 7120 * failure count to prevent the kswapd thread from stopping. 7121 */ 7122 if (!sc.nr_reclaimed && !boosted) 7123 atomic_inc(&pgdat->kswapd_failures); 7124 7125 out: 7126 clear_reclaim_active(pgdat, highest_zoneidx); 7127 7128 /* If reclaim was boosted, account for the reclaim done in this pass */ 7129 if (boosted) { 7130 unsigned long flags; 7131 7132 for (i = 0; i <= highest_zoneidx; i++) { 7133 if (!zone_boosts[i]) 7134 continue; 7135 7136 /* Increments are under the zone lock */ 7137 zone = pgdat->node_zones + i; 7138 spin_lock_irqsave(&zone->lock, flags); 7139 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]); 7140 spin_unlock_irqrestore(&zone->lock, flags); 7141 } 7142 7143 /* 7144 * As there is now likely space, wakeup kcompact to defragment 7145 * pageblocks. 7146 */ 7147 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx); 7148 } 7149 7150 snapshot_refaults(NULL, pgdat); 7151 __fs_reclaim_release(_THIS_IP_); 7152 psi_memstall_leave(&pflags); 7153 set_task_reclaim_state(current, NULL); 7154 7155 /* 7156 * Return the order kswapd stopped reclaiming at as 7157 * prepare_kswapd_sleep() takes it into account. If another caller 7158 * entered the allocator slow path while kswapd was awake, order will 7159 * remain at the higher level. 7160 */ 7161 return sc.order; 7162 } 7163 7164 /* 7165 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to 7166 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is 7167 * not a valid index then either kswapd runs for first time or kswapd couldn't 7168 * sleep after previous reclaim attempt (node is still unbalanced). In that 7169 * case return the zone index of the previous kswapd reclaim cycle. 7170 */ 7171 static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat, 7172 enum zone_type prev_highest_zoneidx) 7173 { 7174 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx); 7175 7176 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx; 7177 } 7178 7179 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order, 7180 unsigned int highest_zoneidx) 7181 { 7182 long remaining = 0; 7183 DEFINE_WAIT(wait); 7184 7185 if (freezing(current) || kthread_should_stop()) 7186 return; 7187 7188 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE); 7189 7190 /* 7191 * Try to sleep for a short interval. Note that kcompactd will only be 7192 * woken if it is possible to sleep for a short interval. This is 7193 * deliberate on the assumption that if reclaim cannot keep an 7194 * eligible zone balanced that it's also unlikely that compaction will 7195 * succeed. 7196 */ 7197 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) { 7198 /* 7199 * Compaction records what page blocks it recently failed to 7200 * isolate pages from and skips them in the future scanning. 7201 * When kswapd is going to sleep, it is reasonable to assume 7202 * that pages and compaction may succeed so reset the cache. 7203 */ 7204 reset_isolation_suitable(pgdat); 7205 7206 /* 7207 * We have freed the memory, now we should compact it to make 7208 * allocation of the requested order possible. 7209 */ 7210 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx); 7211 7212 remaining = schedule_timeout(HZ/10); 7213 7214 /* 7215 * If woken prematurely then reset kswapd_highest_zoneidx and 7216 * order. The values will either be from a wakeup request or 7217 * the previous request that slept prematurely. 7218 */ 7219 if (remaining) { 7220 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, 7221 kswapd_highest_zoneidx(pgdat, 7222 highest_zoneidx)); 7223 7224 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order) 7225 WRITE_ONCE(pgdat->kswapd_order, reclaim_order); 7226 } 7227 7228 finish_wait(&pgdat->kswapd_wait, &wait); 7229 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE); 7230 } 7231 7232 /* 7233 * After a short sleep, check if it was a premature sleep. If not, then 7234 * go fully to sleep until explicitly woken up. 7235 */ 7236 if (!remaining && 7237 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) { 7238 trace_mm_vmscan_kswapd_sleep(pgdat->node_id); 7239 7240 /* 7241 * vmstat counters are not perfectly accurate and the estimated 7242 * value for counters such as NR_FREE_PAGES can deviate from the 7243 * true value by nr_online_cpus * threshold. To avoid the zone 7244 * watermarks being breached while under pressure, we reduce the 7245 * per-cpu vmstat threshold while kswapd is awake and restore 7246 * them before going back to sleep. 7247 */ 7248 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold); 7249 7250 if (!kthread_should_stop()) 7251 schedule(); 7252 7253 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold); 7254 } else { 7255 if (remaining) 7256 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY); 7257 else 7258 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY); 7259 } 7260 finish_wait(&pgdat->kswapd_wait, &wait); 7261 } 7262 7263 /* 7264 * The background pageout daemon, started as a kernel thread 7265 * from the init process. 7266 * 7267 * This basically trickles out pages so that we have _some_ 7268 * free memory available even if there is no other activity 7269 * that frees anything up. This is needed for things like routing 7270 * etc, where we otherwise might have all activity going on in 7271 * asynchronous contexts that cannot page things out. 7272 * 7273 * If there are applications that are active memory-allocators 7274 * (most normal use), this basically shouldn't matter. 7275 */ 7276 static int kswapd(void *p) 7277 { 7278 unsigned int alloc_order, reclaim_order; 7279 unsigned int highest_zoneidx = MAX_NR_ZONES - 1; 7280 pg_data_t *pgdat = (pg_data_t *)p; 7281 struct task_struct *tsk = current; 7282 7283 /* 7284 * Tell the memory management that we're a "memory allocator", 7285 * and that if we need more memory we should get access to it 7286 * regardless (see "__alloc_pages()"). "kswapd" should 7287 * never get caught in the normal page freeing logic. 7288 * 7289 * (Kswapd normally doesn't need memory anyway, but sometimes 7290 * you need a small amount of memory in order to be able to 7291 * page out something else, and this flag essentially protects 7292 * us from recursively trying to free more memory as we're 7293 * trying to free the first piece of memory in the first place). 7294 */ 7295 tsk->flags |= PF_MEMALLOC | PF_KSWAPD; 7296 set_freezable(); 7297 7298 WRITE_ONCE(pgdat->kswapd_order, 0); 7299 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES); 7300 atomic_set(&pgdat->nr_writeback_throttled, 0); 7301 for ( ; ; ) { 7302 bool was_frozen; 7303 7304 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order); 7305 highest_zoneidx = kswapd_highest_zoneidx(pgdat, 7306 highest_zoneidx); 7307 7308 kswapd_try_sleep: 7309 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order, 7310 highest_zoneidx); 7311 7312 /* Read the new order and highest_zoneidx */ 7313 alloc_order = READ_ONCE(pgdat->kswapd_order); 7314 highest_zoneidx = kswapd_highest_zoneidx(pgdat, 7315 highest_zoneidx); 7316 WRITE_ONCE(pgdat->kswapd_order, 0); 7317 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES); 7318 7319 if (kthread_freezable_should_stop(&was_frozen)) 7320 break; 7321 7322 /* 7323 * We can speed up thawing tasks if we don't call balance_pgdat 7324 * after returning from the refrigerator 7325 */ 7326 if (was_frozen) 7327 continue; 7328 7329 /* 7330 * Reclaim begins at the requested order but if a high-order 7331 * reclaim fails then kswapd falls back to reclaiming for 7332 * order-0. If that happens, kswapd will consider sleeping 7333 * for the order it finished reclaiming at (reclaim_order) 7334 * but kcompactd is woken to compact for the original 7335 * request (alloc_order). 7336 */ 7337 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx, 7338 alloc_order); 7339 reclaim_order = balance_pgdat(pgdat, alloc_order, 7340 highest_zoneidx); 7341 if (reclaim_order < alloc_order) 7342 goto kswapd_try_sleep; 7343 } 7344 7345 tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD); 7346 7347 return 0; 7348 } 7349 7350 /* 7351 * A zone is low on free memory or too fragmented for high-order memory. If 7352 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's 7353 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim 7354 * has failed or is not needed, still wake up kcompactd if only compaction is 7355 * needed. 7356 */ 7357 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order, 7358 enum zone_type highest_zoneidx) 7359 { 7360 pg_data_t *pgdat; 7361 enum zone_type curr_idx; 7362 7363 if (!managed_zone(zone)) 7364 return; 7365 7366 if (!cpuset_zone_allowed(zone, gfp_flags)) 7367 return; 7368 7369 pgdat = zone->zone_pgdat; 7370 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx); 7371 7372 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx) 7373 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx); 7374 7375 if (READ_ONCE(pgdat->kswapd_order) < order) 7376 WRITE_ONCE(pgdat->kswapd_order, order); 7377 7378 if (!waitqueue_active(&pgdat->kswapd_wait)) 7379 return; 7380 7381 /* Hopeless node, leave it to direct reclaim if possible */ 7382 if (atomic_read(&pgdat->kswapd_failures) >= MAX_RECLAIM_RETRIES || 7383 (pgdat_balanced(pgdat, order, highest_zoneidx) && 7384 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) { 7385 /* 7386 * There may be plenty of free memory available, but it's too 7387 * fragmented for high-order allocations. Wake up kcompactd 7388 * and rely on compaction_suitable() to determine if it's 7389 * needed. If it fails, it will defer subsequent attempts to 7390 * ratelimit its work. 7391 */ 7392 if (!(gfp_flags & __GFP_DIRECT_RECLAIM)) 7393 wakeup_kcompactd(pgdat, order, highest_zoneidx); 7394 return; 7395 } 7396 7397 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order, 7398 gfp_flags); 7399 wake_up_interruptible(&pgdat->kswapd_wait); 7400 } 7401 7402 #ifdef CONFIG_HIBERNATION 7403 /* 7404 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of 7405 * freed pages. 7406 * 7407 * Rather than trying to age LRUs the aim is to preserve the overall 7408 * LRU order by reclaiming preferentially 7409 * inactive > active > active referenced > active mapped 7410 */ 7411 unsigned long shrink_all_memory(unsigned long nr_to_reclaim) 7412 { 7413 struct scan_control sc = { 7414 .nr_to_reclaim = nr_to_reclaim, 7415 .gfp_mask = GFP_HIGHUSER_MOVABLE, 7416 .reclaim_idx = MAX_NR_ZONES - 1, 7417 .priority = DEF_PRIORITY, 7418 .may_writepage = 1, 7419 .may_unmap = 1, 7420 .may_swap = 1, 7421 .hibernation_mode = 1, 7422 }; 7423 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask); 7424 unsigned long nr_reclaimed; 7425 unsigned int noreclaim_flag; 7426 7427 fs_reclaim_acquire(sc.gfp_mask); 7428 noreclaim_flag = memalloc_noreclaim_save(); 7429 set_task_reclaim_state(current, &sc.reclaim_state); 7430 7431 nr_reclaimed = do_try_to_free_pages(zonelist, &sc); 7432 7433 set_task_reclaim_state(current, NULL); 7434 memalloc_noreclaim_restore(noreclaim_flag); 7435 fs_reclaim_release(sc.gfp_mask); 7436 7437 return nr_reclaimed; 7438 } 7439 #endif /* CONFIG_HIBERNATION */ 7440 7441 /* 7442 * This kswapd start function will be called by init and node-hot-add. 7443 */ 7444 void __meminit kswapd_run(int nid) 7445 { 7446 pg_data_t *pgdat = NODE_DATA(nid); 7447 7448 pgdat_kswapd_lock(pgdat); 7449 if (!pgdat->kswapd) { 7450 pgdat->kswapd = kthread_create_on_node(kswapd, pgdat, nid, "kswapd%d", nid); 7451 if (IS_ERR(pgdat->kswapd)) { 7452 /* failure at boot is fatal */ 7453 pr_err("Failed to start kswapd on node %d,ret=%ld\n", 7454 nid, PTR_ERR(pgdat->kswapd)); 7455 BUG_ON(system_state < SYSTEM_RUNNING); 7456 pgdat->kswapd = NULL; 7457 } else { 7458 wake_up_process(pgdat->kswapd); 7459 } 7460 } 7461 pgdat_kswapd_unlock(pgdat); 7462 } 7463 7464 /* 7465 * Called by memory hotplug when all memory in a node is offlined. Caller must 7466 * be holding mem_hotplug_begin/done(). 7467 */ 7468 void __meminit kswapd_stop(int nid) 7469 { 7470 pg_data_t *pgdat = NODE_DATA(nid); 7471 struct task_struct *kswapd; 7472 7473 pgdat_kswapd_lock(pgdat); 7474 kswapd = pgdat->kswapd; 7475 if (kswapd) { 7476 kthread_stop(kswapd); 7477 pgdat->kswapd = NULL; 7478 } 7479 pgdat_kswapd_unlock(pgdat); 7480 } 7481 7482 static const struct ctl_table vmscan_sysctl_table[] = { 7483 { 7484 .procname = "swappiness", 7485 .data = &vm_swappiness, 7486 .maxlen = sizeof(vm_swappiness), 7487 .mode = 0644, 7488 .proc_handler = proc_dointvec_minmax, 7489 .extra1 = SYSCTL_ZERO, 7490 .extra2 = SYSCTL_TWO_HUNDRED, 7491 }, 7492 #ifdef CONFIG_NUMA 7493 { 7494 .procname = "zone_reclaim_mode", 7495 .data = &node_reclaim_mode, 7496 .maxlen = sizeof(node_reclaim_mode), 7497 .mode = 0644, 7498 .proc_handler = proc_dointvec_minmax, 7499 .extra1 = SYSCTL_ZERO, 7500 } 7501 #endif 7502 }; 7503 7504 static int __init kswapd_init(void) 7505 { 7506 int nid; 7507 7508 swap_setup(); 7509 for_each_node_state(nid, N_MEMORY) 7510 kswapd_run(nid); 7511 register_sysctl_init("vm", vmscan_sysctl_table); 7512 return 0; 7513 } 7514 7515 module_init(kswapd_init) 7516 7517 #ifdef CONFIG_NUMA 7518 /* 7519 * Node reclaim mode 7520 * 7521 * If non-zero call node_reclaim when the number of free pages falls below 7522 * the watermarks. 7523 */ 7524 int node_reclaim_mode __read_mostly; 7525 7526 /* 7527 * Priority for NODE_RECLAIM. This determines the fraction of pages 7528 * of a node considered for each zone_reclaim. 4 scans 1/16th of 7529 * a zone. 7530 */ 7531 #define NODE_RECLAIM_PRIORITY 4 7532 7533 /* 7534 * Percentage of pages in a zone that must be unmapped for node_reclaim to 7535 * occur. 7536 */ 7537 int sysctl_min_unmapped_ratio = 1; 7538 7539 /* 7540 * If the number of slab pages in a zone grows beyond this percentage then 7541 * slab reclaim needs to occur. 7542 */ 7543 int sysctl_min_slab_ratio = 5; 7544 7545 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat) 7546 { 7547 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED); 7548 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) + 7549 node_page_state(pgdat, NR_ACTIVE_FILE); 7550 7551 /* 7552 * It's possible for there to be more file mapped pages than 7553 * accounted for by the pages on the file LRU lists because 7554 * tmpfs pages accounted for as ANON can also be FILE_MAPPED 7555 */ 7556 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0; 7557 } 7558 7559 /* Work out how many page cache pages we can reclaim in this reclaim_mode */ 7560 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat) 7561 { 7562 unsigned long nr_pagecache_reclaimable; 7563 unsigned long delta = 0; 7564 7565 /* 7566 * If RECLAIM_UNMAP is set, then all file pages are considered 7567 * potentially reclaimable. Otherwise, we have to worry about 7568 * pages like swapcache and node_unmapped_file_pages() provides 7569 * a better estimate 7570 */ 7571 if (node_reclaim_mode & RECLAIM_UNMAP) 7572 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES); 7573 else 7574 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat); 7575 7576 /* 7577 * Since we can't clean folios through reclaim, remove dirty file 7578 * folios from consideration. 7579 */ 7580 delta += node_page_state(pgdat, NR_FILE_DIRTY); 7581 7582 /* Watch for any possible underflows due to delta */ 7583 if (unlikely(delta > nr_pagecache_reclaimable)) 7584 delta = nr_pagecache_reclaimable; 7585 7586 return nr_pagecache_reclaimable - delta; 7587 } 7588 7589 /* 7590 * Try to free up some pages from this node through reclaim. 7591 */ 7592 static unsigned long __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, 7593 unsigned long nr_pages, 7594 struct scan_control *sc) 7595 { 7596 struct task_struct *p = current; 7597 unsigned int noreclaim_flag; 7598 unsigned long pflags; 7599 7600 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, sc->order, 7601 sc->gfp_mask); 7602 7603 cond_resched(); 7604 psi_memstall_enter(&pflags); 7605 delayacct_freepages_start(); 7606 fs_reclaim_acquire(sc->gfp_mask); 7607 /* 7608 * We need to be able to allocate from the reserves for RECLAIM_UNMAP 7609 */ 7610 noreclaim_flag = memalloc_noreclaim_save(); 7611 set_task_reclaim_state(p, &sc->reclaim_state); 7612 7613 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages || 7614 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) { 7615 /* 7616 * Free memory by calling shrink node with increasing 7617 * priorities until we have enough memory freed. 7618 */ 7619 do { 7620 shrink_node(pgdat, sc); 7621 } while (sc->nr_reclaimed < nr_pages && --sc->priority >= 0); 7622 } 7623 7624 set_task_reclaim_state(p, NULL); 7625 memalloc_noreclaim_restore(noreclaim_flag); 7626 fs_reclaim_release(sc->gfp_mask); 7627 delayacct_freepages_end(); 7628 psi_memstall_leave(&pflags); 7629 7630 trace_mm_vmscan_node_reclaim_end(sc->nr_reclaimed); 7631 7632 return sc->nr_reclaimed; 7633 } 7634 7635 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order) 7636 { 7637 int ret; 7638 /* Minimum pages needed in order to stay on node */ 7639 const unsigned long nr_pages = 1 << order; 7640 struct scan_control sc = { 7641 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX), 7642 .gfp_mask = current_gfp_context(gfp_mask), 7643 .order = order, 7644 .priority = NODE_RECLAIM_PRIORITY, 7645 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE), 7646 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP), 7647 .may_swap = 1, 7648 .reclaim_idx = gfp_zone(gfp_mask), 7649 }; 7650 7651 /* 7652 * Node reclaim reclaims unmapped file backed pages and 7653 * slab pages if we are over the defined limits. 7654 * 7655 * A small portion of unmapped file backed pages is needed for 7656 * file I/O otherwise pages read by file I/O will be immediately 7657 * thrown out if the node is overallocated. So we do not reclaim 7658 * if less than a specified percentage of the node is used by 7659 * unmapped file backed pages. 7660 */ 7661 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages && 7662 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <= 7663 pgdat->min_slab_pages) 7664 return NODE_RECLAIM_FULL; 7665 7666 /* 7667 * Do not scan if the allocation should not be delayed. 7668 */ 7669 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC)) 7670 return NODE_RECLAIM_NOSCAN; 7671 7672 /* 7673 * Only run node reclaim on the local node or on nodes that do not 7674 * have associated processors. This will favor the local processor 7675 * over remote processors and spread off node memory allocations 7676 * as wide as possible. 7677 */ 7678 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id()) 7679 return NODE_RECLAIM_NOSCAN; 7680 7681 if (test_and_set_bit_lock(PGDAT_RECLAIM_LOCKED, &pgdat->flags)) 7682 return NODE_RECLAIM_NOSCAN; 7683 7684 ret = __node_reclaim(pgdat, gfp_mask, nr_pages, &sc) >= nr_pages; 7685 clear_bit_unlock(PGDAT_RECLAIM_LOCKED, &pgdat->flags); 7686 7687 if (ret) 7688 count_vm_event(PGSCAN_ZONE_RECLAIM_SUCCESS); 7689 else 7690 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED); 7691 7692 return ret; 7693 } 7694 7695 #else 7696 7697 static unsigned long __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, 7698 unsigned long nr_pages, 7699 struct scan_control *sc) 7700 { 7701 return 0; 7702 } 7703 7704 #endif 7705 7706 enum { 7707 MEMORY_RECLAIM_SWAPPINESS = 0, 7708 MEMORY_RECLAIM_SWAPPINESS_MAX, 7709 MEMORY_RECLAIM_NULL, 7710 }; 7711 static const match_table_t tokens = { 7712 { MEMORY_RECLAIM_SWAPPINESS, "swappiness=%d"}, 7713 { MEMORY_RECLAIM_SWAPPINESS_MAX, "swappiness=max"}, 7714 { MEMORY_RECLAIM_NULL, NULL }, 7715 }; 7716 7717 int user_proactive_reclaim(char *buf, 7718 struct mem_cgroup *memcg, pg_data_t *pgdat) 7719 { 7720 unsigned int nr_retries = MAX_RECLAIM_RETRIES; 7721 unsigned long nr_to_reclaim, nr_reclaimed = 0; 7722 int swappiness = -1; 7723 char *old_buf, *start; 7724 substring_t args[MAX_OPT_ARGS]; 7725 gfp_t gfp_mask = GFP_KERNEL; 7726 7727 if (!buf || (!memcg && !pgdat) || (memcg && pgdat)) 7728 return -EINVAL; 7729 7730 buf = strstrip(buf); 7731 7732 old_buf = buf; 7733 nr_to_reclaim = memparse(buf, &buf) / PAGE_SIZE; 7734 if (buf == old_buf) 7735 return -EINVAL; 7736 7737 buf = strstrip(buf); 7738 7739 while ((start = strsep(&buf, " ")) != NULL) { 7740 if (!strlen(start)) 7741 continue; 7742 switch (match_token(start, tokens, args)) { 7743 case MEMORY_RECLAIM_SWAPPINESS: 7744 if (match_int(&args[0], &swappiness)) 7745 return -EINVAL; 7746 if (swappiness < MIN_SWAPPINESS || 7747 swappiness > MAX_SWAPPINESS) 7748 return -EINVAL; 7749 break; 7750 case MEMORY_RECLAIM_SWAPPINESS_MAX: 7751 swappiness = SWAPPINESS_ANON_ONLY; 7752 break; 7753 default: 7754 return -EINVAL; 7755 } 7756 } 7757 7758 while (nr_reclaimed < nr_to_reclaim) { 7759 /* Will converge on zero, but reclaim enforces a minimum */ 7760 unsigned long batch_size = (nr_to_reclaim - nr_reclaimed) / 4; 7761 unsigned long reclaimed; 7762 7763 if (signal_pending(current)) 7764 return -EINTR; 7765 7766 /* 7767 * This is the final attempt, drain percpu lru caches in the 7768 * hope of introducing more evictable pages. 7769 */ 7770 if (!nr_retries) 7771 lru_add_drain_all(); 7772 7773 if (memcg) { 7774 unsigned int reclaim_options; 7775 7776 reclaim_options = MEMCG_RECLAIM_MAY_SWAP | 7777 MEMCG_RECLAIM_PROACTIVE; 7778 reclaimed = try_to_free_mem_cgroup_pages(memcg, 7779 batch_size, gfp_mask, 7780 reclaim_options, 7781 swappiness == -1 ? NULL : &swappiness); 7782 } else { 7783 struct scan_control sc = { 7784 .gfp_mask = current_gfp_context(gfp_mask), 7785 .reclaim_idx = gfp_zone(gfp_mask), 7786 .proactive_swappiness = swappiness == -1 ? NULL : &swappiness, 7787 .priority = DEF_PRIORITY, 7788 .may_writepage = 1, 7789 .nr_to_reclaim = max(batch_size, SWAP_CLUSTER_MAX), 7790 .may_unmap = 1, 7791 .may_swap = 1, 7792 .proactive = 1, 7793 }; 7794 7795 if (test_and_set_bit_lock(PGDAT_RECLAIM_LOCKED, 7796 &pgdat->flags)) 7797 return -EBUSY; 7798 7799 reclaimed = __node_reclaim(pgdat, gfp_mask, 7800 batch_size, &sc); 7801 clear_bit_unlock(PGDAT_RECLAIM_LOCKED, &pgdat->flags); 7802 } 7803 7804 if (!reclaimed && !nr_retries--) 7805 return -EAGAIN; 7806 7807 nr_reclaimed += reclaimed; 7808 } 7809 7810 return 0; 7811 } 7812 7813 /** 7814 * check_move_unevictable_folios - Move evictable folios to appropriate zone 7815 * lru list 7816 * @fbatch: Batch of lru folios to check. 7817 * 7818 * Checks folios for evictability, if an evictable folio is in the unevictable 7819 * lru list, moves it to the appropriate evictable lru list. This function 7820 * should be only used for lru folios. 7821 */ 7822 void check_move_unevictable_folios(struct folio_batch *fbatch) 7823 { 7824 struct lruvec *lruvec = NULL; 7825 int pgscanned = 0; 7826 int pgrescued = 0; 7827 int i; 7828 7829 for (i = 0; i < fbatch->nr; i++) { 7830 struct folio *folio = fbatch->folios[i]; 7831 int nr_pages = folio_nr_pages(folio); 7832 7833 pgscanned += nr_pages; 7834 7835 /* block memcg migration while the folio moves between lrus */ 7836 if (!folio_test_clear_lru(folio)) 7837 continue; 7838 7839 lruvec = folio_lruvec_relock_irq(folio, lruvec); 7840 if (folio_evictable(folio) && folio_test_unevictable(folio)) { 7841 lruvec_del_folio(lruvec, folio); 7842 folio_clear_unevictable(folio); 7843 lruvec_add_folio(lruvec, folio); 7844 pgrescued += nr_pages; 7845 } 7846 folio_set_lru(folio); 7847 } 7848 7849 if (lruvec) { 7850 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued); 7851 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned); 7852 unlock_page_lruvec_irq(lruvec); 7853 } else if (pgscanned) { 7854 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned); 7855 } 7856 } 7857 EXPORT_SYMBOL_GPL(check_move_unevictable_folios); 7858 7859 #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA) 7860 static ssize_t reclaim_store(struct device *dev, 7861 struct device_attribute *attr, 7862 const char *buf, size_t count) 7863 { 7864 int ret, nid = dev->id; 7865 7866 ret = user_proactive_reclaim((char *)buf, NULL, NODE_DATA(nid)); 7867 return ret ? -EAGAIN : count; 7868 } 7869 7870 static DEVICE_ATTR_WO(reclaim); 7871 int reclaim_register_node(struct node *node) 7872 { 7873 return device_create_file(&node->dev, &dev_attr_reclaim); 7874 } 7875 7876 void reclaim_unregister_node(struct node *node) 7877 { 7878 return device_remove_file(&node->dev, &dev_attr_reclaim); 7879 } 7880 #endif 7881