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