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