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 try_to_release_page(), 30 buffer_heads_over_limit */ 31 #include <linux/mm_inline.h> 32 #include <linux/backing-dev.h> 33 #include <linux/rmap.h> 34 #include <linux/topology.h> 35 #include <linux/cpu.h> 36 #include <linux/cpuset.h> 37 #include <linux/compaction.h> 38 #include <linux/notifier.h> 39 #include <linux/rwsem.h> 40 #include <linux/delay.h> 41 #include <linux/kthread.h> 42 #include <linux/freezer.h> 43 #include <linux/memcontrol.h> 44 #include <linux/migrate.h> 45 #include <linux/delayacct.h> 46 #include <linux/sysctl.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 54 #include <asm/tlbflush.h> 55 #include <asm/div64.h> 56 57 #include <linux/swapops.h> 58 #include <linux/balloon_compaction.h> 59 #include <linux/sched/sysctl.h> 60 61 #include "internal.h" 62 #include "swap.h" 63 64 #define CREATE_TRACE_POINTS 65 #include <trace/events/vmscan.h> 66 67 struct scan_control { 68 /* How many pages shrink_list() should reclaim */ 69 unsigned long nr_to_reclaim; 70 71 /* 72 * Nodemask of nodes allowed by the caller. If NULL, all nodes 73 * are scanned. 74 */ 75 nodemask_t *nodemask; 76 77 /* 78 * The memory cgroup that hit its limit and as a result is the 79 * primary target of this reclaim invocation. 80 */ 81 struct mem_cgroup *target_mem_cgroup; 82 83 /* 84 * Scan pressure balancing between anon and file LRUs 85 */ 86 unsigned long anon_cost; 87 unsigned long file_cost; 88 89 /* Can active pages be deactivated as part of reclaim? */ 90 #define DEACTIVATE_ANON 1 91 #define DEACTIVATE_FILE 2 92 unsigned int may_deactivate:2; 93 unsigned int force_deactivate:1; 94 unsigned int skipped_deactivate:1; 95 96 /* Writepage batching in laptop mode; RECLAIM_WRITE */ 97 unsigned int may_writepage:1; 98 99 /* Can mapped pages be reclaimed? */ 100 unsigned int may_unmap:1; 101 102 /* Can pages be swapped as part of reclaim? */ 103 unsigned int may_swap:1; 104 105 /* 106 * Cgroup memory below memory.low is protected as long as we 107 * don't threaten to OOM. If any cgroup is reclaimed at 108 * reduced force or passed over entirely due to its memory.low 109 * setting (memcg_low_skipped), and nothing is reclaimed as a 110 * result, then go back for one more cycle that reclaims the protected 111 * memory (memcg_low_reclaim) to avert OOM. 112 */ 113 unsigned int memcg_low_reclaim:1; 114 unsigned int memcg_low_skipped:1; 115 116 unsigned int hibernation_mode:1; 117 118 /* One of the zones is ready for compaction */ 119 unsigned int compaction_ready:1; 120 121 /* There is easily reclaimable cold cache in the current node */ 122 unsigned int cache_trim_mode:1; 123 124 /* The file pages on the current node are dangerously low */ 125 unsigned int file_is_tiny:1; 126 127 /* Always discard instead of demoting to lower tier memory */ 128 unsigned int no_demotion:1; 129 130 /* Allocation order */ 131 s8 order; 132 133 /* Scan (total_size >> priority) pages at once */ 134 s8 priority; 135 136 /* The highest zone to isolate pages for reclaim from */ 137 s8 reclaim_idx; 138 139 /* This context's GFP mask */ 140 gfp_t gfp_mask; 141 142 /* Incremented by the number of inactive pages that were scanned */ 143 unsigned long nr_scanned; 144 145 /* Number of pages freed so far during a call to shrink_zones() */ 146 unsigned long nr_reclaimed; 147 148 struct { 149 unsigned int dirty; 150 unsigned int unqueued_dirty; 151 unsigned int congested; 152 unsigned int writeback; 153 unsigned int immediate; 154 unsigned int file_taken; 155 unsigned int taken; 156 } nr; 157 158 /* for recording the reclaimed slab by now */ 159 struct reclaim_state reclaim_state; 160 }; 161 162 #ifdef ARCH_HAS_PREFETCHW 163 #define prefetchw_prev_lru_page(_page, _base, _field) \ 164 do { \ 165 if ((_page)->lru.prev != _base) { \ 166 struct page *prev; \ 167 \ 168 prev = lru_to_page(&(_page->lru)); \ 169 prefetchw(&prev->_field); \ 170 } \ 171 } while (0) 172 #else 173 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0) 174 #endif 175 176 /* 177 * From 0 .. 200. Higher means more swappy. 178 */ 179 int vm_swappiness = 60; 180 181 static void set_task_reclaim_state(struct task_struct *task, 182 struct reclaim_state *rs) 183 { 184 /* Check for an overwrite */ 185 WARN_ON_ONCE(rs && task->reclaim_state); 186 187 /* Check for the nulling of an already-nulled member */ 188 WARN_ON_ONCE(!rs && !task->reclaim_state); 189 190 task->reclaim_state = rs; 191 } 192 193 static LIST_HEAD(shrinker_list); 194 static DECLARE_RWSEM(shrinker_rwsem); 195 196 #ifdef CONFIG_MEMCG 197 static int shrinker_nr_max; 198 199 /* The shrinker_info is expanded in a batch of BITS_PER_LONG */ 200 static inline int shrinker_map_size(int nr_items) 201 { 202 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long)); 203 } 204 205 static inline int shrinker_defer_size(int nr_items) 206 { 207 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t)); 208 } 209 210 static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg, 211 int nid) 212 { 213 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info, 214 lockdep_is_held(&shrinker_rwsem)); 215 } 216 217 static int expand_one_shrinker_info(struct mem_cgroup *memcg, 218 int map_size, int defer_size, 219 int old_map_size, int old_defer_size) 220 { 221 struct shrinker_info *new, *old; 222 struct mem_cgroup_per_node *pn; 223 int nid; 224 int size = map_size + defer_size; 225 226 for_each_node(nid) { 227 pn = memcg->nodeinfo[nid]; 228 old = shrinker_info_protected(memcg, nid); 229 /* Not yet online memcg */ 230 if (!old) 231 return 0; 232 233 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid); 234 if (!new) 235 return -ENOMEM; 236 237 new->nr_deferred = (atomic_long_t *)(new + 1); 238 new->map = (void *)new->nr_deferred + defer_size; 239 240 /* map: set all old bits, clear all new bits */ 241 memset(new->map, (int)0xff, old_map_size); 242 memset((void *)new->map + old_map_size, 0, map_size - old_map_size); 243 /* nr_deferred: copy old values, clear all new values */ 244 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size); 245 memset((void *)new->nr_deferred + old_defer_size, 0, 246 defer_size - old_defer_size); 247 248 rcu_assign_pointer(pn->shrinker_info, new); 249 kvfree_rcu(old, rcu); 250 } 251 252 return 0; 253 } 254 255 void free_shrinker_info(struct mem_cgroup *memcg) 256 { 257 struct mem_cgroup_per_node *pn; 258 struct shrinker_info *info; 259 int nid; 260 261 for_each_node(nid) { 262 pn = memcg->nodeinfo[nid]; 263 info = rcu_dereference_protected(pn->shrinker_info, true); 264 kvfree(info); 265 rcu_assign_pointer(pn->shrinker_info, NULL); 266 } 267 } 268 269 int alloc_shrinker_info(struct mem_cgroup *memcg) 270 { 271 struct shrinker_info *info; 272 int nid, size, ret = 0; 273 int map_size, defer_size = 0; 274 275 down_write(&shrinker_rwsem); 276 map_size = shrinker_map_size(shrinker_nr_max); 277 defer_size = shrinker_defer_size(shrinker_nr_max); 278 size = map_size + defer_size; 279 for_each_node(nid) { 280 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid); 281 if (!info) { 282 free_shrinker_info(memcg); 283 ret = -ENOMEM; 284 break; 285 } 286 info->nr_deferred = (atomic_long_t *)(info + 1); 287 info->map = (void *)info->nr_deferred + defer_size; 288 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info); 289 } 290 up_write(&shrinker_rwsem); 291 292 return ret; 293 } 294 295 static inline bool need_expand(int nr_max) 296 { 297 return round_up(nr_max, BITS_PER_LONG) > 298 round_up(shrinker_nr_max, BITS_PER_LONG); 299 } 300 301 static int expand_shrinker_info(int new_id) 302 { 303 int ret = 0; 304 int new_nr_max = new_id + 1; 305 int map_size, defer_size = 0; 306 int old_map_size, old_defer_size = 0; 307 struct mem_cgroup *memcg; 308 309 if (!need_expand(new_nr_max)) 310 goto out; 311 312 if (!root_mem_cgroup) 313 goto out; 314 315 lockdep_assert_held(&shrinker_rwsem); 316 317 map_size = shrinker_map_size(new_nr_max); 318 defer_size = shrinker_defer_size(new_nr_max); 319 old_map_size = shrinker_map_size(shrinker_nr_max); 320 old_defer_size = shrinker_defer_size(shrinker_nr_max); 321 322 memcg = mem_cgroup_iter(NULL, NULL, NULL); 323 do { 324 ret = expand_one_shrinker_info(memcg, map_size, defer_size, 325 old_map_size, old_defer_size); 326 if (ret) { 327 mem_cgroup_iter_break(NULL, memcg); 328 goto out; 329 } 330 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL); 331 out: 332 if (!ret) 333 shrinker_nr_max = new_nr_max; 334 335 return ret; 336 } 337 338 void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id) 339 { 340 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) { 341 struct shrinker_info *info; 342 343 rcu_read_lock(); 344 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info); 345 /* Pairs with smp mb in shrink_slab() */ 346 smp_mb__before_atomic(); 347 set_bit(shrinker_id, info->map); 348 rcu_read_unlock(); 349 } 350 } 351 352 static DEFINE_IDR(shrinker_idr); 353 354 static int prealloc_memcg_shrinker(struct shrinker *shrinker) 355 { 356 int id, ret = -ENOMEM; 357 358 if (mem_cgroup_disabled()) 359 return -ENOSYS; 360 361 down_write(&shrinker_rwsem); 362 /* This may call shrinker, so it must use down_read_trylock() */ 363 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL); 364 if (id < 0) 365 goto unlock; 366 367 if (id >= shrinker_nr_max) { 368 if (expand_shrinker_info(id)) { 369 idr_remove(&shrinker_idr, id); 370 goto unlock; 371 } 372 } 373 shrinker->id = id; 374 ret = 0; 375 unlock: 376 up_write(&shrinker_rwsem); 377 return ret; 378 } 379 380 static void unregister_memcg_shrinker(struct shrinker *shrinker) 381 { 382 int id = shrinker->id; 383 384 BUG_ON(id < 0); 385 386 lockdep_assert_held(&shrinker_rwsem); 387 388 idr_remove(&shrinker_idr, id); 389 } 390 391 static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker, 392 struct mem_cgroup *memcg) 393 { 394 struct shrinker_info *info; 395 396 info = shrinker_info_protected(memcg, nid); 397 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0); 398 } 399 400 static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker, 401 struct mem_cgroup *memcg) 402 { 403 struct shrinker_info *info; 404 405 info = shrinker_info_protected(memcg, nid); 406 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]); 407 } 408 409 void reparent_shrinker_deferred(struct mem_cgroup *memcg) 410 { 411 int i, nid; 412 long nr; 413 struct mem_cgroup *parent; 414 struct shrinker_info *child_info, *parent_info; 415 416 parent = parent_mem_cgroup(memcg); 417 if (!parent) 418 parent = root_mem_cgroup; 419 420 /* Prevent from concurrent shrinker_info expand */ 421 down_read(&shrinker_rwsem); 422 for_each_node(nid) { 423 child_info = shrinker_info_protected(memcg, nid); 424 parent_info = shrinker_info_protected(parent, nid); 425 for (i = 0; i < shrinker_nr_max; i++) { 426 nr = atomic_long_read(&child_info->nr_deferred[i]); 427 atomic_long_add(nr, &parent_info->nr_deferred[i]); 428 } 429 } 430 up_read(&shrinker_rwsem); 431 } 432 433 static bool cgroup_reclaim(struct scan_control *sc) 434 { 435 return sc->target_mem_cgroup; 436 } 437 438 /** 439 * writeback_throttling_sane - is the usual dirty throttling mechanism available? 440 * @sc: scan_control in question 441 * 442 * The normal page dirty throttling mechanism in balance_dirty_pages() is 443 * completely broken with the legacy memcg and direct stalling in 444 * shrink_page_list() is used for throttling instead, which lacks all the 445 * niceties such as fairness, adaptive pausing, bandwidth proportional 446 * allocation and configurability. 447 * 448 * This function tests whether the vmscan currently in progress can assume 449 * that the normal dirty throttling mechanism is operational. 450 */ 451 static bool writeback_throttling_sane(struct scan_control *sc) 452 { 453 if (!cgroup_reclaim(sc)) 454 return true; 455 #ifdef CONFIG_CGROUP_WRITEBACK 456 if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) 457 return true; 458 #endif 459 return false; 460 } 461 #else 462 static int prealloc_memcg_shrinker(struct shrinker *shrinker) 463 { 464 return -ENOSYS; 465 } 466 467 static void unregister_memcg_shrinker(struct shrinker *shrinker) 468 { 469 } 470 471 static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker, 472 struct mem_cgroup *memcg) 473 { 474 return 0; 475 } 476 477 static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker, 478 struct mem_cgroup *memcg) 479 { 480 return 0; 481 } 482 483 static bool cgroup_reclaim(struct scan_control *sc) 484 { 485 return false; 486 } 487 488 static bool writeback_throttling_sane(struct scan_control *sc) 489 { 490 return true; 491 } 492 #endif 493 494 static long xchg_nr_deferred(struct shrinker *shrinker, 495 struct shrink_control *sc) 496 { 497 int nid = sc->nid; 498 499 if (!(shrinker->flags & SHRINKER_NUMA_AWARE)) 500 nid = 0; 501 502 if (sc->memcg && 503 (shrinker->flags & SHRINKER_MEMCG_AWARE)) 504 return xchg_nr_deferred_memcg(nid, shrinker, 505 sc->memcg); 506 507 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0); 508 } 509 510 511 static long add_nr_deferred(long nr, struct shrinker *shrinker, 512 struct shrink_control *sc) 513 { 514 int nid = sc->nid; 515 516 if (!(shrinker->flags & SHRINKER_NUMA_AWARE)) 517 nid = 0; 518 519 if (sc->memcg && 520 (shrinker->flags & SHRINKER_MEMCG_AWARE)) 521 return add_nr_deferred_memcg(nr, nid, shrinker, 522 sc->memcg); 523 524 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]); 525 } 526 527 static bool can_demote(int nid, struct scan_control *sc) 528 { 529 if (!numa_demotion_enabled) 530 return false; 531 if (sc) { 532 if (sc->no_demotion) 533 return false; 534 /* It is pointless to do demotion in memcg reclaim */ 535 if (cgroup_reclaim(sc)) 536 return false; 537 } 538 if (next_demotion_node(nid) == NUMA_NO_NODE) 539 return false; 540 541 return true; 542 } 543 544 static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg, 545 int nid, 546 struct scan_control *sc) 547 { 548 if (memcg == NULL) { 549 /* 550 * For non-memcg reclaim, is there 551 * space in any swap device? 552 */ 553 if (get_nr_swap_pages() > 0) 554 return true; 555 } else { 556 /* Is the memcg below its swap limit? */ 557 if (mem_cgroup_get_nr_swap_pages(memcg) > 0) 558 return true; 559 } 560 561 /* 562 * The page can not be swapped. 563 * 564 * Can it be reclaimed from this node via demotion? 565 */ 566 return can_demote(nid, sc); 567 } 568 569 /* 570 * This misses isolated pages which are not accounted for to save counters. 571 * As the data only determines if reclaim or compaction continues, it is 572 * not expected that isolated pages will be a dominating factor. 573 */ 574 unsigned long zone_reclaimable_pages(struct zone *zone) 575 { 576 unsigned long nr; 577 578 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) + 579 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE); 580 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL)) 581 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) + 582 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON); 583 584 return nr; 585 } 586 587 /** 588 * lruvec_lru_size - Returns the number of pages on the given LRU list. 589 * @lruvec: lru vector 590 * @lru: lru to use 591 * @zone_idx: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list) 592 */ 593 static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, 594 int zone_idx) 595 { 596 unsigned long size = 0; 597 int zid; 598 599 for (zid = 0; zid <= zone_idx; zid++) { 600 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid]; 601 602 if (!managed_zone(zone)) 603 continue; 604 605 if (!mem_cgroup_disabled()) 606 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid); 607 else 608 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru); 609 } 610 return size; 611 } 612 613 /* 614 * Add a shrinker callback to be called from the vm. 615 */ 616 int prealloc_shrinker(struct shrinker *shrinker) 617 { 618 unsigned int size; 619 int err; 620 621 if (shrinker->flags & SHRINKER_MEMCG_AWARE) { 622 err = prealloc_memcg_shrinker(shrinker); 623 if (err != -ENOSYS) 624 return err; 625 626 shrinker->flags &= ~SHRINKER_MEMCG_AWARE; 627 } 628 629 size = sizeof(*shrinker->nr_deferred); 630 if (shrinker->flags & SHRINKER_NUMA_AWARE) 631 size *= nr_node_ids; 632 633 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL); 634 if (!shrinker->nr_deferred) 635 return -ENOMEM; 636 637 return 0; 638 } 639 640 void free_prealloced_shrinker(struct shrinker *shrinker) 641 { 642 if (shrinker->flags & SHRINKER_MEMCG_AWARE) { 643 down_write(&shrinker_rwsem); 644 unregister_memcg_shrinker(shrinker); 645 up_write(&shrinker_rwsem); 646 return; 647 } 648 649 kfree(shrinker->nr_deferred); 650 shrinker->nr_deferred = NULL; 651 } 652 653 void register_shrinker_prepared(struct shrinker *shrinker) 654 { 655 down_write(&shrinker_rwsem); 656 list_add_tail(&shrinker->list, &shrinker_list); 657 shrinker->flags |= SHRINKER_REGISTERED; 658 up_write(&shrinker_rwsem); 659 } 660 661 int register_shrinker(struct shrinker *shrinker) 662 { 663 int err = prealloc_shrinker(shrinker); 664 665 if (err) 666 return err; 667 register_shrinker_prepared(shrinker); 668 return 0; 669 } 670 EXPORT_SYMBOL(register_shrinker); 671 672 /* 673 * Remove one 674 */ 675 void unregister_shrinker(struct shrinker *shrinker) 676 { 677 if (!(shrinker->flags & SHRINKER_REGISTERED)) 678 return; 679 680 down_write(&shrinker_rwsem); 681 list_del(&shrinker->list); 682 shrinker->flags &= ~SHRINKER_REGISTERED; 683 if (shrinker->flags & SHRINKER_MEMCG_AWARE) 684 unregister_memcg_shrinker(shrinker); 685 up_write(&shrinker_rwsem); 686 687 kfree(shrinker->nr_deferred); 688 shrinker->nr_deferred = NULL; 689 } 690 EXPORT_SYMBOL(unregister_shrinker); 691 692 /** 693 * synchronize_shrinkers - Wait for all running shrinkers to complete. 694 * 695 * This is equivalent to calling unregister_shrink() and register_shrinker(), 696 * but atomically and with less overhead. This is useful to guarantee that all 697 * shrinker invocations have seen an update, before freeing memory, similar to 698 * rcu. 699 */ 700 void synchronize_shrinkers(void) 701 { 702 down_write(&shrinker_rwsem); 703 up_write(&shrinker_rwsem); 704 } 705 EXPORT_SYMBOL(synchronize_shrinkers); 706 707 #define SHRINK_BATCH 128 708 709 static unsigned long do_shrink_slab(struct shrink_control *shrinkctl, 710 struct shrinker *shrinker, int priority) 711 { 712 unsigned long freed = 0; 713 unsigned long long delta; 714 long total_scan; 715 long freeable; 716 long nr; 717 long new_nr; 718 long batch_size = shrinker->batch ? shrinker->batch 719 : SHRINK_BATCH; 720 long scanned = 0, next_deferred; 721 722 freeable = shrinker->count_objects(shrinker, shrinkctl); 723 if (freeable == 0 || freeable == SHRINK_EMPTY) 724 return freeable; 725 726 /* 727 * copy the current shrinker scan count into a local variable 728 * and zero it so that other concurrent shrinker invocations 729 * don't also do this scanning work. 730 */ 731 nr = xchg_nr_deferred(shrinker, shrinkctl); 732 733 if (shrinker->seeks) { 734 delta = freeable >> priority; 735 delta *= 4; 736 do_div(delta, shrinker->seeks); 737 } else { 738 /* 739 * These objects don't require any IO to create. Trim 740 * them aggressively under memory pressure to keep 741 * them from causing refetches in the IO caches. 742 */ 743 delta = freeable / 2; 744 } 745 746 total_scan = nr >> priority; 747 total_scan += delta; 748 total_scan = min(total_scan, (2 * freeable)); 749 750 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr, 751 freeable, delta, total_scan, priority); 752 753 /* 754 * Normally, we should not scan less than batch_size objects in one 755 * pass to avoid too frequent shrinker calls, but if the slab has less 756 * than batch_size objects in total and we are really tight on memory, 757 * we will try to reclaim all available objects, otherwise we can end 758 * up failing allocations although there are plenty of reclaimable 759 * objects spread over several slabs with usage less than the 760 * batch_size. 761 * 762 * We detect the "tight on memory" situations by looking at the total 763 * number of objects we want to scan (total_scan). If it is greater 764 * than the total number of objects on slab (freeable), we must be 765 * scanning at high prio and therefore should try to reclaim as much as 766 * possible. 767 */ 768 while (total_scan >= batch_size || 769 total_scan >= freeable) { 770 unsigned long ret; 771 unsigned long nr_to_scan = min(batch_size, total_scan); 772 773 shrinkctl->nr_to_scan = nr_to_scan; 774 shrinkctl->nr_scanned = nr_to_scan; 775 ret = shrinker->scan_objects(shrinker, shrinkctl); 776 if (ret == SHRINK_STOP) 777 break; 778 freed += ret; 779 780 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned); 781 total_scan -= shrinkctl->nr_scanned; 782 scanned += shrinkctl->nr_scanned; 783 784 cond_resched(); 785 } 786 787 /* 788 * The deferred work is increased by any new work (delta) that wasn't 789 * done, decreased by old deferred work that was done now. 790 * 791 * And it is capped to two times of the freeable items. 792 */ 793 next_deferred = max_t(long, (nr + delta - scanned), 0); 794 next_deferred = min(next_deferred, (2 * freeable)); 795 796 /* 797 * move the unused scan count back into the shrinker in a 798 * manner that handles concurrent updates. 799 */ 800 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl); 801 802 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan); 803 return freed; 804 } 805 806 #ifdef CONFIG_MEMCG 807 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid, 808 struct mem_cgroup *memcg, int priority) 809 { 810 struct shrinker_info *info; 811 unsigned long ret, freed = 0; 812 int i; 813 814 if (!mem_cgroup_online(memcg)) 815 return 0; 816 817 if (!down_read_trylock(&shrinker_rwsem)) 818 return 0; 819 820 info = shrinker_info_protected(memcg, nid); 821 if (unlikely(!info)) 822 goto unlock; 823 824 for_each_set_bit(i, info->map, shrinker_nr_max) { 825 struct shrink_control sc = { 826 .gfp_mask = gfp_mask, 827 .nid = nid, 828 .memcg = memcg, 829 }; 830 struct shrinker *shrinker; 831 832 shrinker = idr_find(&shrinker_idr, i); 833 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) { 834 if (!shrinker) 835 clear_bit(i, info->map); 836 continue; 837 } 838 839 /* Call non-slab shrinkers even though kmem is disabled */ 840 if (!memcg_kmem_enabled() && 841 !(shrinker->flags & SHRINKER_NONSLAB)) 842 continue; 843 844 ret = do_shrink_slab(&sc, shrinker, priority); 845 if (ret == SHRINK_EMPTY) { 846 clear_bit(i, info->map); 847 /* 848 * After the shrinker reported that it had no objects to 849 * free, but before we cleared the corresponding bit in 850 * the memcg shrinker map, a new object might have been 851 * added. To make sure, we have the bit set in this 852 * case, we invoke the shrinker one more time and reset 853 * the bit if it reports that it is not empty anymore. 854 * The memory barrier here pairs with the barrier in 855 * set_shrinker_bit(): 856 * 857 * list_lru_add() shrink_slab_memcg() 858 * list_add_tail() clear_bit() 859 * <MB> <MB> 860 * set_bit() do_shrink_slab() 861 */ 862 smp_mb__after_atomic(); 863 ret = do_shrink_slab(&sc, shrinker, priority); 864 if (ret == SHRINK_EMPTY) 865 ret = 0; 866 else 867 set_shrinker_bit(memcg, nid, i); 868 } 869 freed += ret; 870 871 if (rwsem_is_contended(&shrinker_rwsem)) { 872 freed = freed ? : 1; 873 break; 874 } 875 } 876 unlock: 877 up_read(&shrinker_rwsem); 878 return freed; 879 } 880 #else /* CONFIG_MEMCG */ 881 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid, 882 struct mem_cgroup *memcg, int priority) 883 { 884 return 0; 885 } 886 #endif /* CONFIG_MEMCG */ 887 888 /** 889 * shrink_slab - shrink slab caches 890 * @gfp_mask: allocation context 891 * @nid: node whose slab caches to target 892 * @memcg: memory cgroup whose slab caches to target 893 * @priority: the reclaim priority 894 * 895 * Call the shrink functions to age shrinkable caches. 896 * 897 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set, 898 * unaware shrinkers will receive a node id of 0 instead. 899 * 900 * @memcg specifies the memory cgroup to target. Unaware shrinkers 901 * are called only if it is the root cgroup. 902 * 903 * @priority is sc->priority, we take the number of objects and >> by priority 904 * in order to get the scan target. 905 * 906 * Returns the number of reclaimed slab objects. 907 */ 908 static unsigned long shrink_slab(gfp_t gfp_mask, int nid, 909 struct mem_cgroup *memcg, 910 int priority) 911 { 912 unsigned long ret, freed = 0; 913 struct shrinker *shrinker; 914 915 /* 916 * The root memcg might be allocated even though memcg is disabled 917 * via "cgroup_disable=memory" boot parameter. This could make 918 * mem_cgroup_is_root() return false, then just run memcg slab 919 * shrink, but skip global shrink. This may result in premature 920 * oom. 921 */ 922 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg)) 923 return shrink_slab_memcg(gfp_mask, nid, memcg, priority); 924 925 if (!down_read_trylock(&shrinker_rwsem)) 926 goto out; 927 928 list_for_each_entry(shrinker, &shrinker_list, list) { 929 struct shrink_control sc = { 930 .gfp_mask = gfp_mask, 931 .nid = nid, 932 .memcg = memcg, 933 }; 934 935 ret = do_shrink_slab(&sc, shrinker, priority); 936 if (ret == SHRINK_EMPTY) 937 ret = 0; 938 freed += ret; 939 /* 940 * Bail out if someone want to register a new shrinker to 941 * prevent the registration from being stalled for long periods 942 * by parallel ongoing shrinking. 943 */ 944 if (rwsem_is_contended(&shrinker_rwsem)) { 945 freed = freed ? : 1; 946 break; 947 } 948 } 949 950 up_read(&shrinker_rwsem); 951 out: 952 cond_resched(); 953 return freed; 954 } 955 956 static void drop_slab_node(int nid) 957 { 958 unsigned long freed; 959 int shift = 0; 960 961 do { 962 struct mem_cgroup *memcg = NULL; 963 964 if (fatal_signal_pending(current)) 965 return; 966 967 freed = 0; 968 memcg = mem_cgroup_iter(NULL, NULL, NULL); 969 do { 970 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0); 971 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL); 972 } while ((freed >> shift++) > 1); 973 } 974 975 void drop_slab(void) 976 { 977 int nid; 978 979 for_each_online_node(nid) 980 drop_slab_node(nid); 981 } 982 983 static inline int is_page_cache_freeable(struct folio *folio) 984 { 985 /* 986 * A freeable page cache page is referenced only by the caller 987 * that isolated the page, the page cache and optional buffer 988 * heads at page->private. 989 */ 990 return folio_ref_count(folio) - folio_test_private(folio) == 991 1 + folio_nr_pages(folio); 992 } 993 994 /* 995 * We detected a synchronous write error writing a folio out. Probably 996 * -ENOSPC. We need to propagate that into the address_space for a subsequent 997 * fsync(), msync() or close(). 998 * 999 * The tricky part is that after writepage we cannot touch the mapping: nothing 1000 * prevents it from being freed up. But we have a ref on the folio and once 1001 * that folio is locked, the mapping is pinned. 1002 * 1003 * We're allowed to run sleeping folio_lock() here because we know the caller has 1004 * __GFP_FS. 1005 */ 1006 static void handle_write_error(struct address_space *mapping, 1007 struct folio *folio, int error) 1008 { 1009 folio_lock(folio); 1010 if (folio_mapping(folio) == mapping) 1011 mapping_set_error(mapping, error); 1012 folio_unlock(folio); 1013 } 1014 1015 static bool skip_throttle_noprogress(pg_data_t *pgdat) 1016 { 1017 int reclaimable = 0, write_pending = 0; 1018 int i; 1019 1020 /* 1021 * If kswapd is disabled, reschedule if necessary but do not 1022 * throttle as the system is likely near OOM. 1023 */ 1024 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES) 1025 return true; 1026 1027 /* 1028 * If there are a lot of dirty/writeback pages then do not 1029 * throttle as throttling will occur when the pages cycle 1030 * towards the end of the LRU if still under writeback. 1031 */ 1032 for (i = 0; i < MAX_NR_ZONES; i++) { 1033 struct zone *zone = pgdat->node_zones + i; 1034 1035 if (!managed_zone(zone)) 1036 continue; 1037 1038 reclaimable += zone_reclaimable_pages(zone); 1039 write_pending += zone_page_state_snapshot(zone, 1040 NR_ZONE_WRITE_PENDING); 1041 } 1042 if (2 * write_pending <= reclaimable) 1043 return true; 1044 1045 return false; 1046 } 1047 1048 void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason) 1049 { 1050 wait_queue_head_t *wqh = &pgdat->reclaim_wait[reason]; 1051 long timeout, ret; 1052 DEFINE_WAIT(wait); 1053 1054 /* 1055 * Do not throttle IO workers, kthreads other than kswapd or 1056 * workqueues. They may be required for reclaim to make 1057 * forward progress (e.g. journalling workqueues or kthreads). 1058 */ 1059 if (!current_is_kswapd() && 1060 current->flags & (PF_IO_WORKER|PF_KTHREAD)) { 1061 cond_resched(); 1062 return; 1063 } 1064 1065 /* 1066 * These figures are pulled out of thin air. 1067 * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many 1068 * parallel reclaimers which is a short-lived event so the timeout is 1069 * short. Failing to make progress or waiting on writeback are 1070 * potentially long-lived events so use a longer timeout. This is shaky 1071 * logic as a failure to make progress could be due to anything from 1072 * writeback to a slow device to excessive references pages at the tail 1073 * of the inactive LRU. 1074 */ 1075 switch(reason) { 1076 case VMSCAN_THROTTLE_WRITEBACK: 1077 timeout = HZ/10; 1078 1079 if (atomic_inc_return(&pgdat->nr_writeback_throttled) == 1) { 1080 WRITE_ONCE(pgdat->nr_reclaim_start, 1081 node_page_state(pgdat, NR_THROTTLED_WRITTEN)); 1082 } 1083 1084 break; 1085 case VMSCAN_THROTTLE_CONGESTED: 1086 fallthrough; 1087 case VMSCAN_THROTTLE_NOPROGRESS: 1088 if (skip_throttle_noprogress(pgdat)) { 1089 cond_resched(); 1090 return; 1091 } 1092 1093 timeout = 1; 1094 1095 break; 1096 case VMSCAN_THROTTLE_ISOLATED: 1097 timeout = HZ/50; 1098 break; 1099 default: 1100 WARN_ON_ONCE(1); 1101 timeout = HZ; 1102 break; 1103 } 1104 1105 prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE); 1106 ret = schedule_timeout(timeout); 1107 finish_wait(wqh, &wait); 1108 1109 if (reason == VMSCAN_THROTTLE_WRITEBACK) 1110 atomic_dec(&pgdat->nr_writeback_throttled); 1111 1112 trace_mm_vmscan_throttled(pgdat->node_id, jiffies_to_usecs(timeout), 1113 jiffies_to_usecs(timeout - ret), 1114 reason); 1115 } 1116 1117 /* 1118 * Account for pages written if tasks are throttled waiting on dirty 1119 * pages to clean. If enough pages have been cleaned since throttling 1120 * started then wakeup the throttled tasks. 1121 */ 1122 void __acct_reclaim_writeback(pg_data_t *pgdat, struct folio *folio, 1123 int nr_throttled) 1124 { 1125 unsigned long nr_written; 1126 1127 node_stat_add_folio(folio, NR_THROTTLED_WRITTEN); 1128 1129 /* 1130 * This is an inaccurate read as the per-cpu deltas may not 1131 * be synchronised. However, given that the system is 1132 * writeback throttled, it is not worth taking the penalty 1133 * of getting an accurate count. At worst, the throttle 1134 * timeout guarantees forward progress. 1135 */ 1136 nr_written = node_page_state(pgdat, NR_THROTTLED_WRITTEN) - 1137 READ_ONCE(pgdat->nr_reclaim_start); 1138 1139 if (nr_written > SWAP_CLUSTER_MAX * nr_throttled) 1140 wake_up(&pgdat->reclaim_wait[VMSCAN_THROTTLE_WRITEBACK]); 1141 } 1142 1143 /* possible outcome of pageout() */ 1144 typedef enum { 1145 /* failed to write page out, page is locked */ 1146 PAGE_KEEP, 1147 /* move page to the active list, page is locked */ 1148 PAGE_ACTIVATE, 1149 /* page has been sent to the disk successfully, page is unlocked */ 1150 PAGE_SUCCESS, 1151 /* page is clean and locked */ 1152 PAGE_CLEAN, 1153 } pageout_t; 1154 1155 /* 1156 * pageout is called by shrink_page_list() for each dirty page. 1157 * Calls ->writepage(). 1158 */ 1159 static pageout_t pageout(struct folio *folio, struct address_space *mapping, 1160 struct swap_iocb **plug) 1161 { 1162 /* 1163 * If the folio is dirty, only perform writeback if that write 1164 * will be non-blocking. To prevent this allocation from being 1165 * stalled by pagecache activity. But note that there may be 1166 * stalls if we need to run get_block(). We could test 1167 * PagePrivate for that. 1168 * 1169 * If this process is currently in __generic_file_write_iter() against 1170 * this folio's queue, we can perform writeback even if that 1171 * will block. 1172 * 1173 * If the folio is swapcache, write it back even if that would 1174 * block, for some throttling. This happens by accident, because 1175 * swap_backing_dev_info is bust: it doesn't reflect the 1176 * congestion state of the swapdevs. Easy to fix, if needed. 1177 */ 1178 if (!is_page_cache_freeable(folio)) 1179 return PAGE_KEEP; 1180 if (!mapping) { 1181 /* 1182 * Some data journaling orphaned folios can have 1183 * folio->mapping == NULL while being dirty with clean buffers. 1184 */ 1185 if (folio_test_private(folio)) { 1186 if (try_to_free_buffers(&folio->page)) { 1187 folio_clear_dirty(folio); 1188 pr_info("%s: orphaned folio\n", __func__); 1189 return PAGE_CLEAN; 1190 } 1191 } 1192 return PAGE_KEEP; 1193 } 1194 if (mapping->a_ops->writepage == NULL) 1195 return PAGE_ACTIVATE; 1196 1197 if (folio_clear_dirty_for_io(folio)) { 1198 int res; 1199 struct writeback_control wbc = { 1200 .sync_mode = WB_SYNC_NONE, 1201 .nr_to_write = SWAP_CLUSTER_MAX, 1202 .range_start = 0, 1203 .range_end = LLONG_MAX, 1204 .for_reclaim = 1, 1205 .swap_plug = plug, 1206 }; 1207 1208 folio_set_reclaim(folio); 1209 res = mapping->a_ops->writepage(&folio->page, &wbc); 1210 if (res < 0) 1211 handle_write_error(mapping, folio, res); 1212 if (res == AOP_WRITEPAGE_ACTIVATE) { 1213 folio_clear_reclaim(folio); 1214 return PAGE_ACTIVATE; 1215 } 1216 1217 if (!folio_test_writeback(folio)) { 1218 /* synchronous write or broken a_ops? */ 1219 folio_clear_reclaim(folio); 1220 } 1221 trace_mm_vmscan_write_folio(folio); 1222 node_stat_add_folio(folio, NR_VMSCAN_WRITE); 1223 return PAGE_SUCCESS; 1224 } 1225 1226 return PAGE_CLEAN; 1227 } 1228 1229 /* 1230 * Same as remove_mapping, but if the page is removed from the mapping, it 1231 * gets returned with a refcount of 0. 1232 */ 1233 static int __remove_mapping(struct address_space *mapping, struct folio *folio, 1234 bool reclaimed, struct mem_cgroup *target_memcg) 1235 { 1236 int refcount; 1237 void *shadow = NULL; 1238 1239 BUG_ON(!folio_test_locked(folio)); 1240 BUG_ON(mapping != folio_mapping(folio)); 1241 1242 if (!folio_test_swapcache(folio)) 1243 spin_lock(&mapping->host->i_lock); 1244 xa_lock_irq(&mapping->i_pages); 1245 /* 1246 * The non racy check for a busy page. 1247 * 1248 * Must be careful with the order of the tests. When someone has 1249 * a ref to the page, it may be possible that they dirty it then 1250 * drop the reference. So if PageDirty is tested before page_count 1251 * here, then the following race may occur: 1252 * 1253 * get_user_pages(&page); 1254 * [user mapping goes away] 1255 * write_to(page); 1256 * !PageDirty(page) [good] 1257 * SetPageDirty(page); 1258 * put_page(page); 1259 * !page_count(page) [good, discard it] 1260 * 1261 * [oops, our write_to data is lost] 1262 * 1263 * Reversing the order of the tests ensures such a situation cannot 1264 * escape unnoticed. The smp_rmb is needed to ensure the page->flags 1265 * load is not satisfied before that of page->_refcount. 1266 * 1267 * Note that if SetPageDirty is always performed via set_page_dirty, 1268 * and thus under the i_pages lock, then this ordering is not required. 1269 */ 1270 refcount = 1 + folio_nr_pages(folio); 1271 if (!folio_ref_freeze(folio, refcount)) 1272 goto cannot_free; 1273 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */ 1274 if (unlikely(folio_test_dirty(folio))) { 1275 folio_ref_unfreeze(folio, refcount); 1276 goto cannot_free; 1277 } 1278 1279 if (folio_test_swapcache(folio)) { 1280 swp_entry_t swap = folio_swap_entry(folio); 1281 mem_cgroup_swapout(folio, swap); 1282 if (reclaimed && !mapping_exiting(mapping)) 1283 shadow = workingset_eviction(folio, target_memcg); 1284 __delete_from_swap_cache(&folio->page, swap, shadow); 1285 xa_unlock_irq(&mapping->i_pages); 1286 put_swap_page(&folio->page, swap); 1287 } else { 1288 void (*freepage)(struct page *); 1289 1290 freepage = mapping->a_ops->freepage; 1291 /* 1292 * Remember a shadow entry for reclaimed file cache in 1293 * order to detect refaults, thus thrashing, later on. 1294 * 1295 * But don't store shadows in an address space that is 1296 * already exiting. This is not just an optimization, 1297 * inode reclaim needs to empty out the radix tree or 1298 * the nodes are lost. Don't plant shadows behind its 1299 * back. 1300 * 1301 * We also don't store shadows for DAX mappings because the 1302 * only page cache pages found in these are zero pages 1303 * covering holes, and because we don't want to mix DAX 1304 * exceptional entries and shadow exceptional entries in the 1305 * same address_space. 1306 */ 1307 if (reclaimed && folio_is_file_lru(folio) && 1308 !mapping_exiting(mapping) && !dax_mapping(mapping)) 1309 shadow = workingset_eviction(folio, target_memcg); 1310 __filemap_remove_folio(folio, shadow); 1311 xa_unlock_irq(&mapping->i_pages); 1312 if (mapping_shrinkable(mapping)) 1313 inode_add_lru(mapping->host); 1314 spin_unlock(&mapping->host->i_lock); 1315 1316 if (freepage != NULL) 1317 freepage(&folio->page); 1318 } 1319 1320 return 1; 1321 1322 cannot_free: 1323 xa_unlock_irq(&mapping->i_pages); 1324 if (!folio_test_swapcache(folio)) 1325 spin_unlock(&mapping->host->i_lock); 1326 return 0; 1327 } 1328 1329 /** 1330 * remove_mapping() - Attempt to remove a folio from its mapping. 1331 * @mapping: The address space. 1332 * @folio: The folio to remove. 1333 * 1334 * If the folio is dirty, under writeback or if someone else has a ref 1335 * on it, removal will fail. 1336 * Return: The number of pages removed from the mapping. 0 if the folio 1337 * could not be removed. 1338 * Context: The caller should have a single refcount on the folio and 1339 * hold its lock. 1340 */ 1341 long remove_mapping(struct address_space *mapping, struct folio *folio) 1342 { 1343 if (__remove_mapping(mapping, folio, false, NULL)) { 1344 /* 1345 * Unfreezing the refcount with 1 effectively 1346 * drops the pagecache ref for us without requiring another 1347 * atomic operation. 1348 */ 1349 folio_ref_unfreeze(folio, 1); 1350 return folio_nr_pages(folio); 1351 } 1352 return 0; 1353 } 1354 1355 /** 1356 * folio_putback_lru - Put previously isolated folio onto appropriate LRU list. 1357 * @folio: Folio to be returned to an LRU list. 1358 * 1359 * Add previously isolated @folio to appropriate LRU list. 1360 * The folio may still be unevictable for other reasons. 1361 * 1362 * Context: lru_lock must not be held, interrupts must be enabled. 1363 */ 1364 void folio_putback_lru(struct folio *folio) 1365 { 1366 folio_add_lru(folio); 1367 folio_put(folio); /* drop ref from isolate */ 1368 } 1369 1370 enum page_references { 1371 PAGEREF_RECLAIM, 1372 PAGEREF_RECLAIM_CLEAN, 1373 PAGEREF_KEEP, 1374 PAGEREF_ACTIVATE, 1375 }; 1376 1377 static enum page_references folio_check_references(struct folio *folio, 1378 struct scan_control *sc) 1379 { 1380 int referenced_ptes, referenced_folio; 1381 unsigned long vm_flags; 1382 1383 referenced_ptes = folio_referenced(folio, 1, sc->target_mem_cgroup, 1384 &vm_flags); 1385 referenced_folio = folio_test_clear_referenced(folio); 1386 1387 /* 1388 * The supposedly reclaimable folio was found to be in a VM_LOCKED vma. 1389 * Let the folio, now marked Mlocked, be moved to the unevictable list. 1390 */ 1391 if (vm_flags & VM_LOCKED) 1392 return PAGEREF_ACTIVATE; 1393 1394 if (referenced_ptes) { 1395 /* 1396 * All mapped folios start out with page table 1397 * references from the instantiating fault, so we need 1398 * to look twice if a mapped file/anon folio is used more 1399 * than once. 1400 * 1401 * Mark it and spare it for another trip around the 1402 * inactive list. Another page table reference will 1403 * lead to its activation. 1404 * 1405 * Note: the mark is set for activated folios as well 1406 * so that recently deactivated but used folios are 1407 * quickly recovered. 1408 */ 1409 folio_set_referenced(folio); 1410 1411 if (referenced_folio || referenced_ptes > 1) 1412 return PAGEREF_ACTIVATE; 1413 1414 /* 1415 * Activate file-backed executable folios after first usage. 1416 */ 1417 if ((vm_flags & VM_EXEC) && !folio_test_swapbacked(folio)) 1418 return PAGEREF_ACTIVATE; 1419 1420 return PAGEREF_KEEP; 1421 } 1422 1423 /* Reclaim if clean, defer dirty folios to writeback */ 1424 if (referenced_folio && !folio_test_swapbacked(folio)) 1425 return PAGEREF_RECLAIM_CLEAN; 1426 1427 return PAGEREF_RECLAIM; 1428 } 1429 1430 /* Check if a page is dirty or under writeback */ 1431 static void folio_check_dirty_writeback(struct folio *folio, 1432 bool *dirty, bool *writeback) 1433 { 1434 struct address_space *mapping; 1435 1436 /* 1437 * Anonymous pages are not handled by flushers and must be written 1438 * from reclaim context. Do not stall reclaim based on them. 1439 * MADV_FREE anonymous pages are put into inactive file list too. 1440 * They could be mistakenly treated as file lru. So further anon 1441 * test is needed. 1442 */ 1443 if (!folio_is_file_lru(folio) || 1444 (folio_test_anon(folio) && !folio_test_swapbacked(folio))) { 1445 *dirty = false; 1446 *writeback = false; 1447 return; 1448 } 1449 1450 /* By default assume that the folio flags are accurate */ 1451 *dirty = folio_test_dirty(folio); 1452 *writeback = folio_test_writeback(folio); 1453 1454 /* Verify dirty/writeback state if the filesystem supports it */ 1455 if (!folio_test_private(folio)) 1456 return; 1457 1458 mapping = folio_mapping(folio); 1459 if (mapping && mapping->a_ops->is_dirty_writeback) 1460 mapping->a_ops->is_dirty_writeback(&folio->page, dirty, writeback); 1461 } 1462 1463 static struct page *alloc_demote_page(struct page *page, unsigned long node) 1464 { 1465 struct migration_target_control mtc = { 1466 /* 1467 * Allocate from 'node', or fail quickly and quietly. 1468 * When this happens, 'page' will likely just be discarded 1469 * instead of migrated. 1470 */ 1471 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) | 1472 __GFP_THISNODE | __GFP_NOWARN | 1473 __GFP_NOMEMALLOC | GFP_NOWAIT, 1474 .nid = node 1475 }; 1476 1477 return alloc_migration_target(page, (unsigned long)&mtc); 1478 } 1479 1480 /* 1481 * Take pages on @demote_list and attempt to demote them to 1482 * another node. Pages which are not demoted are left on 1483 * @demote_pages. 1484 */ 1485 static unsigned int demote_page_list(struct list_head *demote_pages, 1486 struct pglist_data *pgdat) 1487 { 1488 int target_nid = next_demotion_node(pgdat->node_id); 1489 unsigned int nr_succeeded; 1490 1491 if (list_empty(demote_pages)) 1492 return 0; 1493 1494 if (target_nid == NUMA_NO_NODE) 1495 return 0; 1496 1497 /* Demotion ignores all cpuset and mempolicy settings */ 1498 migrate_pages(demote_pages, alloc_demote_page, NULL, 1499 target_nid, MIGRATE_ASYNC, MR_DEMOTION, 1500 &nr_succeeded); 1501 1502 if (current_is_kswapd()) 1503 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded); 1504 else 1505 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded); 1506 1507 return nr_succeeded; 1508 } 1509 1510 static bool may_enter_fs(struct page *page, gfp_t gfp_mask) 1511 { 1512 if (gfp_mask & __GFP_FS) 1513 return true; 1514 if (!PageSwapCache(page) || !(gfp_mask & __GFP_IO)) 1515 return false; 1516 /* 1517 * We can "enter_fs" for swap-cache with only __GFP_IO 1518 * providing this isn't SWP_FS_OPS. 1519 * ->flags can be updated non-atomicially (scan_swap_map_slots), 1520 * but that will never affect SWP_FS_OPS, so the data_race 1521 * is safe. 1522 */ 1523 return !data_race(page_swap_flags(page) & SWP_FS_OPS); 1524 } 1525 1526 /* 1527 * shrink_page_list() returns the number of reclaimed pages 1528 */ 1529 static unsigned int shrink_page_list(struct list_head *page_list, 1530 struct pglist_data *pgdat, 1531 struct scan_control *sc, 1532 struct reclaim_stat *stat, 1533 bool ignore_references) 1534 { 1535 LIST_HEAD(ret_pages); 1536 LIST_HEAD(free_pages); 1537 LIST_HEAD(demote_pages); 1538 unsigned int nr_reclaimed = 0; 1539 unsigned int pgactivate = 0; 1540 bool do_demote_pass; 1541 struct swap_iocb *plug = NULL; 1542 1543 memset(stat, 0, sizeof(*stat)); 1544 cond_resched(); 1545 do_demote_pass = can_demote(pgdat->node_id, sc); 1546 1547 retry: 1548 while (!list_empty(page_list)) { 1549 struct address_space *mapping; 1550 struct page *page; 1551 struct folio *folio; 1552 enum page_references references = PAGEREF_RECLAIM; 1553 bool dirty, writeback; 1554 unsigned int nr_pages; 1555 1556 cond_resched(); 1557 1558 folio = lru_to_folio(page_list); 1559 list_del(&folio->lru); 1560 page = &folio->page; 1561 1562 if (!trylock_page(page)) 1563 goto keep; 1564 1565 VM_BUG_ON_PAGE(PageActive(page), page); 1566 1567 nr_pages = compound_nr(page); 1568 1569 /* Account the number of base pages even though THP */ 1570 sc->nr_scanned += nr_pages; 1571 1572 if (unlikely(!page_evictable(page))) 1573 goto activate_locked; 1574 1575 if (!sc->may_unmap && page_mapped(page)) 1576 goto keep_locked; 1577 1578 /* 1579 * The number of dirty pages determines if a node is marked 1580 * reclaim_congested. kswapd will stall and start writing 1581 * pages if the tail of the LRU is all dirty unqueued pages. 1582 */ 1583 folio_check_dirty_writeback(folio, &dirty, &writeback); 1584 if (dirty || writeback) 1585 stat->nr_dirty += nr_pages; 1586 1587 if (dirty && !writeback) 1588 stat->nr_unqueued_dirty += nr_pages; 1589 1590 /* 1591 * Treat this page as congested if the underlying BDI is or if 1592 * pages are cycling through the LRU so quickly that the 1593 * pages marked for immediate reclaim are making it to the 1594 * end of the LRU a second time. 1595 */ 1596 mapping = page_mapping(page); 1597 if (writeback && PageReclaim(page)) 1598 stat->nr_congested += nr_pages; 1599 1600 /* 1601 * If a page at the tail of the LRU is under writeback, there 1602 * are three cases to consider. 1603 * 1604 * 1) If reclaim is encountering an excessive number of pages 1605 * under writeback and this page is both under writeback and 1606 * PageReclaim then it indicates that pages are being queued 1607 * for IO but are being recycled through the LRU before the 1608 * IO can complete. Waiting on the page itself risks an 1609 * indefinite stall if it is impossible to writeback the 1610 * page due to IO error or disconnected storage so instead 1611 * note that the LRU is being scanned too quickly and the 1612 * caller can stall after page list has been processed. 1613 * 1614 * 2) Global or new memcg reclaim encounters a page that is 1615 * not marked for immediate reclaim, or the caller does not 1616 * have __GFP_FS (or __GFP_IO if it's simply going to swap, 1617 * not to fs). In this case mark the page for immediate 1618 * reclaim and continue scanning. 1619 * 1620 * Require may_enter_fs() because we would wait on fs, which 1621 * may not have submitted IO yet. And the loop driver might 1622 * enter reclaim, and deadlock if it waits on a page for 1623 * which it is needed to do the write (loop masks off 1624 * __GFP_IO|__GFP_FS for this reason); but more thought 1625 * would probably show more reasons. 1626 * 1627 * 3) Legacy memcg encounters a page that is already marked 1628 * PageReclaim. memcg does not have any dirty pages 1629 * throttling so we could easily OOM just because too many 1630 * pages are in writeback and there is nothing else to 1631 * reclaim. Wait for the writeback to complete. 1632 * 1633 * In cases 1) and 2) we activate the pages to get them out of 1634 * the way while we continue scanning for clean pages on the 1635 * inactive list and refilling from the active list. The 1636 * observation here is that waiting for disk writes is more 1637 * expensive than potentially causing reloads down the line. 1638 * Since they're marked for immediate reclaim, they won't put 1639 * memory pressure on the cache working set any longer than it 1640 * takes to write them to disk. 1641 */ 1642 if (PageWriteback(page)) { 1643 /* Case 1 above */ 1644 if (current_is_kswapd() && 1645 PageReclaim(page) && 1646 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) { 1647 stat->nr_immediate += nr_pages; 1648 goto activate_locked; 1649 1650 /* Case 2 above */ 1651 } else if (writeback_throttling_sane(sc) || 1652 !PageReclaim(page) || !may_enter_fs(page, sc->gfp_mask)) { 1653 /* 1654 * This is slightly racy - end_page_writeback() 1655 * might have just cleared PageReclaim, then 1656 * setting PageReclaim here end up interpreted 1657 * as PageReadahead - but that does not matter 1658 * enough to care. What we do want is for this 1659 * page to have PageReclaim set next time memcg 1660 * reclaim reaches the tests above, so it will 1661 * then wait_on_page_writeback() to avoid OOM; 1662 * and it's also appropriate in global reclaim. 1663 */ 1664 SetPageReclaim(page); 1665 stat->nr_writeback += nr_pages; 1666 goto activate_locked; 1667 1668 /* Case 3 above */ 1669 } else { 1670 unlock_page(page); 1671 wait_on_page_writeback(page); 1672 /* then go back and try same page again */ 1673 list_add_tail(&page->lru, page_list); 1674 continue; 1675 } 1676 } 1677 1678 if (!ignore_references) 1679 references = folio_check_references(folio, sc); 1680 1681 switch (references) { 1682 case PAGEREF_ACTIVATE: 1683 goto activate_locked; 1684 case PAGEREF_KEEP: 1685 stat->nr_ref_keep += nr_pages; 1686 goto keep_locked; 1687 case PAGEREF_RECLAIM: 1688 case PAGEREF_RECLAIM_CLEAN: 1689 ; /* try to reclaim the page below */ 1690 } 1691 1692 /* 1693 * Before reclaiming the page, try to relocate 1694 * its contents to another node. 1695 */ 1696 if (do_demote_pass && 1697 (thp_migration_supported() || !PageTransHuge(page))) { 1698 list_add(&page->lru, &demote_pages); 1699 unlock_page(page); 1700 continue; 1701 } 1702 1703 /* 1704 * Anonymous process memory has backing store? 1705 * Try to allocate it some swap space here. 1706 * Lazyfree page could be freed directly 1707 */ 1708 if (PageAnon(page) && PageSwapBacked(page)) { 1709 if (!PageSwapCache(page)) { 1710 if (!(sc->gfp_mask & __GFP_IO)) 1711 goto keep_locked; 1712 if (folio_maybe_dma_pinned(folio)) 1713 goto keep_locked; 1714 if (PageTransHuge(page)) { 1715 /* cannot split THP, skip it */ 1716 if (!can_split_folio(folio, NULL)) 1717 goto activate_locked; 1718 /* 1719 * Split pages without a PMD map right 1720 * away. Chances are some or all of the 1721 * tail pages can be freed without IO. 1722 */ 1723 if (!folio_entire_mapcount(folio) && 1724 split_folio_to_list(folio, 1725 page_list)) 1726 goto activate_locked; 1727 } 1728 if (!add_to_swap(page)) { 1729 if (!PageTransHuge(page)) 1730 goto activate_locked_split; 1731 /* Fallback to swap normal pages */ 1732 if (split_folio_to_list(folio, 1733 page_list)) 1734 goto activate_locked; 1735 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 1736 count_vm_event(THP_SWPOUT_FALLBACK); 1737 #endif 1738 if (!add_to_swap(page)) 1739 goto activate_locked_split; 1740 } 1741 1742 /* Adding to swap updated mapping */ 1743 mapping = page_mapping(page); 1744 } 1745 } else if (PageSwapBacked(page) && PageTransHuge(page)) { 1746 /* Split shmem THP */ 1747 if (split_folio_to_list(folio, page_list)) 1748 goto keep_locked; 1749 } 1750 1751 /* 1752 * THP may get split above, need minus tail pages and update 1753 * nr_pages to avoid accounting tail pages twice. 1754 * 1755 * The tail pages that are added into swap cache successfully 1756 * reach here. 1757 */ 1758 if ((nr_pages > 1) && !PageTransHuge(page)) { 1759 sc->nr_scanned -= (nr_pages - 1); 1760 nr_pages = 1; 1761 } 1762 1763 /* 1764 * The page is mapped into the page tables of one or more 1765 * processes. Try to unmap it here. 1766 */ 1767 if (page_mapped(page)) { 1768 enum ttu_flags flags = TTU_BATCH_FLUSH; 1769 bool was_swapbacked = PageSwapBacked(page); 1770 1771 if (PageTransHuge(page) && 1772 thp_order(page) >= HPAGE_PMD_ORDER) 1773 flags |= TTU_SPLIT_HUGE_PMD; 1774 1775 try_to_unmap(folio, flags); 1776 if (page_mapped(page)) { 1777 stat->nr_unmap_fail += nr_pages; 1778 if (!was_swapbacked && PageSwapBacked(page)) 1779 stat->nr_lazyfree_fail += nr_pages; 1780 goto activate_locked; 1781 } 1782 } 1783 1784 if (PageDirty(page)) { 1785 /* 1786 * Only kswapd can writeback filesystem pages 1787 * to avoid risk of stack overflow. But avoid 1788 * injecting inefficient single-page IO into 1789 * flusher writeback as much as possible: only 1790 * write pages when we've encountered many 1791 * dirty pages, and when we've already scanned 1792 * the rest of the LRU for clean pages and see 1793 * the same dirty pages again (PageReclaim). 1794 */ 1795 if (page_is_file_lru(page) && 1796 (!current_is_kswapd() || !PageReclaim(page) || 1797 !test_bit(PGDAT_DIRTY, &pgdat->flags))) { 1798 /* 1799 * Immediately reclaim when written back. 1800 * Similar in principal to deactivate_page() 1801 * except we already have the page isolated 1802 * and know it's dirty 1803 */ 1804 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE); 1805 SetPageReclaim(page); 1806 1807 goto activate_locked; 1808 } 1809 1810 if (references == PAGEREF_RECLAIM_CLEAN) 1811 goto keep_locked; 1812 if (!may_enter_fs(page, sc->gfp_mask)) 1813 goto keep_locked; 1814 if (!sc->may_writepage) 1815 goto keep_locked; 1816 1817 /* 1818 * Page is dirty. Flush the TLB if a writable entry 1819 * potentially exists to avoid CPU writes after IO 1820 * starts and then write it out here. 1821 */ 1822 try_to_unmap_flush_dirty(); 1823 switch (pageout(folio, mapping, &plug)) { 1824 case PAGE_KEEP: 1825 goto keep_locked; 1826 case PAGE_ACTIVATE: 1827 goto activate_locked; 1828 case PAGE_SUCCESS: 1829 stat->nr_pageout += nr_pages; 1830 1831 if (PageWriteback(page)) 1832 goto keep; 1833 if (PageDirty(page)) 1834 goto keep; 1835 1836 /* 1837 * A synchronous write - probably a ramdisk. Go 1838 * ahead and try to reclaim the page. 1839 */ 1840 if (!trylock_page(page)) 1841 goto keep; 1842 if (PageDirty(page) || PageWriteback(page)) 1843 goto keep_locked; 1844 mapping = page_mapping(page); 1845 fallthrough; 1846 case PAGE_CLEAN: 1847 ; /* try to free the page below */ 1848 } 1849 } 1850 1851 /* 1852 * If the page has buffers, try to free the buffer mappings 1853 * associated with this page. If we succeed we try to free 1854 * the page as well. 1855 * 1856 * We do this even if the page is PageDirty(). 1857 * try_to_release_page() does not perform I/O, but it is 1858 * possible for a page to have PageDirty set, but it is actually 1859 * clean (all its buffers are clean). This happens if the 1860 * buffers were written out directly, with submit_bh(). ext3 1861 * will do this, as well as the blockdev mapping. 1862 * try_to_release_page() will discover that cleanness and will 1863 * drop the buffers and mark the page clean - it can be freed. 1864 * 1865 * Rarely, pages can have buffers and no ->mapping. These are 1866 * the pages which were not successfully invalidated in 1867 * truncate_cleanup_page(). We try to drop those buffers here 1868 * and if that worked, and the page is no longer mapped into 1869 * process address space (page_count == 1) it can be freed. 1870 * Otherwise, leave the page on the LRU so it is swappable. 1871 */ 1872 if (page_has_private(page)) { 1873 if (!try_to_release_page(page, sc->gfp_mask)) 1874 goto activate_locked; 1875 if (!mapping && page_count(page) == 1) { 1876 unlock_page(page); 1877 if (put_page_testzero(page)) 1878 goto free_it; 1879 else { 1880 /* 1881 * rare race with speculative reference. 1882 * the speculative reference will free 1883 * this page shortly, so we may 1884 * increment nr_reclaimed here (and 1885 * leave it off the LRU). 1886 */ 1887 nr_reclaimed++; 1888 continue; 1889 } 1890 } 1891 } 1892 1893 if (PageAnon(page) && !PageSwapBacked(page)) { 1894 /* follow __remove_mapping for reference */ 1895 if (!page_ref_freeze(page, 1)) 1896 goto keep_locked; 1897 /* 1898 * The page has only one reference left, which is 1899 * from the isolation. After the caller puts the 1900 * page back on lru and drops the reference, the 1901 * page will be freed anyway. It doesn't matter 1902 * which lru it goes. So we don't bother checking 1903 * PageDirty here. 1904 */ 1905 count_vm_event(PGLAZYFREED); 1906 count_memcg_page_event(page, PGLAZYFREED); 1907 } else if (!mapping || !__remove_mapping(mapping, folio, true, 1908 sc->target_mem_cgroup)) 1909 goto keep_locked; 1910 1911 unlock_page(page); 1912 free_it: 1913 /* 1914 * THP may get swapped out in a whole, need account 1915 * all base pages. 1916 */ 1917 nr_reclaimed += nr_pages; 1918 1919 /* 1920 * Is there need to periodically free_page_list? It would 1921 * appear not as the counts should be low 1922 */ 1923 if (unlikely(PageTransHuge(page))) 1924 destroy_compound_page(page); 1925 else 1926 list_add(&page->lru, &free_pages); 1927 continue; 1928 1929 activate_locked_split: 1930 /* 1931 * The tail pages that are failed to add into swap cache 1932 * reach here. Fixup nr_scanned and nr_pages. 1933 */ 1934 if (nr_pages > 1) { 1935 sc->nr_scanned -= (nr_pages - 1); 1936 nr_pages = 1; 1937 } 1938 activate_locked: 1939 /* Not a candidate for swapping, so reclaim swap space. */ 1940 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) || 1941 PageMlocked(page))) 1942 try_to_free_swap(page); 1943 VM_BUG_ON_PAGE(PageActive(page), page); 1944 if (!PageMlocked(page)) { 1945 int type = page_is_file_lru(page); 1946 SetPageActive(page); 1947 stat->nr_activate[type] += nr_pages; 1948 count_memcg_page_event(page, PGACTIVATE); 1949 } 1950 keep_locked: 1951 unlock_page(page); 1952 keep: 1953 list_add(&page->lru, &ret_pages); 1954 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page); 1955 } 1956 /* 'page_list' is always empty here */ 1957 1958 /* Migrate pages selected for demotion */ 1959 nr_reclaimed += demote_page_list(&demote_pages, pgdat); 1960 /* Pages that could not be demoted are still in @demote_pages */ 1961 if (!list_empty(&demote_pages)) { 1962 /* Pages which failed to demoted go back on @page_list for retry: */ 1963 list_splice_init(&demote_pages, page_list); 1964 do_demote_pass = false; 1965 goto retry; 1966 } 1967 1968 pgactivate = stat->nr_activate[0] + stat->nr_activate[1]; 1969 1970 mem_cgroup_uncharge_list(&free_pages); 1971 try_to_unmap_flush(); 1972 free_unref_page_list(&free_pages); 1973 1974 list_splice(&ret_pages, page_list); 1975 count_vm_events(PGACTIVATE, pgactivate); 1976 1977 if (plug) 1978 swap_write_unplug(plug); 1979 return nr_reclaimed; 1980 } 1981 1982 unsigned int reclaim_clean_pages_from_list(struct zone *zone, 1983 struct list_head *page_list) 1984 { 1985 struct scan_control sc = { 1986 .gfp_mask = GFP_KERNEL, 1987 .may_unmap = 1, 1988 }; 1989 struct reclaim_stat stat; 1990 unsigned int nr_reclaimed; 1991 struct page *page, *next; 1992 LIST_HEAD(clean_pages); 1993 unsigned int noreclaim_flag; 1994 1995 list_for_each_entry_safe(page, next, page_list, lru) { 1996 if (!PageHuge(page) && page_is_file_lru(page) && 1997 !PageDirty(page) && !__PageMovable(page) && 1998 !PageUnevictable(page)) { 1999 ClearPageActive(page); 2000 list_move(&page->lru, &clean_pages); 2001 } 2002 } 2003 2004 /* 2005 * We should be safe here since we are only dealing with file pages and 2006 * we are not kswapd and therefore cannot write dirty file pages. But 2007 * call memalloc_noreclaim_save() anyway, just in case these conditions 2008 * change in the future. 2009 */ 2010 noreclaim_flag = memalloc_noreclaim_save(); 2011 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc, 2012 &stat, true); 2013 memalloc_noreclaim_restore(noreclaim_flag); 2014 2015 list_splice(&clean_pages, page_list); 2016 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, 2017 -(long)nr_reclaimed); 2018 /* 2019 * Since lazyfree pages are isolated from file LRU from the beginning, 2020 * they will rotate back to anonymous LRU in the end if it failed to 2021 * discard so isolated count will be mismatched. 2022 * Compensate the isolated count for both LRU lists. 2023 */ 2024 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON, 2025 stat.nr_lazyfree_fail); 2026 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, 2027 -(long)stat.nr_lazyfree_fail); 2028 return nr_reclaimed; 2029 } 2030 2031 /* 2032 * Update LRU sizes after isolating pages. The LRU size updates must 2033 * be complete before mem_cgroup_update_lru_size due to a sanity check. 2034 */ 2035 static __always_inline void update_lru_sizes(struct lruvec *lruvec, 2036 enum lru_list lru, unsigned long *nr_zone_taken) 2037 { 2038 int zid; 2039 2040 for (zid = 0; zid < MAX_NR_ZONES; zid++) { 2041 if (!nr_zone_taken[zid]) 2042 continue; 2043 2044 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]); 2045 } 2046 2047 } 2048 2049 /* 2050 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times. 2051 * 2052 * lruvec->lru_lock is heavily contended. Some of the functions that 2053 * shrink the lists perform better by taking out a batch of pages 2054 * and working on them outside the LRU lock. 2055 * 2056 * For pagecache intensive workloads, this function is the hottest 2057 * spot in the kernel (apart from copy_*_user functions). 2058 * 2059 * Lru_lock must be held before calling this function. 2060 * 2061 * @nr_to_scan: The number of eligible pages to look through on the list. 2062 * @lruvec: The LRU vector to pull pages from. 2063 * @dst: The temp list to put pages on to. 2064 * @nr_scanned: The number of pages that were scanned. 2065 * @sc: The scan_control struct for this reclaim session 2066 * @lru: LRU list id for isolating 2067 * 2068 * returns how many pages were moved onto *@dst. 2069 */ 2070 static unsigned long isolate_lru_pages(unsigned long nr_to_scan, 2071 struct lruvec *lruvec, struct list_head *dst, 2072 unsigned long *nr_scanned, struct scan_control *sc, 2073 enum lru_list lru) 2074 { 2075 struct list_head *src = &lruvec->lists[lru]; 2076 unsigned long nr_taken = 0; 2077 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 }; 2078 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, }; 2079 unsigned long skipped = 0; 2080 unsigned long scan, total_scan, nr_pages; 2081 LIST_HEAD(pages_skipped); 2082 2083 total_scan = 0; 2084 scan = 0; 2085 while (scan < nr_to_scan && !list_empty(src)) { 2086 struct list_head *move_to = src; 2087 struct page *page; 2088 2089 page = lru_to_page(src); 2090 prefetchw_prev_lru_page(page, src, flags); 2091 2092 nr_pages = compound_nr(page); 2093 total_scan += nr_pages; 2094 2095 if (page_zonenum(page) > sc->reclaim_idx) { 2096 nr_skipped[page_zonenum(page)] += nr_pages; 2097 move_to = &pages_skipped; 2098 goto move; 2099 } 2100 2101 /* 2102 * Do not count skipped pages because that makes the function 2103 * return with no isolated pages if the LRU mostly contains 2104 * ineligible pages. This causes the VM to not reclaim any 2105 * pages, triggering a premature OOM. 2106 * Account all tail pages of THP. 2107 */ 2108 scan += nr_pages; 2109 2110 if (!PageLRU(page)) 2111 goto move; 2112 if (!sc->may_unmap && page_mapped(page)) 2113 goto move; 2114 2115 /* 2116 * Be careful not to clear PageLRU until after we're 2117 * sure the page is not being freed elsewhere -- the 2118 * page release code relies on it. 2119 */ 2120 if (unlikely(!get_page_unless_zero(page))) 2121 goto move; 2122 2123 if (!TestClearPageLRU(page)) { 2124 /* Another thread is already isolating this page */ 2125 put_page(page); 2126 goto move; 2127 } 2128 2129 nr_taken += nr_pages; 2130 nr_zone_taken[page_zonenum(page)] += nr_pages; 2131 move_to = dst; 2132 move: 2133 list_move(&page->lru, move_to); 2134 } 2135 2136 /* 2137 * Splice any skipped pages to the start of the LRU list. Note that 2138 * this disrupts the LRU order when reclaiming for lower zones but 2139 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX 2140 * scanning would soon rescan the same pages to skip and waste lots 2141 * of cpu cycles. 2142 */ 2143 if (!list_empty(&pages_skipped)) { 2144 int zid; 2145 2146 list_splice(&pages_skipped, src); 2147 for (zid = 0; zid < MAX_NR_ZONES; zid++) { 2148 if (!nr_skipped[zid]) 2149 continue; 2150 2151 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]); 2152 skipped += nr_skipped[zid]; 2153 } 2154 } 2155 *nr_scanned = total_scan; 2156 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan, 2157 total_scan, skipped, nr_taken, 2158 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru); 2159 update_lru_sizes(lruvec, lru, nr_zone_taken); 2160 return nr_taken; 2161 } 2162 2163 /** 2164 * folio_isolate_lru() - Try to isolate a folio from its LRU list. 2165 * @folio: Folio to isolate from its LRU list. 2166 * 2167 * Isolate a @folio from an LRU list and adjust the vmstat statistic 2168 * corresponding to whatever LRU list the folio was on. 2169 * 2170 * The folio will have its LRU flag cleared. If it was found on the 2171 * active list, it will have the Active flag set. If it was found on the 2172 * unevictable list, it will have the Unevictable flag set. These flags 2173 * may need to be cleared by the caller before letting the page go. 2174 * 2175 * Context: 2176 * 2177 * (1) Must be called with an elevated refcount on the page. This is a 2178 * fundamental difference from isolate_lru_pages() (which is called 2179 * without a stable reference). 2180 * (2) The lru_lock must not be held. 2181 * (3) Interrupts must be enabled. 2182 * 2183 * Return: 0 if the folio was removed from an LRU list. 2184 * -EBUSY if the folio was not on an LRU list. 2185 */ 2186 int folio_isolate_lru(struct folio *folio) 2187 { 2188 int ret = -EBUSY; 2189 2190 VM_BUG_ON_FOLIO(!folio_ref_count(folio), folio); 2191 2192 if (folio_test_clear_lru(folio)) { 2193 struct lruvec *lruvec; 2194 2195 folio_get(folio); 2196 lruvec = folio_lruvec_lock_irq(folio); 2197 lruvec_del_folio(lruvec, folio); 2198 unlock_page_lruvec_irq(lruvec); 2199 ret = 0; 2200 } 2201 2202 return ret; 2203 } 2204 2205 /* 2206 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and 2207 * then get rescheduled. When there are massive number of tasks doing page 2208 * allocation, such sleeping direct reclaimers may keep piling up on each CPU, 2209 * the LRU list will go small and be scanned faster than necessary, leading to 2210 * unnecessary swapping, thrashing and OOM. 2211 */ 2212 static int too_many_isolated(struct pglist_data *pgdat, int file, 2213 struct scan_control *sc) 2214 { 2215 unsigned long inactive, isolated; 2216 bool too_many; 2217 2218 if (current_is_kswapd()) 2219 return 0; 2220 2221 if (!writeback_throttling_sane(sc)) 2222 return 0; 2223 2224 if (file) { 2225 inactive = node_page_state(pgdat, NR_INACTIVE_FILE); 2226 isolated = node_page_state(pgdat, NR_ISOLATED_FILE); 2227 } else { 2228 inactive = node_page_state(pgdat, NR_INACTIVE_ANON); 2229 isolated = node_page_state(pgdat, NR_ISOLATED_ANON); 2230 } 2231 2232 /* 2233 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they 2234 * won't get blocked by normal direct-reclaimers, forming a circular 2235 * deadlock. 2236 */ 2237 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS)) 2238 inactive >>= 3; 2239 2240 too_many = isolated > inactive; 2241 2242 /* Wake up tasks throttled due to too_many_isolated. */ 2243 if (!too_many) 2244 wake_throttle_isolated(pgdat); 2245 2246 return too_many; 2247 } 2248 2249 /* 2250 * move_pages_to_lru() moves pages from private @list to appropriate LRU list. 2251 * On return, @list is reused as a list of pages to be freed by the caller. 2252 * 2253 * Returns the number of pages moved to the given lruvec. 2254 */ 2255 static unsigned int move_pages_to_lru(struct lruvec *lruvec, 2256 struct list_head *list) 2257 { 2258 int nr_pages, nr_moved = 0; 2259 LIST_HEAD(pages_to_free); 2260 struct page *page; 2261 2262 while (!list_empty(list)) { 2263 page = lru_to_page(list); 2264 VM_BUG_ON_PAGE(PageLRU(page), page); 2265 list_del(&page->lru); 2266 if (unlikely(!page_evictable(page))) { 2267 spin_unlock_irq(&lruvec->lru_lock); 2268 putback_lru_page(page); 2269 spin_lock_irq(&lruvec->lru_lock); 2270 continue; 2271 } 2272 2273 /* 2274 * The SetPageLRU needs to be kept here for list integrity. 2275 * Otherwise: 2276 * #0 move_pages_to_lru #1 release_pages 2277 * if !put_page_testzero 2278 * if (put_page_testzero()) 2279 * !PageLRU //skip lru_lock 2280 * SetPageLRU() 2281 * list_add(&page->lru,) 2282 * list_add(&page->lru,) 2283 */ 2284 SetPageLRU(page); 2285 2286 if (unlikely(put_page_testzero(page))) { 2287 __clear_page_lru_flags(page); 2288 2289 if (unlikely(PageCompound(page))) { 2290 spin_unlock_irq(&lruvec->lru_lock); 2291 destroy_compound_page(page); 2292 spin_lock_irq(&lruvec->lru_lock); 2293 } else 2294 list_add(&page->lru, &pages_to_free); 2295 2296 continue; 2297 } 2298 2299 /* 2300 * All pages were isolated from the same lruvec (and isolation 2301 * inhibits memcg migration). 2302 */ 2303 VM_BUG_ON_PAGE(!folio_matches_lruvec(page_folio(page), lruvec), page); 2304 add_page_to_lru_list(page, lruvec); 2305 nr_pages = thp_nr_pages(page); 2306 nr_moved += nr_pages; 2307 if (PageActive(page)) 2308 workingset_age_nonresident(lruvec, nr_pages); 2309 } 2310 2311 /* 2312 * To save our caller's stack, now use input list for pages to free. 2313 */ 2314 list_splice(&pages_to_free, list); 2315 2316 return nr_moved; 2317 } 2318 2319 /* 2320 * If a kernel thread (such as nfsd for loop-back mounts) services a backing 2321 * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case 2322 * we should not throttle. Otherwise it is safe to do so. 2323 */ 2324 static int current_may_throttle(void) 2325 { 2326 return !(current->flags & PF_LOCAL_THROTTLE); 2327 } 2328 2329 /* 2330 * shrink_inactive_list() is a helper for shrink_node(). It returns the number 2331 * of reclaimed pages 2332 */ 2333 static unsigned long 2334 shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec, 2335 struct scan_control *sc, enum lru_list lru) 2336 { 2337 LIST_HEAD(page_list); 2338 unsigned long nr_scanned; 2339 unsigned int nr_reclaimed = 0; 2340 unsigned long nr_taken; 2341 struct reclaim_stat stat; 2342 bool file = is_file_lru(lru); 2343 enum vm_event_item item; 2344 struct pglist_data *pgdat = lruvec_pgdat(lruvec); 2345 bool stalled = false; 2346 2347 while (unlikely(too_many_isolated(pgdat, file, sc))) { 2348 if (stalled) 2349 return 0; 2350 2351 /* wait a bit for the reclaimer. */ 2352 stalled = true; 2353 reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED); 2354 2355 /* We are about to die and free our memory. Return now. */ 2356 if (fatal_signal_pending(current)) 2357 return SWAP_CLUSTER_MAX; 2358 } 2359 2360 lru_add_drain(); 2361 2362 spin_lock_irq(&lruvec->lru_lock); 2363 2364 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list, 2365 &nr_scanned, sc, lru); 2366 2367 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken); 2368 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT; 2369 if (!cgroup_reclaim(sc)) 2370 __count_vm_events(item, nr_scanned); 2371 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned); 2372 __count_vm_events(PGSCAN_ANON + file, nr_scanned); 2373 2374 spin_unlock_irq(&lruvec->lru_lock); 2375 2376 if (nr_taken == 0) 2377 return 0; 2378 2379 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false); 2380 2381 spin_lock_irq(&lruvec->lru_lock); 2382 move_pages_to_lru(lruvec, &page_list); 2383 2384 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken); 2385 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT; 2386 if (!cgroup_reclaim(sc)) 2387 __count_vm_events(item, nr_reclaimed); 2388 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed); 2389 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed); 2390 spin_unlock_irq(&lruvec->lru_lock); 2391 2392 lru_note_cost(lruvec, file, stat.nr_pageout); 2393 mem_cgroup_uncharge_list(&page_list); 2394 free_unref_page_list(&page_list); 2395 2396 /* 2397 * If dirty pages are scanned that are not queued for IO, it 2398 * implies that flushers are not doing their job. This can 2399 * happen when memory pressure pushes dirty pages to the end of 2400 * the LRU before the dirty limits are breached and the dirty 2401 * data has expired. It can also happen when the proportion of 2402 * dirty pages grows not through writes but through memory 2403 * pressure reclaiming all the clean cache. And in some cases, 2404 * the flushers simply cannot keep up with the allocation 2405 * rate. Nudge the flusher threads in case they are asleep. 2406 */ 2407 if (stat.nr_unqueued_dirty == nr_taken) 2408 wakeup_flusher_threads(WB_REASON_VMSCAN); 2409 2410 sc->nr.dirty += stat.nr_dirty; 2411 sc->nr.congested += stat.nr_congested; 2412 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty; 2413 sc->nr.writeback += stat.nr_writeback; 2414 sc->nr.immediate += stat.nr_immediate; 2415 sc->nr.taken += nr_taken; 2416 if (file) 2417 sc->nr.file_taken += nr_taken; 2418 2419 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id, 2420 nr_scanned, nr_reclaimed, &stat, sc->priority, file); 2421 return nr_reclaimed; 2422 } 2423 2424 /* 2425 * shrink_active_list() moves pages from the active LRU to the inactive LRU. 2426 * 2427 * We move them the other way if the page is referenced by one or more 2428 * processes. 2429 * 2430 * If the pages are mostly unmapped, the processing is fast and it is 2431 * appropriate to hold lru_lock across the whole operation. But if 2432 * the pages are mapped, the processing is slow (folio_referenced()), so 2433 * we should drop lru_lock around each page. It's impossible to balance 2434 * this, so instead we remove the pages from the LRU while processing them. 2435 * It is safe to rely on PG_active against the non-LRU pages in here because 2436 * nobody will play with that bit on a non-LRU page. 2437 * 2438 * The downside is that we have to touch page->_refcount against each page. 2439 * But we had to alter page->flags anyway. 2440 */ 2441 static void shrink_active_list(unsigned long nr_to_scan, 2442 struct lruvec *lruvec, 2443 struct scan_control *sc, 2444 enum lru_list lru) 2445 { 2446 unsigned long nr_taken; 2447 unsigned long nr_scanned; 2448 unsigned long vm_flags; 2449 LIST_HEAD(l_hold); /* The pages which were snipped off */ 2450 LIST_HEAD(l_active); 2451 LIST_HEAD(l_inactive); 2452 unsigned nr_deactivate, nr_activate; 2453 unsigned nr_rotated = 0; 2454 int file = is_file_lru(lru); 2455 struct pglist_data *pgdat = lruvec_pgdat(lruvec); 2456 2457 lru_add_drain(); 2458 2459 spin_lock_irq(&lruvec->lru_lock); 2460 2461 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold, 2462 &nr_scanned, sc, lru); 2463 2464 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken); 2465 2466 if (!cgroup_reclaim(sc)) 2467 __count_vm_events(PGREFILL, nr_scanned); 2468 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned); 2469 2470 spin_unlock_irq(&lruvec->lru_lock); 2471 2472 while (!list_empty(&l_hold)) { 2473 struct folio *folio; 2474 struct page *page; 2475 2476 cond_resched(); 2477 folio = lru_to_folio(&l_hold); 2478 list_del(&folio->lru); 2479 page = &folio->page; 2480 2481 if (unlikely(!page_evictable(page))) { 2482 putback_lru_page(page); 2483 continue; 2484 } 2485 2486 if (unlikely(buffer_heads_over_limit)) { 2487 if (page_has_private(page) && trylock_page(page)) { 2488 if (page_has_private(page)) 2489 try_to_release_page(page, 0); 2490 unlock_page(page); 2491 } 2492 } 2493 2494 if (folio_referenced(folio, 0, sc->target_mem_cgroup, 2495 &vm_flags)) { 2496 /* 2497 * Identify referenced, file-backed active pages and 2498 * give them one more trip around the active list. So 2499 * that executable code get better chances to stay in 2500 * memory under moderate memory pressure. Anon pages 2501 * are not likely to be evicted by use-once streaming 2502 * IO, plus JVM can create lots of anon VM_EXEC pages, 2503 * so we ignore them here. 2504 */ 2505 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) { 2506 nr_rotated += thp_nr_pages(page); 2507 list_add(&page->lru, &l_active); 2508 continue; 2509 } 2510 } 2511 2512 ClearPageActive(page); /* we are de-activating */ 2513 SetPageWorkingset(page); 2514 list_add(&page->lru, &l_inactive); 2515 } 2516 2517 /* 2518 * Move pages back to the lru list. 2519 */ 2520 spin_lock_irq(&lruvec->lru_lock); 2521 2522 nr_activate = move_pages_to_lru(lruvec, &l_active); 2523 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive); 2524 /* Keep all free pages in l_active list */ 2525 list_splice(&l_inactive, &l_active); 2526 2527 __count_vm_events(PGDEACTIVATE, nr_deactivate); 2528 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate); 2529 2530 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken); 2531 spin_unlock_irq(&lruvec->lru_lock); 2532 2533 mem_cgroup_uncharge_list(&l_active); 2534 free_unref_page_list(&l_active); 2535 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate, 2536 nr_deactivate, nr_rotated, sc->priority, file); 2537 } 2538 2539 static unsigned int reclaim_page_list(struct list_head *page_list, 2540 struct pglist_data *pgdat) 2541 { 2542 struct reclaim_stat dummy_stat; 2543 unsigned int nr_reclaimed; 2544 struct folio *folio; 2545 struct scan_control sc = { 2546 .gfp_mask = GFP_KERNEL, 2547 .may_writepage = 1, 2548 .may_unmap = 1, 2549 .may_swap = 1, 2550 .no_demotion = 1, 2551 }; 2552 2553 nr_reclaimed = shrink_page_list(page_list, pgdat, &sc, &dummy_stat, false); 2554 while (!list_empty(page_list)) { 2555 folio = lru_to_folio(page_list); 2556 list_del(&folio->lru); 2557 folio_putback_lru(folio); 2558 } 2559 2560 return nr_reclaimed; 2561 } 2562 2563 unsigned long reclaim_pages(struct list_head *page_list) 2564 { 2565 int nid = NUMA_NO_NODE; 2566 unsigned int nr_reclaimed = 0; 2567 LIST_HEAD(node_page_list); 2568 struct page *page; 2569 unsigned int noreclaim_flag; 2570 2571 noreclaim_flag = memalloc_noreclaim_save(); 2572 2573 while (!list_empty(page_list)) { 2574 page = lru_to_page(page_list); 2575 if (nid == NUMA_NO_NODE) 2576 nid = page_to_nid(page); 2577 2578 if (nid == page_to_nid(page)) { 2579 ClearPageActive(page); 2580 list_move(&page->lru, &node_page_list); 2581 continue; 2582 } 2583 2584 nr_reclaimed += reclaim_page_list(&node_page_list, NODE_DATA(nid)); 2585 nid = NUMA_NO_NODE; 2586 } 2587 2588 if (!list_empty(&node_page_list)) 2589 nr_reclaimed += reclaim_page_list(&node_page_list, NODE_DATA(nid)); 2590 2591 memalloc_noreclaim_restore(noreclaim_flag); 2592 2593 return nr_reclaimed; 2594 } 2595 2596 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan, 2597 struct lruvec *lruvec, struct scan_control *sc) 2598 { 2599 if (is_active_lru(lru)) { 2600 if (sc->may_deactivate & (1 << is_file_lru(lru))) 2601 shrink_active_list(nr_to_scan, lruvec, sc, lru); 2602 else 2603 sc->skipped_deactivate = 1; 2604 return 0; 2605 } 2606 2607 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru); 2608 } 2609 2610 /* 2611 * The inactive anon list should be small enough that the VM never has 2612 * to do too much work. 2613 * 2614 * The inactive file list should be small enough to leave most memory 2615 * to the established workingset on the scan-resistant active list, 2616 * but large enough to avoid thrashing the aggregate readahead window. 2617 * 2618 * Both inactive lists should also be large enough that each inactive 2619 * page has a chance to be referenced again before it is reclaimed. 2620 * 2621 * If that fails and refaulting is observed, the inactive list grows. 2622 * 2623 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages 2624 * on this LRU, maintained by the pageout code. An inactive_ratio 2625 * of 3 means 3:1 or 25% of the pages are kept on the inactive list. 2626 * 2627 * total target max 2628 * memory ratio inactive 2629 * ------------------------------------- 2630 * 10MB 1 5MB 2631 * 100MB 1 50MB 2632 * 1GB 3 250MB 2633 * 10GB 10 0.9GB 2634 * 100GB 31 3GB 2635 * 1TB 101 10GB 2636 * 10TB 320 32GB 2637 */ 2638 static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru) 2639 { 2640 enum lru_list active_lru = inactive_lru + LRU_ACTIVE; 2641 unsigned long inactive, active; 2642 unsigned long inactive_ratio; 2643 unsigned long gb; 2644 2645 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru); 2646 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru); 2647 2648 gb = (inactive + active) >> (30 - PAGE_SHIFT); 2649 if (gb) 2650 inactive_ratio = int_sqrt(10 * gb); 2651 else 2652 inactive_ratio = 1; 2653 2654 return inactive * inactive_ratio < active; 2655 } 2656 2657 enum scan_balance { 2658 SCAN_EQUAL, 2659 SCAN_FRACT, 2660 SCAN_ANON, 2661 SCAN_FILE, 2662 }; 2663 2664 /* 2665 * Determine how aggressively the anon and file LRU lists should be 2666 * scanned. 2667 * 2668 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan 2669 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan 2670 */ 2671 static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc, 2672 unsigned long *nr) 2673 { 2674 struct pglist_data *pgdat = lruvec_pgdat(lruvec); 2675 struct mem_cgroup *memcg = lruvec_memcg(lruvec); 2676 unsigned long anon_cost, file_cost, total_cost; 2677 int swappiness = mem_cgroup_swappiness(memcg); 2678 u64 fraction[ANON_AND_FILE]; 2679 u64 denominator = 0; /* gcc */ 2680 enum scan_balance scan_balance; 2681 unsigned long ap, fp; 2682 enum lru_list lru; 2683 2684 /* If we have no swap space, do not bother scanning anon pages. */ 2685 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) { 2686 scan_balance = SCAN_FILE; 2687 goto out; 2688 } 2689 2690 /* 2691 * Global reclaim will swap to prevent OOM even with no 2692 * swappiness, but memcg users want to use this knob to 2693 * disable swapping for individual groups completely when 2694 * using the memory controller's swap limit feature would be 2695 * too expensive. 2696 */ 2697 if (cgroup_reclaim(sc) && !swappiness) { 2698 scan_balance = SCAN_FILE; 2699 goto out; 2700 } 2701 2702 /* 2703 * Do not apply any pressure balancing cleverness when the 2704 * system is close to OOM, scan both anon and file equally 2705 * (unless the swappiness setting disagrees with swapping). 2706 */ 2707 if (!sc->priority && swappiness) { 2708 scan_balance = SCAN_EQUAL; 2709 goto out; 2710 } 2711 2712 /* 2713 * If the system is almost out of file pages, force-scan anon. 2714 */ 2715 if (sc->file_is_tiny) { 2716 scan_balance = SCAN_ANON; 2717 goto out; 2718 } 2719 2720 /* 2721 * If there is enough inactive page cache, we do not reclaim 2722 * anything from the anonymous working right now. 2723 */ 2724 if (sc->cache_trim_mode) { 2725 scan_balance = SCAN_FILE; 2726 goto out; 2727 } 2728 2729 scan_balance = SCAN_FRACT; 2730 /* 2731 * Calculate the pressure balance between anon and file pages. 2732 * 2733 * The amount of pressure we put on each LRU is inversely 2734 * proportional to the cost of reclaiming each list, as 2735 * determined by the share of pages that are refaulting, times 2736 * the relative IO cost of bringing back a swapped out 2737 * anonymous page vs reloading a filesystem page (swappiness). 2738 * 2739 * Although we limit that influence to ensure no list gets 2740 * left behind completely: at least a third of the pressure is 2741 * applied, before swappiness. 2742 * 2743 * With swappiness at 100, anon and file have equal IO cost. 2744 */ 2745 total_cost = sc->anon_cost + sc->file_cost; 2746 anon_cost = total_cost + sc->anon_cost; 2747 file_cost = total_cost + sc->file_cost; 2748 total_cost = anon_cost + file_cost; 2749 2750 ap = swappiness * (total_cost + 1); 2751 ap /= anon_cost + 1; 2752 2753 fp = (200 - swappiness) * (total_cost + 1); 2754 fp /= file_cost + 1; 2755 2756 fraction[0] = ap; 2757 fraction[1] = fp; 2758 denominator = ap + fp; 2759 out: 2760 for_each_evictable_lru(lru) { 2761 int file = is_file_lru(lru); 2762 unsigned long lruvec_size; 2763 unsigned long low, min; 2764 unsigned long scan; 2765 2766 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx); 2767 mem_cgroup_protection(sc->target_mem_cgroup, memcg, 2768 &min, &low); 2769 2770 if (min || low) { 2771 /* 2772 * Scale a cgroup's reclaim pressure by proportioning 2773 * its current usage to its memory.low or memory.min 2774 * setting. 2775 * 2776 * This is important, as otherwise scanning aggression 2777 * becomes extremely binary -- from nothing as we 2778 * approach the memory protection threshold, to totally 2779 * nominal as we exceed it. This results in requiring 2780 * setting extremely liberal protection thresholds. It 2781 * also means we simply get no protection at all if we 2782 * set it too low, which is not ideal. 2783 * 2784 * If there is any protection in place, we reduce scan 2785 * pressure by how much of the total memory used is 2786 * within protection thresholds. 2787 * 2788 * There is one special case: in the first reclaim pass, 2789 * we skip over all groups that are within their low 2790 * protection. If that fails to reclaim enough pages to 2791 * satisfy the reclaim goal, we come back and override 2792 * the best-effort low protection. However, we still 2793 * ideally want to honor how well-behaved groups are in 2794 * that case instead of simply punishing them all 2795 * equally. As such, we reclaim them based on how much 2796 * memory they are using, reducing the scan pressure 2797 * again by how much of the total memory used is under 2798 * hard protection. 2799 */ 2800 unsigned long cgroup_size = mem_cgroup_size(memcg); 2801 unsigned long protection; 2802 2803 /* memory.low scaling, make sure we retry before OOM */ 2804 if (!sc->memcg_low_reclaim && low > min) { 2805 protection = low; 2806 sc->memcg_low_skipped = 1; 2807 } else { 2808 protection = min; 2809 } 2810 2811 /* Avoid TOCTOU with earlier protection check */ 2812 cgroup_size = max(cgroup_size, protection); 2813 2814 scan = lruvec_size - lruvec_size * protection / 2815 (cgroup_size + 1); 2816 2817 /* 2818 * Minimally target SWAP_CLUSTER_MAX pages to keep 2819 * reclaim moving forwards, avoiding decrementing 2820 * sc->priority further than desirable. 2821 */ 2822 scan = max(scan, SWAP_CLUSTER_MAX); 2823 } else { 2824 scan = lruvec_size; 2825 } 2826 2827 scan >>= sc->priority; 2828 2829 /* 2830 * If the cgroup's already been deleted, make sure to 2831 * scrape out the remaining cache. 2832 */ 2833 if (!scan && !mem_cgroup_online(memcg)) 2834 scan = min(lruvec_size, SWAP_CLUSTER_MAX); 2835 2836 switch (scan_balance) { 2837 case SCAN_EQUAL: 2838 /* Scan lists relative to size */ 2839 break; 2840 case SCAN_FRACT: 2841 /* 2842 * Scan types proportional to swappiness and 2843 * their relative recent reclaim efficiency. 2844 * Make sure we don't miss the last page on 2845 * the offlined memory cgroups because of a 2846 * round-off error. 2847 */ 2848 scan = mem_cgroup_online(memcg) ? 2849 div64_u64(scan * fraction[file], denominator) : 2850 DIV64_U64_ROUND_UP(scan * fraction[file], 2851 denominator); 2852 break; 2853 case SCAN_FILE: 2854 case SCAN_ANON: 2855 /* Scan one type exclusively */ 2856 if ((scan_balance == SCAN_FILE) != file) 2857 scan = 0; 2858 break; 2859 default: 2860 /* Look ma, no brain */ 2861 BUG(); 2862 } 2863 2864 nr[lru] = scan; 2865 } 2866 } 2867 2868 /* 2869 * Anonymous LRU management is a waste if there is 2870 * ultimately no way to reclaim the memory. 2871 */ 2872 static bool can_age_anon_pages(struct pglist_data *pgdat, 2873 struct scan_control *sc) 2874 { 2875 /* Aging the anon LRU is valuable if swap is present: */ 2876 if (total_swap_pages > 0) 2877 return true; 2878 2879 /* Also valuable if anon pages can be demoted: */ 2880 return can_demote(pgdat->node_id, sc); 2881 } 2882 2883 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc) 2884 { 2885 unsigned long nr[NR_LRU_LISTS]; 2886 unsigned long targets[NR_LRU_LISTS]; 2887 unsigned long nr_to_scan; 2888 enum lru_list lru; 2889 unsigned long nr_reclaimed = 0; 2890 unsigned long nr_to_reclaim = sc->nr_to_reclaim; 2891 struct blk_plug plug; 2892 bool scan_adjusted; 2893 2894 get_scan_count(lruvec, sc, nr); 2895 2896 /* Record the original scan target for proportional adjustments later */ 2897 memcpy(targets, nr, sizeof(nr)); 2898 2899 /* 2900 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal 2901 * event that can occur when there is little memory pressure e.g. 2902 * multiple streaming readers/writers. Hence, we do not abort scanning 2903 * when the requested number of pages are reclaimed when scanning at 2904 * DEF_PRIORITY on the assumption that the fact we are direct 2905 * reclaiming implies that kswapd is not keeping up and it is best to 2906 * do a batch of work at once. For memcg reclaim one check is made to 2907 * abort proportional reclaim if either the file or anon lru has already 2908 * dropped to zero at the first pass. 2909 */ 2910 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() && 2911 sc->priority == DEF_PRIORITY); 2912 2913 blk_start_plug(&plug); 2914 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] || 2915 nr[LRU_INACTIVE_FILE]) { 2916 unsigned long nr_anon, nr_file, percentage; 2917 unsigned long nr_scanned; 2918 2919 for_each_evictable_lru(lru) { 2920 if (nr[lru]) { 2921 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX); 2922 nr[lru] -= nr_to_scan; 2923 2924 nr_reclaimed += shrink_list(lru, nr_to_scan, 2925 lruvec, sc); 2926 } 2927 } 2928 2929 cond_resched(); 2930 2931 if (nr_reclaimed < nr_to_reclaim || scan_adjusted) 2932 continue; 2933 2934 /* 2935 * For kswapd and memcg, reclaim at least the number of pages 2936 * requested. Ensure that the anon and file LRUs are scanned 2937 * proportionally what was requested by get_scan_count(). We 2938 * stop reclaiming one LRU and reduce the amount scanning 2939 * proportional to the original scan target. 2940 */ 2941 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE]; 2942 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON]; 2943 2944 /* 2945 * It's just vindictive to attack the larger once the smaller 2946 * has gone to zero. And given the way we stop scanning the 2947 * smaller below, this makes sure that we only make one nudge 2948 * towards proportionality once we've got nr_to_reclaim. 2949 */ 2950 if (!nr_file || !nr_anon) 2951 break; 2952 2953 if (nr_file > nr_anon) { 2954 unsigned long scan_target = targets[LRU_INACTIVE_ANON] + 2955 targets[LRU_ACTIVE_ANON] + 1; 2956 lru = LRU_BASE; 2957 percentage = nr_anon * 100 / scan_target; 2958 } else { 2959 unsigned long scan_target = targets[LRU_INACTIVE_FILE] + 2960 targets[LRU_ACTIVE_FILE] + 1; 2961 lru = LRU_FILE; 2962 percentage = nr_file * 100 / scan_target; 2963 } 2964 2965 /* Stop scanning the smaller of the LRU */ 2966 nr[lru] = 0; 2967 nr[lru + LRU_ACTIVE] = 0; 2968 2969 /* 2970 * Recalculate the other LRU scan count based on its original 2971 * scan target and the percentage scanning already complete 2972 */ 2973 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE; 2974 nr_scanned = targets[lru] - nr[lru]; 2975 nr[lru] = targets[lru] * (100 - percentage) / 100; 2976 nr[lru] -= min(nr[lru], nr_scanned); 2977 2978 lru += LRU_ACTIVE; 2979 nr_scanned = targets[lru] - nr[lru]; 2980 nr[lru] = targets[lru] * (100 - percentage) / 100; 2981 nr[lru] -= min(nr[lru], nr_scanned); 2982 2983 scan_adjusted = true; 2984 } 2985 blk_finish_plug(&plug); 2986 sc->nr_reclaimed += nr_reclaimed; 2987 2988 /* 2989 * Even if we did not try to evict anon pages at all, we want to 2990 * rebalance the anon lru active/inactive ratio. 2991 */ 2992 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) && 2993 inactive_is_low(lruvec, LRU_INACTIVE_ANON)) 2994 shrink_active_list(SWAP_CLUSTER_MAX, lruvec, 2995 sc, LRU_ACTIVE_ANON); 2996 } 2997 2998 /* Use reclaim/compaction for costly allocs or under memory pressure */ 2999 static bool in_reclaim_compaction(struct scan_control *sc) 3000 { 3001 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order && 3002 (sc->order > PAGE_ALLOC_COSTLY_ORDER || 3003 sc->priority < DEF_PRIORITY - 2)) 3004 return true; 3005 3006 return false; 3007 } 3008 3009 /* 3010 * Reclaim/compaction is used for high-order allocation requests. It reclaims 3011 * order-0 pages before compacting the zone. should_continue_reclaim() returns 3012 * true if more pages should be reclaimed such that when the page allocator 3013 * calls try_to_compact_pages() that it will have enough free pages to succeed. 3014 * It will give up earlier than that if there is difficulty reclaiming pages. 3015 */ 3016 static inline bool should_continue_reclaim(struct pglist_data *pgdat, 3017 unsigned long nr_reclaimed, 3018 struct scan_control *sc) 3019 { 3020 unsigned long pages_for_compaction; 3021 unsigned long inactive_lru_pages; 3022 int z; 3023 3024 /* If not in reclaim/compaction mode, stop */ 3025 if (!in_reclaim_compaction(sc)) 3026 return false; 3027 3028 /* 3029 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX 3030 * number of pages that were scanned. This will return to the caller 3031 * with the risk reclaim/compaction and the resulting allocation attempt 3032 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL 3033 * allocations through requiring that the full LRU list has been scanned 3034 * first, by assuming that zero delta of sc->nr_scanned means full LRU 3035 * scan, but that approximation was wrong, and there were corner cases 3036 * where always a non-zero amount of pages were scanned. 3037 */ 3038 if (!nr_reclaimed) 3039 return false; 3040 3041 /* If compaction would go ahead or the allocation would succeed, stop */ 3042 for (z = 0; z <= sc->reclaim_idx; z++) { 3043 struct zone *zone = &pgdat->node_zones[z]; 3044 if (!managed_zone(zone)) 3045 continue; 3046 3047 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) { 3048 case COMPACT_SUCCESS: 3049 case COMPACT_CONTINUE: 3050 return false; 3051 default: 3052 /* check next zone */ 3053 ; 3054 } 3055 } 3056 3057 /* 3058 * If we have not reclaimed enough pages for compaction and the 3059 * inactive lists are large enough, continue reclaiming 3060 */ 3061 pages_for_compaction = compact_gap(sc->order); 3062 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE); 3063 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc)) 3064 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON); 3065 3066 return inactive_lru_pages > pages_for_compaction; 3067 } 3068 3069 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc) 3070 { 3071 struct mem_cgroup *target_memcg = sc->target_mem_cgroup; 3072 struct mem_cgroup *memcg; 3073 3074 memcg = mem_cgroup_iter(target_memcg, NULL, NULL); 3075 do { 3076 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat); 3077 unsigned long reclaimed; 3078 unsigned long scanned; 3079 3080 /* 3081 * This loop can become CPU-bound when target memcgs 3082 * aren't eligible for reclaim - either because they 3083 * don't have any reclaimable pages, or because their 3084 * memory is explicitly protected. Avoid soft lockups. 3085 */ 3086 cond_resched(); 3087 3088 mem_cgroup_calculate_protection(target_memcg, memcg); 3089 3090 if (mem_cgroup_below_min(memcg)) { 3091 /* 3092 * Hard protection. 3093 * If there is no reclaimable memory, OOM. 3094 */ 3095 continue; 3096 } else if (mem_cgroup_below_low(memcg)) { 3097 /* 3098 * Soft protection. 3099 * Respect the protection only as long as 3100 * there is an unprotected supply 3101 * of reclaimable memory from other cgroups. 3102 */ 3103 if (!sc->memcg_low_reclaim) { 3104 sc->memcg_low_skipped = 1; 3105 continue; 3106 } 3107 memcg_memory_event(memcg, MEMCG_LOW); 3108 } 3109 3110 reclaimed = sc->nr_reclaimed; 3111 scanned = sc->nr_scanned; 3112 3113 shrink_lruvec(lruvec, sc); 3114 3115 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, 3116 sc->priority); 3117 3118 /* Record the group's reclaim efficiency */ 3119 vmpressure(sc->gfp_mask, memcg, false, 3120 sc->nr_scanned - scanned, 3121 sc->nr_reclaimed - reclaimed); 3122 3123 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL))); 3124 } 3125 3126 static void shrink_node(pg_data_t *pgdat, struct scan_control *sc) 3127 { 3128 struct reclaim_state *reclaim_state = current->reclaim_state; 3129 unsigned long nr_reclaimed, nr_scanned; 3130 struct lruvec *target_lruvec; 3131 bool reclaimable = false; 3132 unsigned long file; 3133 3134 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat); 3135 3136 again: 3137 /* 3138 * Flush the memory cgroup stats, so that we read accurate per-memcg 3139 * lruvec stats for heuristics. 3140 */ 3141 mem_cgroup_flush_stats(); 3142 3143 memset(&sc->nr, 0, sizeof(sc->nr)); 3144 3145 nr_reclaimed = sc->nr_reclaimed; 3146 nr_scanned = sc->nr_scanned; 3147 3148 /* 3149 * Determine the scan balance between anon and file LRUs. 3150 */ 3151 spin_lock_irq(&target_lruvec->lru_lock); 3152 sc->anon_cost = target_lruvec->anon_cost; 3153 sc->file_cost = target_lruvec->file_cost; 3154 spin_unlock_irq(&target_lruvec->lru_lock); 3155 3156 /* 3157 * Target desirable inactive:active list ratios for the anon 3158 * and file LRU lists. 3159 */ 3160 if (!sc->force_deactivate) { 3161 unsigned long refaults; 3162 3163 refaults = lruvec_page_state(target_lruvec, 3164 WORKINGSET_ACTIVATE_ANON); 3165 if (refaults != target_lruvec->refaults[0] || 3166 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON)) 3167 sc->may_deactivate |= DEACTIVATE_ANON; 3168 else 3169 sc->may_deactivate &= ~DEACTIVATE_ANON; 3170 3171 /* 3172 * When refaults are being observed, it means a new 3173 * workingset is being established. Deactivate to get 3174 * rid of any stale active pages quickly. 3175 */ 3176 refaults = lruvec_page_state(target_lruvec, 3177 WORKINGSET_ACTIVATE_FILE); 3178 if (refaults != target_lruvec->refaults[1] || 3179 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE)) 3180 sc->may_deactivate |= DEACTIVATE_FILE; 3181 else 3182 sc->may_deactivate &= ~DEACTIVATE_FILE; 3183 } else 3184 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE; 3185 3186 /* 3187 * If we have plenty of inactive file pages that aren't 3188 * thrashing, try to reclaim those first before touching 3189 * anonymous pages. 3190 */ 3191 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE); 3192 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE)) 3193 sc->cache_trim_mode = 1; 3194 else 3195 sc->cache_trim_mode = 0; 3196 3197 /* 3198 * Prevent the reclaimer from falling into the cache trap: as 3199 * cache pages start out inactive, every cache fault will tip 3200 * the scan balance towards the file LRU. And as the file LRU 3201 * shrinks, so does the window for rotation from references. 3202 * This means we have a runaway feedback loop where a tiny 3203 * thrashing file LRU becomes infinitely more attractive than 3204 * anon pages. Try to detect this based on file LRU size. 3205 */ 3206 if (!cgroup_reclaim(sc)) { 3207 unsigned long total_high_wmark = 0; 3208 unsigned long free, anon; 3209 int z; 3210 3211 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES); 3212 file = node_page_state(pgdat, NR_ACTIVE_FILE) + 3213 node_page_state(pgdat, NR_INACTIVE_FILE); 3214 3215 for (z = 0; z < MAX_NR_ZONES; z++) { 3216 struct zone *zone = &pgdat->node_zones[z]; 3217 if (!managed_zone(zone)) 3218 continue; 3219 3220 total_high_wmark += high_wmark_pages(zone); 3221 } 3222 3223 /* 3224 * Consider anon: if that's low too, this isn't a 3225 * runaway file reclaim problem, but rather just 3226 * extreme pressure. Reclaim as per usual then. 3227 */ 3228 anon = node_page_state(pgdat, NR_INACTIVE_ANON); 3229 3230 sc->file_is_tiny = 3231 file + free <= total_high_wmark && 3232 !(sc->may_deactivate & DEACTIVATE_ANON) && 3233 anon >> sc->priority; 3234 } 3235 3236 shrink_node_memcgs(pgdat, sc); 3237 3238 if (reclaim_state) { 3239 sc->nr_reclaimed += reclaim_state->reclaimed_slab; 3240 reclaim_state->reclaimed_slab = 0; 3241 } 3242 3243 /* Record the subtree's reclaim efficiency */ 3244 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true, 3245 sc->nr_scanned - nr_scanned, 3246 sc->nr_reclaimed - nr_reclaimed); 3247 3248 if (sc->nr_reclaimed - nr_reclaimed) 3249 reclaimable = true; 3250 3251 if (current_is_kswapd()) { 3252 /* 3253 * If reclaim is isolating dirty pages under writeback, 3254 * it implies that the long-lived page allocation rate 3255 * is exceeding the page laundering rate. Either the 3256 * global limits are not being effective at throttling 3257 * processes due to the page distribution throughout 3258 * zones or there is heavy usage of a slow backing 3259 * device. The only option is to throttle from reclaim 3260 * context which is not ideal as there is no guarantee 3261 * the dirtying process is throttled in the same way 3262 * balance_dirty_pages() manages. 3263 * 3264 * Once a node is flagged PGDAT_WRITEBACK, kswapd will 3265 * count the number of pages under pages flagged for 3266 * immediate reclaim and stall if any are encountered 3267 * in the nr_immediate check below. 3268 */ 3269 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken) 3270 set_bit(PGDAT_WRITEBACK, &pgdat->flags); 3271 3272 /* Allow kswapd to start writing pages during reclaim.*/ 3273 if (sc->nr.unqueued_dirty == sc->nr.file_taken) 3274 set_bit(PGDAT_DIRTY, &pgdat->flags); 3275 3276 /* 3277 * If kswapd scans pages marked for immediate 3278 * reclaim and under writeback (nr_immediate), it 3279 * implies that pages are cycling through the LRU 3280 * faster than they are written so forcibly stall 3281 * until some pages complete writeback. 3282 */ 3283 if (sc->nr.immediate) 3284 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK); 3285 } 3286 3287 /* 3288 * Tag a node/memcg as congested if all the dirty pages were marked 3289 * for writeback and immediate reclaim (counted in nr.congested). 3290 * 3291 * Legacy memcg will stall in page writeback so avoid forcibly 3292 * stalling in reclaim_throttle(). 3293 */ 3294 if ((current_is_kswapd() || 3295 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) && 3296 sc->nr.dirty && sc->nr.dirty == sc->nr.congested) 3297 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags); 3298 3299 /* 3300 * Stall direct reclaim for IO completions if the lruvec is 3301 * node is congested. Allow kswapd to continue until it 3302 * starts encountering unqueued dirty pages or cycling through 3303 * the LRU too quickly. 3304 */ 3305 if (!current_is_kswapd() && current_may_throttle() && 3306 !sc->hibernation_mode && 3307 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags)) 3308 reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED); 3309 3310 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed, 3311 sc)) 3312 goto again; 3313 3314 /* 3315 * Kswapd gives up on balancing particular nodes after too 3316 * many failures to reclaim anything from them and goes to 3317 * sleep. On reclaim progress, reset the failure counter. A 3318 * successful direct reclaim run will revive a dormant kswapd. 3319 */ 3320 if (reclaimable) 3321 pgdat->kswapd_failures = 0; 3322 } 3323 3324 /* 3325 * Returns true if compaction should go ahead for a costly-order request, or 3326 * the allocation would already succeed without compaction. Return false if we 3327 * should reclaim first. 3328 */ 3329 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc) 3330 { 3331 unsigned long watermark; 3332 enum compact_result suitable; 3333 3334 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx); 3335 if (suitable == COMPACT_SUCCESS) 3336 /* Allocation should succeed already. Don't reclaim. */ 3337 return true; 3338 if (suitable == COMPACT_SKIPPED) 3339 /* Compaction cannot yet proceed. Do reclaim. */ 3340 return false; 3341 3342 /* 3343 * Compaction is already possible, but it takes time to run and there 3344 * are potentially other callers using the pages just freed. So proceed 3345 * with reclaim to make a buffer of free pages available to give 3346 * compaction a reasonable chance of completing and allocating the page. 3347 * Note that we won't actually reclaim the whole buffer in one attempt 3348 * as the target watermark in should_continue_reclaim() is lower. But if 3349 * we are already above the high+gap watermark, don't reclaim at all. 3350 */ 3351 watermark = high_wmark_pages(zone) + compact_gap(sc->order); 3352 3353 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx); 3354 } 3355 3356 static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc) 3357 { 3358 /* 3359 * If reclaim is making progress greater than 12% efficiency then 3360 * wake all the NOPROGRESS throttled tasks. 3361 */ 3362 if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) { 3363 wait_queue_head_t *wqh; 3364 3365 wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS]; 3366 if (waitqueue_active(wqh)) 3367 wake_up(wqh); 3368 3369 return; 3370 } 3371 3372 /* 3373 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will 3374 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages 3375 * under writeback and marked for immediate reclaim at the tail of the 3376 * LRU. 3377 */ 3378 if (current_is_kswapd() || cgroup_reclaim(sc)) 3379 return; 3380 3381 /* Throttle if making no progress at high prioities. */ 3382 if (sc->priority == 1 && !sc->nr_reclaimed) 3383 reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS); 3384 } 3385 3386 /* 3387 * This is the direct reclaim path, for page-allocating processes. We only 3388 * try to reclaim pages from zones which will satisfy the caller's allocation 3389 * request. 3390 * 3391 * If a zone is deemed to be full of pinned pages then just give it a light 3392 * scan then give up on it. 3393 */ 3394 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc) 3395 { 3396 struct zoneref *z; 3397 struct zone *zone; 3398 unsigned long nr_soft_reclaimed; 3399 unsigned long nr_soft_scanned; 3400 gfp_t orig_mask; 3401 pg_data_t *last_pgdat = NULL; 3402 pg_data_t *first_pgdat = NULL; 3403 3404 /* 3405 * If the number of buffer_heads in the machine exceeds the maximum 3406 * allowed level, force direct reclaim to scan the highmem zone as 3407 * highmem pages could be pinning lowmem pages storing buffer_heads 3408 */ 3409 orig_mask = sc->gfp_mask; 3410 if (buffer_heads_over_limit) { 3411 sc->gfp_mask |= __GFP_HIGHMEM; 3412 sc->reclaim_idx = gfp_zone(sc->gfp_mask); 3413 } 3414 3415 for_each_zone_zonelist_nodemask(zone, z, zonelist, 3416 sc->reclaim_idx, sc->nodemask) { 3417 /* 3418 * Take care memory controller reclaiming has small influence 3419 * to global LRU. 3420 */ 3421 if (!cgroup_reclaim(sc)) { 3422 if (!cpuset_zone_allowed(zone, 3423 GFP_KERNEL | __GFP_HARDWALL)) 3424 continue; 3425 3426 /* 3427 * If we already have plenty of memory free for 3428 * compaction in this zone, don't free any more. 3429 * Even though compaction is invoked for any 3430 * non-zero order, only frequent costly order 3431 * reclamation is disruptive enough to become a 3432 * noticeable problem, like transparent huge 3433 * page allocations. 3434 */ 3435 if (IS_ENABLED(CONFIG_COMPACTION) && 3436 sc->order > PAGE_ALLOC_COSTLY_ORDER && 3437 compaction_ready(zone, sc)) { 3438 sc->compaction_ready = true; 3439 continue; 3440 } 3441 3442 /* 3443 * Shrink each node in the zonelist once. If the 3444 * zonelist is ordered by zone (not the default) then a 3445 * node may be shrunk multiple times but in that case 3446 * the user prefers lower zones being preserved. 3447 */ 3448 if (zone->zone_pgdat == last_pgdat) 3449 continue; 3450 3451 /* 3452 * This steals pages from memory cgroups over softlimit 3453 * and returns the number of reclaimed pages and 3454 * scanned pages. This works for global memory pressure 3455 * and balancing, not for a memcg's limit. 3456 */ 3457 nr_soft_scanned = 0; 3458 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat, 3459 sc->order, sc->gfp_mask, 3460 &nr_soft_scanned); 3461 sc->nr_reclaimed += nr_soft_reclaimed; 3462 sc->nr_scanned += nr_soft_scanned; 3463 /* need some check for avoid more shrink_zone() */ 3464 } 3465 3466 if (!first_pgdat) 3467 first_pgdat = zone->zone_pgdat; 3468 3469 /* See comment about same check for global reclaim above */ 3470 if (zone->zone_pgdat == last_pgdat) 3471 continue; 3472 last_pgdat = zone->zone_pgdat; 3473 shrink_node(zone->zone_pgdat, sc); 3474 } 3475 3476 if (first_pgdat) 3477 consider_reclaim_throttle(first_pgdat, sc); 3478 3479 /* 3480 * Restore to original mask to avoid the impact on the caller if we 3481 * promoted it to __GFP_HIGHMEM. 3482 */ 3483 sc->gfp_mask = orig_mask; 3484 } 3485 3486 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat) 3487 { 3488 struct lruvec *target_lruvec; 3489 unsigned long refaults; 3490 3491 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat); 3492 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON); 3493 target_lruvec->refaults[0] = refaults; 3494 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE); 3495 target_lruvec->refaults[1] = refaults; 3496 } 3497 3498 /* 3499 * This is the main entry point to direct page reclaim. 3500 * 3501 * If a full scan of the inactive list fails to free enough memory then we 3502 * are "out of memory" and something needs to be killed. 3503 * 3504 * If the caller is !__GFP_FS then the probability of a failure is reasonably 3505 * high - the zone may be full of dirty or under-writeback pages, which this 3506 * caller can't do much about. We kick the writeback threads and take explicit 3507 * naps in the hope that some of these pages can be written. But if the 3508 * allocating task holds filesystem locks which prevent writeout this might not 3509 * work, and the allocation attempt will fail. 3510 * 3511 * returns: 0, if no pages reclaimed 3512 * else, the number of pages reclaimed 3513 */ 3514 static unsigned long do_try_to_free_pages(struct zonelist *zonelist, 3515 struct scan_control *sc) 3516 { 3517 int initial_priority = sc->priority; 3518 pg_data_t *last_pgdat; 3519 struct zoneref *z; 3520 struct zone *zone; 3521 retry: 3522 delayacct_freepages_start(); 3523 3524 if (!cgroup_reclaim(sc)) 3525 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1); 3526 3527 do { 3528 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup, 3529 sc->priority); 3530 sc->nr_scanned = 0; 3531 shrink_zones(zonelist, sc); 3532 3533 if (sc->nr_reclaimed >= sc->nr_to_reclaim) 3534 break; 3535 3536 if (sc->compaction_ready) 3537 break; 3538 3539 /* 3540 * If we're getting trouble reclaiming, start doing 3541 * writepage even in laptop mode. 3542 */ 3543 if (sc->priority < DEF_PRIORITY - 2) 3544 sc->may_writepage = 1; 3545 } while (--sc->priority >= 0); 3546 3547 last_pgdat = NULL; 3548 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx, 3549 sc->nodemask) { 3550 if (zone->zone_pgdat == last_pgdat) 3551 continue; 3552 last_pgdat = zone->zone_pgdat; 3553 3554 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat); 3555 3556 if (cgroup_reclaim(sc)) { 3557 struct lruvec *lruvec; 3558 3559 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, 3560 zone->zone_pgdat); 3561 clear_bit(LRUVEC_CONGESTED, &lruvec->flags); 3562 } 3563 } 3564 3565 delayacct_freepages_end(); 3566 3567 if (sc->nr_reclaimed) 3568 return sc->nr_reclaimed; 3569 3570 /* Aborted reclaim to try compaction? don't OOM, then */ 3571 if (sc->compaction_ready) 3572 return 1; 3573 3574 /* 3575 * We make inactive:active ratio decisions based on the node's 3576 * composition of memory, but a restrictive reclaim_idx or a 3577 * memory.low cgroup setting can exempt large amounts of 3578 * memory from reclaim. Neither of which are very common, so 3579 * instead of doing costly eligibility calculations of the 3580 * entire cgroup subtree up front, we assume the estimates are 3581 * good, and retry with forcible deactivation if that fails. 3582 */ 3583 if (sc->skipped_deactivate) { 3584 sc->priority = initial_priority; 3585 sc->force_deactivate = 1; 3586 sc->skipped_deactivate = 0; 3587 goto retry; 3588 } 3589 3590 /* Untapped cgroup reserves? Don't OOM, retry. */ 3591 if (sc->memcg_low_skipped) { 3592 sc->priority = initial_priority; 3593 sc->force_deactivate = 0; 3594 sc->memcg_low_reclaim = 1; 3595 sc->memcg_low_skipped = 0; 3596 goto retry; 3597 } 3598 3599 return 0; 3600 } 3601 3602 static bool allow_direct_reclaim(pg_data_t *pgdat) 3603 { 3604 struct zone *zone; 3605 unsigned long pfmemalloc_reserve = 0; 3606 unsigned long free_pages = 0; 3607 int i; 3608 bool wmark_ok; 3609 3610 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES) 3611 return true; 3612 3613 for (i = 0; i <= ZONE_NORMAL; i++) { 3614 zone = &pgdat->node_zones[i]; 3615 if (!managed_zone(zone)) 3616 continue; 3617 3618 if (!zone_reclaimable_pages(zone)) 3619 continue; 3620 3621 pfmemalloc_reserve += min_wmark_pages(zone); 3622 free_pages += zone_page_state(zone, NR_FREE_PAGES); 3623 } 3624 3625 /* If there are no reserves (unexpected config) then do not throttle */ 3626 if (!pfmemalloc_reserve) 3627 return true; 3628 3629 wmark_ok = free_pages > pfmemalloc_reserve / 2; 3630 3631 /* kswapd must be awake if processes are being throttled */ 3632 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) { 3633 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL) 3634 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL); 3635 3636 wake_up_interruptible(&pgdat->kswapd_wait); 3637 } 3638 3639 return wmark_ok; 3640 } 3641 3642 /* 3643 * Throttle direct reclaimers if backing storage is backed by the network 3644 * and the PFMEMALLOC reserve for the preferred node is getting dangerously 3645 * depleted. kswapd will continue to make progress and wake the processes 3646 * when the low watermark is reached. 3647 * 3648 * Returns true if a fatal signal was delivered during throttling. If this 3649 * happens, the page allocator should not consider triggering the OOM killer. 3650 */ 3651 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist, 3652 nodemask_t *nodemask) 3653 { 3654 struct zoneref *z; 3655 struct zone *zone; 3656 pg_data_t *pgdat = NULL; 3657 3658 /* 3659 * Kernel threads should not be throttled as they may be indirectly 3660 * responsible for cleaning pages necessary for reclaim to make forward 3661 * progress. kjournald for example may enter direct reclaim while 3662 * committing a transaction where throttling it could forcing other 3663 * processes to block on log_wait_commit(). 3664 */ 3665 if (current->flags & PF_KTHREAD) 3666 goto out; 3667 3668 /* 3669 * If a fatal signal is pending, this process should not throttle. 3670 * It should return quickly so it can exit and free its memory 3671 */ 3672 if (fatal_signal_pending(current)) 3673 goto out; 3674 3675 /* 3676 * Check if the pfmemalloc reserves are ok by finding the first node 3677 * with a usable ZONE_NORMAL or lower zone. The expectation is that 3678 * GFP_KERNEL will be required for allocating network buffers when 3679 * swapping over the network so ZONE_HIGHMEM is unusable. 3680 * 3681 * Throttling is based on the first usable node and throttled processes 3682 * wait on a queue until kswapd makes progress and wakes them. There 3683 * is an affinity then between processes waking up and where reclaim 3684 * progress has been made assuming the process wakes on the same node. 3685 * More importantly, processes running on remote nodes will not compete 3686 * for remote pfmemalloc reserves and processes on different nodes 3687 * should make reasonable progress. 3688 */ 3689 for_each_zone_zonelist_nodemask(zone, z, zonelist, 3690 gfp_zone(gfp_mask), nodemask) { 3691 if (zone_idx(zone) > ZONE_NORMAL) 3692 continue; 3693 3694 /* Throttle based on the first usable node */ 3695 pgdat = zone->zone_pgdat; 3696 if (allow_direct_reclaim(pgdat)) 3697 goto out; 3698 break; 3699 } 3700 3701 /* If no zone was usable by the allocation flags then do not throttle */ 3702 if (!pgdat) 3703 goto out; 3704 3705 /* Account for the throttling */ 3706 count_vm_event(PGSCAN_DIRECT_THROTTLE); 3707 3708 /* 3709 * If the caller cannot enter the filesystem, it's possible that it 3710 * is due to the caller holding an FS lock or performing a journal 3711 * transaction in the case of a filesystem like ext[3|4]. In this case, 3712 * it is not safe to block on pfmemalloc_wait as kswapd could be 3713 * blocked waiting on the same lock. Instead, throttle for up to a 3714 * second before continuing. 3715 */ 3716 if (!(gfp_mask & __GFP_FS)) 3717 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait, 3718 allow_direct_reclaim(pgdat), HZ); 3719 else 3720 /* Throttle until kswapd wakes the process */ 3721 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait, 3722 allow_direct_reclaim(pgdat)); 3723 3724 if (fatal_signal_pending(current)) 3725 return true; 3726 3727 out: 3728 return false; 3729 } 3730 3731 unsigned long try_to_free_pages(struct zonelist *zonelist, int order, 3732 gfp_t gfp_mask, nodemask_t *nodemask) 3733 { 3734 unsigned long nr_reclaimed; 3735 struct scan_control sc = { 3736 .nr_to_reclaim = SWAP_CLUSTER_MAX, 3737 .gfp_mask = current_gfp_context(gfp_mask), 3738 .reclaim_idx = gfp_zone(gfp_mask), 3739 .order = order, 3740 .nodemask = nodemask, 3741 .priority = DEF_PRIORITY, 3742 .may_writepage = !laptop_mode, 3743 .may_unmap = 1, 3744 .may_swap = 1, 3745 }; 3746 3747 /* 3748 * scan_control uses s8 fields for order, priority, and reclaim_idx. 3749 * Confirm they are large enough for max values. 3750 */ 3751 BUILD_BUG_ON(MAX_ORDER > S8_MAX); 3752 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX); 3753 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX); 3754 3755 /* 3756 * Do not enter reclaim if fatal signal was delivered while throttled. 3757 * 1 is returned so that the page allocator does not OOM kill at this 3758 * point. 3759 */ 3760 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask)) 3761 return 1; 3762 3763 set_task_reclaim_state(current, &sc.reclaim_state); 3764 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask); 3765 3766 nr_reclaimed = do_try_to_free_pages(zonelist, &sc); 3767 3768 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed); 3769 set_task_reclaim_state(current, NULL); 3770 3771 return nr_reclaimed; 3772 } 3773 3774 #ifdef CONFIG_MEMCG 3775 3776 /* Only used by soft limit reclaim. Do not reuse for anything else. */ 3777 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg, 3778 gfp_t gfp_mask, bool noswap, 3779 pg_data_t *pgdat, 3780 unsigned long *nr_scanned) 3781 { 3782 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat); 3783 struct scan_control sc = { 3784 .nr_to_reclaim = SWAP_CLUSTER_MAX, 3785 .target_mem_cgroup = memcg, 3786 .may_writepage = !laptop_mode, 3787 .may_unmap = 1, 3788 .reclaim_idx = MAX_NR_ZONES - 1, 3789 .may_swap = !noswap, 3790 }; 3791 3792 WARN_ON_ONCE(!current->reclaim_state); 3793 3794 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) | 3795 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK); 3796 3797 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order, 3798 sc.gfp_mask); 3799 3800 /* 3801 * NOTE: Although we can get the priority field, using it 3802 * here is not a good idea, since it limits the pages we can scan. 3803 * if we don't reclaim here, the shrink_node from balance_pgdat 3804 * will pick up pages from other mem cgroup's as well. We hack 3805 * the priority and make it zero. 3806 */ 3807 shrink_lruvec(lruvec, &sc); 3808 3809 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed); 3810 3811 *nr_scanned = sc.nr_scanned; 3812 3813 return sc.nr_reclaimed; 3814 } 3815 3816 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg, 3817 unsigned long nr_pages, 3818 gfp_t gfp_mask, 3819 bool may_swap) 3820 { 3821 unsigned long nr_reclaimed; 3822 unsigned int noreclaim_flag; 3823 struct scan_control sc = { 3824 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX), 3825 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) | 3826 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK), 3827 .reclaim_idx = MAX_NR_ZONES - 1, 3828 .target_mem_cgroup = memcg, 3829 .priority = DEF_PRIORITY, 3830 .may_writepage = !laptop_mode, 3831 .may_unmap = 1, 3832 .may_swap = may_swap, 3833 }; 3834 /* 3835 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put 3836 * equal pressure on all the nodes. This is based on the assumption that 3837 * the reclaim does not bail out early. 3838 */ 3839 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask); 3840 3841 set_task_reclaim_state(current, &sc.reclaim_state); 3842 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask); 3843 noreclaim_flag = memalloc_noreclaim_save(); 3844 3845 nr_reclaimed = do_try_to_free_pages(zonelist, &sc); 3846 3847 memalloc_noreclaim_restore(noreclaim_flag); 3848 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed); 3849 set_task_reclaim_state(current, NULL); 3850 3851 return nr_reclaimed; 3852 } 3853 #endif 3854 3855 static void age_active_anon(struct pglist_data *pgdat, 3856 struct scan_control *sc) 3857 { 3858 struct mem_cgroup *memcg; 3859 struct lruvec *lruvec; 3860 3861 if (!can_age_anon_pages(pgdat, sc)) 3862 return; 3863 3864 lruvec = mem_cgroup_lruvec(NULL, pgdat); 3865 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON)) 3866 return; 3867 3868 memcg = mem_cgroup_iter(NULL, NULL, NULL); 3869 do { 3870 lruvec = mem_cgroup_lruvec(memcg, pgdat); 3871 shrink_active_list(SWAP_CLUSTER_MAX, lruvec, 3872 sc, LRU_ACTIVE_ANON); 3873 memcg = mem_cgroup_iter(NULL, memcg, NULL); 3874 } while (memcg); 3875 } 3876 3877 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx) 3878 { 3879 int i; 3880 struct zone *zone; 3881 3882 /* 3883 * Check for watermark boosts top-down as the higher zones 3884 * are more likely to be boosted. Both watermarks and boosts 3885 * should not be checked at the same time as reclaim would 3886 * start prematurely when there is no boosting and a lower 3887 * zone is balanced. 3888 */ 3889 for (i = highest_zoneidx; i >= 0; i--) { 3890 zone = pgdat->node_zones + i; 3891 if (!managed_zone(zone)) 3892 continue; 3893 3894 if (zone->watermark_boost) 3895 return true; 3896 } 3897 3898 return false; 3899 } 3900 3901 /* 3902 * Returns true if there is an eligible zone balanced for the request order 3903 * and highest_zoneidx 3904 */ 3905 static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx) 3906 { 3907 int i; 3908 unsigned long mark = -1; 3909 struct zone *zone; 3910 3911 /* 3912 * Check watermarks bottom-up as lower zones are more likely to 3913 * meet watermarks. 3914 */ 3915 for (i = 0; i <= highest_zoneidx; i++) { 3916 zone = pgdat->node_zones + i; 3917 3918 if (!managed_zone(zone)) 3919 continue; 3920 3921 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) 3922 mark = wmark_pages(zone, WMARK_PROMO); 3923 else 3924 mark = high_wmark_pages(zone); 3925 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx)) 3926 return true; 3927 } 3928 3929 /* 3930 * If a node has no managed zone within highest_zoneidx, it does not 3931 * need balancing by definition. This can happen if a zone-restricted 3932 * allocation tries to wake a remote kswapd. 3933 */ 3934 if (mark == -1) 3935 return true; 3936 3937 return false; 3938 } 3939 3940 /* Clear pgdat state for congested, dirty or under writeback. */ 3941 static void clear_pgdat_congested(pg_data_t *pgdat) 3942 { 3943 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat); 3944 3945 clear_bit(LRUVEC_CONGESTED, &lruvec->flags); 3946 clear_bit(PGDAT_DIRTY, &pgdat->flags); 3947 clear_bit(PGDAT_WRITEBACK, &pgdat->flags); 3948 } 3949 3950 /* 3951 * Prepare kswapd for sleeping. This verifies that there are no processes 3952 * waiting in throttle_direct_reclaim() and that watermarks have been met. 3953 * 3954 * Returns true if kswapd is ready to sleep 3955 */ 3956 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, 3957 int highest_zoneidx) 3958 { 3959 /* 3960 * The throttled processes are normally woken up in balance_pgdat() as 3961 * soon as allow_direct_reclaim() is true. But there is a potential 3962 * race between when kswapd checks the watermarks and a process gets 3963 * throttled. There is also a potential race if processes get 3964 * throttled, kswapd wakes, a large process exits thereby balancing the 3965 * zones, which causes kswapd to exit balance_pgdat() before reaching 3966 * the wake up checks. If kswapd is going to sleep, no process should 3967 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If 3968 * the wake up is premature, processes will wake kswapd and get 3969 * throttled again. The difference from wake ups in balance_pgdat() is 3970 * that here we are under prepare_to_wait(). 3971 */ 3972 if (waitqueue_active(&pgdat->pfmemalloc_wait)) 3973 wake_up_all(&pgdat->pfmemalloc_wait); 3974 3975 /* Hopeless node, leave it to direct reclaim */ 3976 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES) 3977 return true; 3978 3979 if (pgdat_balanced(pgdat, order, highest_zoneidx)) { 3980 clear_pgdat_congested(pgdat); 3981 return true; 3982 } 3983 3984 return false; 3985 } 3986 3987 /* 3988 * kswapd shrinks a node of pages that are at or below the highest usable 3989 * zone that is currently unbalanced. 3990 * 3991 * Returns true if kswapd scanned at least the requested number of pages to 3992 * reclaim or if the lack of progress was due to pages under writeback. 3993 * This is used to determine if the scanning priority needs to be raised. 3994 */ 3995 static bool kswapd_shrink_node(pg_data_t *pgdat, 3996 struct scan_control *sc) 3997 { 3998 struct zone *zone; 3999 int z; 4000 4001 /* Reclaim a number of pages proportional to the number of zones */ 4002 sc->nr_to_reclaim = 0; 4003 for (z = 0; z <= sc->reclaim_idx; z++) { 4004 zone = pgdat->node_zones + z; 4005 if (!managed_zone(zone)) 4006 continue; 4007 4008 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX); 4009 } 4010 4011 /* 4012 * Historically care was taken to put equal pressure on all zones but 4013 * now pressure is applied based on node LRU order. 4014 */ 4015 shrink_node(pgdat, sc); 4016 4017 /* 4018 * Fragmentation may mean that the system cannot be rebalanced for 4019 * high-order allocations. If twice the allocation size has been 4020 * reclaimed then recheck watermarks only at order-0 to prevent 4021 * excessive reclaim. Assume that a process requested a high-order 4022 * can direct reclaim/compact. 4023 */ 4024 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order)) 4025 sc->order = 0; 4026 4027 return sc->nr_scanned >= sc->nr_to_reclaim; 4028 } 4029 4030 /* Page allocator PCP high watermark is lowered if reclaim is active. */ 4031 static inline void 4032 update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active) 4033 { 4034 int i; 4035 struct zone *zone; 4036 4037 for (i = 0; i <= highest_zoneidx; i++) { 4038 zone = pgdat->node_zones + i; 4039 4040 if (!managed_zone(zone)) 4041 continue; 4042 4043 if (active) 4044 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags); 4045 else 4046 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags); 4047 } 4048 } 4049 4050 static inline void 4051 set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx) 4052 { 4053 update_reclaim_active(pgdat, highest_zoneidx, true); 4054 } 4055 4056 static inline void 4057 clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx) 4058 { 4059 update_reclaim_active(pgdat, highest_zoneidx, false); 4060 } 4061 4062 /* 4063 * For kswapd, balance_pgdat() will reclaim pages across a node from zones 4064 * that are eligible for use by the caller until at least one zone is 4065 * balanced. 4066 * 4067 * Returns the order kswapd finished reclaiming at. 4068 * 4069 * kswapd scans the zones in the highmem->normal->dma direction. It skips 4070 * zones which have free_pages > high_wmark_pages(zone), but once a zone is 4071 * found to have free_pages <= high_wmark_pages(zone), any page in that zone 4072 * or lower is eligible for reclaim until at least one usable zone is 4073 * balanced. 4074 */ 4075 static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx) 4076 { 4077 int i; 4078 unsigned long nr_soft_reclaimed; 4079 unsigned long nr_soft_scanned; 4080 unsigned long pflags; 4081 unsigned long nr_boost_reclaim; 4082 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, }; 4083 bool boosted; 4084 struct zone *zone; 4085 struct scan_control sc = { 4086 .gfp_mask = GFP_KERNEL, 4087 .order = order, 4088 .may_unmap = 1, 4089 }; 4090 4091 set_task_reclaim_state(current, &sc.reclaim_state); 4092 psi_memstall_enter(&pflags); 4093 __fs_reclaim_acquire(_THIS_IP_); 4094 4095 count_vm_event(PAGEOUTRUN); 4096 4097 /* 4098 * Account for the reclaim boost. Note that the zone boost is left in 4099 * place so that parallel allocations that are near the watermark will 4100 * stall or direct reclaim until kswapd is finished. 4101 */ 4102 nr_boost_reclaim = 0; 4103 for (i = 0; i <= highest_zoneidx; i++) { 4104 zone = pgdat->node_zones + i; 4105 if (!managed_zone(zone)) 4106 continue; 4107 4108 nr_boost_reclaim += zone->watermark_boost; 4109 zone_boosts[i] = zone->watermark_boost; 4110 } 4111 boosted = nr_boost_reclaim; 4112 4113 restart: 4114 set_reclaim_active(pgdat, highest_zoneidx); 4115 sc.priority = DEF_PRIORITY; 4116 do { 4117 unsigned long nr_reclaimed = sc.nr_reclaimed; 4118 bool raise_priority = true; 4119 bool balanced; 4120 bool ret; 4121 4122 sc.reclaim_idx = highest_zoneidx; 4123 4124 /* 4125 * If the number of buffer_heads exceeds the maximum allowed 4126 * then consider reclaiming from all zones. This has a dual 4127 * purpose -- on 64-bit systems it is expected that 4128 * buffer_heads are stripped during active rotation. On 32-bit 4129 * systems, highmem pages can pin lowmem memory and shrinking 4130 * buffers can relieve lowmem pressure. Reclaim may still not 4131 * go ahead if all eligible zones for the original allocation 4132 * request are balanced to avoid excessive reclaim from kswapd. 4133 */ 4134 if (buffer_heads_over_limit) { 4135 for (i = MAX_NR_ZONES - 1; i >= 0; i--) { 4136 zone = pgdat->node_zones + i; 4137 if (!managed_zone(zone)) 4138 continue; 4139 4140 sc.reclaim_idx = i; 4141 break; 4142 } 4143 } 4144 4145 /* 4146 * If the pgdat is imbalanced then ignore boosting and preserve 4147 * the watermarks for a later time and restart. Note that the 4148 * zone watermarks will be still reset at the end of balancing 4149 * on the grounds that the normal reclaim should be enough to 4150 * re-evaluate if boosting is required when kswapd next wakes. 4151 */ 4152 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx); 4153 if (!balanced && nr_boost_reclaim) { 4154 nr_boost_reclaim = 0; 4155 goto restart; 4156 } 4157 4158 /* 4159 * If boosting is not active then only reclaim if there are no 4160 * eligible zones. Note that sc.reclaim_idx is not used as 4161 * buffer_heads_over_limit may have adjusted it. 4162 */ 4163 if (!nr_boost_reclaim && balanced) 4164 goto out; 4165 4166 /* Limit the priority of boosting to avoid reclaim writeback */ 4167 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2) 4168 raise_priority = false; 4169 4170 /* 4171 * Do not writeback or swap pages for boosted reclaim. The 4172 * intent is to relieve pressure not issue sub-optimal IO 4173 * from reclaim context. If no pages are reclaimed, the 4174 * reclaim will be aborted. 4175 */ 4176 sc.may_writepage = !laptop_mode && !nr_boost_reclaim; 4177 sc.may_swap = !nr_boost_reclaim; 4178 4179 /* 4180 * Do some background aging of the anon list, to give 4181 * pages a chance to be referenced before reclaiming. All 4182 * pages are rotated regardless of classzone as this is 4183 * about consistent aging. 4184 */ 4185 age_active_anon(pgdat, &sc); 4186 4187 /* 4188 * If we're getting trouble reclaiming, start doing writepage 4189 * even in laptop mode. 4190 */ 4191 if (sc.priority < DEF_PRIORITY - 2) 4192 sc.may_writepage = 1; 4193 4194 /* Call soft limit reclaim before calling shrink_node. */ 4195 sc.nr_scanned = 0; 4196 nr_soft_scanned = 0; 4197 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order, 4198 sc.gfp_mask, &nr_soft_scanned); 4199 sc.nr_reclaimed += nr_soft_reclaimed; 4200 4201 /* 4202 * There should be no need to raise the scanning priority if 4203 * enough pages are already being scanned that that high 4204 * watermark would be met at 100% efficiency. 4205 */ 4206 if (kswapd_shrink_node(pgdat, &sc)) 4207 raise_priority = false; 4208 4209 /* 4210 * If the low watermark is met there is no need for processes 4211 * to be throttled on pfmemalloc_wait as they should not be 4212 * able to safely make forward progress. Wake them 4213 */ 4214 if (waitqueue_active(&pgdat->pfmemalloc_wait) && 4215 allow_direct_reclaim(pgdat)) 4216 wake_up_all(&pgdat->pfmemalloc_wait); 4217 4218 /* Check if kswapd should be suspending */ 4219 __fs_reclaim_release(_THIS_IP_); 4220 ret = try_to_freeze(); 4221 __fs_reclaim_acquire(_THIS_IP_); 4222 if (ret || kthread_should_stop()) 4223 break; 4224 4225 /* 4226 * Raise priority if scanning rate is too low or there was no 4227 * progress in reclaiming pages 4228 */ 4229 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed; 4230 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed); 4231 4232 /* 4233 * If reclaim made no progress for a boost, stop reclaim as 4234 * IO cannot be queued and it could be an infinite loop in 4235 * extreme circumstances. 4236 */ 4237 if (nr_boost_reclaim && !nr_reclaimed) 4238 break; 4239 4240 if (raise_priority || !nr_reclaimed) 4241 sc.priority--; 4242 } while (sc.priority >= 1); 4243 4244 if (!sc.nr_reclaimed) 4245 pgdat->kswapd_failures++; 4246 4247 out: 4248 clear_reclaim_active(pgdat, highest_zoneidx); 4249 4250 /* If reclaim was boosted, account for the reclaim done in this pass */ 4251 if (boosted) { 4252 unsigned long flags; 4253 4254 for (i = 0; i <= highest_zoneidx; i++) { 4255 if (!zone_boosts[i]) 4256 continue; 4257 4258 /* Increments are under the zone lock */ 4259 zone = pgdat->node_zones + i; 4260 spin_lock_irqsave(&zone->lock, flags); 4261 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]); 4262 spin_unlock_irqrestore(&zone->lock, flags); 4263 } 4264 4265 /* 4266 * As there is now likely space, wakeup kcompact to defragment 4267 * pageblocks. 4268 */ 4269 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx); 4270 } 4271 4272 snapshot_refaults(NULL, pgdat); 4273 __fs_reclaim_release(_THIS_IP_); 4274 psi_memstall_leave(&pflags); 4275 set_task_reclaim_state(current, NULL); 4276 4277 /* 4278 * Return the order kswapd stopped reclaiming at as 4279 * prepare_kswapd_sleep() takes it into account. If another caller 4280 * entered the allocator slow path while kswapd was awake, order will 4281 * remain at the higher level. 4282 */ 4283 return sc.order; 4284 } 4285 4286 /* 4287 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to 4288 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is 4289 * not a valid index then either kswapd runs for first time or kswapd couldn't 4290 * sleep after previous reclaim attempt (node is still unbalanced). In that 4291 * case return the zone index of the previous kswapd reclaim cycle. 4292 */ 4293 static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat, 4294 enum zone_type prev_highest_zoneidx) 4295 { 4296 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx); 4297 4298 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx; 4299 } 4300 4301 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order, 4302 unsigned int highest_zoneidx) 4303 { 4304 long remaining = 0; 4305 DEFINE_WAIT(wait); 4306 4307 if (freezing(current) || kthread_should_stop()) 4308 return; 4309 4310 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE); 4311 4312 /* 4313 * Try to sleep for a short interval. Note that kcompactd will only be 4314 * woken if it is possible to sleep for a short interval. This is 4315 * deliberate on the assumption that if reclaim cannot keep an 4316 * eligible zone balanced that it's also unlikely that compaction will 4317 * succeed. 4318 */ 4319 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) { 4320 /* 4321 * Compaction records what page blocks it recently failed to 4322 * isolate pages from and skips them in the future scanning. 4323 * When kswapd is going to sleep, it is reasonable to assume 4324 * that pages and compaction may succeed so reset the cache. 4325 */ 4326 reset_isolation_suitable(pgdat); 4327 4328 /* 4329 * We have freed the memory, now we should compact it to make 4330 * allocation of the requested order possible. 4331 */ 4332 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx); 4333 4334 remaining = schedule_timeout(HZ/10); 4335 4336 /* 4337 * If woken prematurely then reset kswapd_highest_zoneidx and 4338 * order. The values will either be from a wakeup request or 4339 * the previous request that slept prematurely. 4340 */ 4341 if (remaining) { 4342 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, 4343 kswapd_highest_zoneidx(pgdat, 4344 highest_zoneidx)); 4345 4346 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order) 4347 WRITE_ONCE(pgdat->kswapd_order, reclaim_order); 4348 } 4349 4350 finish_wait(&pgdat->kswapd_wait, &wait); 4351 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE); 4352 } 4353 4354 /* 4355 * After a short sleep, check if it was a premature sleep. If not, then 4356 * go fully to sleep until explicitly woken up. 4357 */ 4358 if (!remaining && 4359 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) { 4360 trace_mm_vmscan_kswapd_sleep(pgdat->node_id); 4361 4362 /* 4363 * vmstat counters are not perfectly accurate and the estimated 4364 * value for counters such as NR_FREE_PAGES can deviate from the 4365 * true value by nr_online_cpus * threshold. To avoid the zone 4366 * watermarks being breached while under pressure, we reduce the 4367 * per-cpu vmstat threshold while kswapd is awake and restore 4368 * them before going back to sleep. 4369 */ 4370 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold); 4371 4372 if (!kthread_should_stop()) 4373 schedule(); 4374 4375 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold); 4376 } else { 4377 if (remaining) 4378 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY); 4379 else 4380 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY); 4381 } 4382 finish_wait(&pgdat->kswapd_wait, &wait); 4383 } 4384 4385 /* 4386 * The background pageout daemon, started as a kernel thread 4387 * from the init process. 4388 * 4389 * This basically trickles out pages so that we have _some_ 4390 * free memory available even if there is no other activity 4391 * that frees anything up. This is needed for things like routing 4392 * etc, where we otherwise might have all activity going on in 4393 * asynchronous contexts that cannot page things out. 4394 * 4395 * If there are applications that are active memory-allocators 4396 * (most normal use), this basically shouldn't matter. 4397 */ 4398 static int kswapd(void *p) 4399 { 4400 unsigned int alloc_order, reclaim_order; 4401 unsigned int highest_zoneidx = MAX_NR_ZONES - 1; 4402 pg_data_t *pgdat = (pg_data_t *)p; 4403 struct task_struct *tsk = current; 4404 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id); 4405 4406 if (!cpumask_empty(cpumask)) 4407 set_cpus_allowed_ptr(tsk, cpumask); 4408 4409 /* 4410 * Tell the memory management that we're a "memory allocator", 4411 * and that if we need more memory we should get access to it 4412 * regardless (see "__alloc_pages()"). "kswapd" should 4413 * never get caught in the normal page freeing logic. 4414 * 4415 * (Kswapd normally doesn't need memory anyway, but sometimes 4416 * you need a small amount of memory in order to be able to 4417 * page out something else, and this flag essentially protects 4418 * us from recursively trying to free more memory as we're 4419 * trying to free the first piece of memory in the first place). 4420 */ 4421 tsk->flags |= PF_MEMALLOC | PF_KSWAPD; 4422 set_freezable(); 4423 4424 WRITE_ONCE(pgdat->kswapd_order, 0); 4425 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES); 4426 atomic_set(&pgdat->nr_writeback_throttled, 0); 4427 for ( ; ; ) { 4428 bool ret; 4429 4430 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order); 4431 highest_zoneidx = kswapd_highest_zoneidx(pgdat, 4432 highest_zoneidx); 4433 4434 kswapd_try_sleep: 4435 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order, 4436 highest_zoneidx); 4437 4438 /* Read the new order and highest_zoneidx */ 4439 alloc_order = READ_ONCE(pgdat->kswapd_order); 4440 highest_zoneidx = kswapd_highest_zoneidx(pgdat, 4441 highest_zoneidx); 4442 WRITE_ONCE(pgdat->kswapd_order, 0); 4443 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES); 4444 4445 ret = try_to_freeze(); 4446 if (kthread_should_stop()) 4447 break; 4448 4449 /* 4450 * We can speed up thawing tasks if we don't call balance_pgdat 4451 * after returning from the refrigerator 4452 */ 4453 if (ret) 4454 continue; 4455 4456 /* 4457 * Reclaim begins at the requested order but if a high-order 4458 * reclaim fails then kswapd falls back to reclaiming for 4459 * order-0. If that happens, kswapd will consider sleeping 4460 * for the order it finished reclaiming at (reclaim_order) 4461 * but kcompactd is woken to compact for the original 4462 * request (alloc_order). 4463 */ 4464 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx, 4465 alloc_order); 4466 reclaim_order = balance_pgdat(pgdat, alloc_order, 4467 highest_zoneidx); 4468 if (reclaim_order < alloc_order) 4469 goto kswapd_try_sleep; 4470 } 4471 4472 tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD); 4473 4474 return 0; 4475 } 4476 4477 /* 4478 * A zone is low on free memory or too fragmented for high-order memory. If 4479 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's 4480 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim 4481 * has failed or is not needed, still wake up kcompactd if only compaction is 4482 * needed. 4483 */ 4484 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order, 4485 enum zone_type highest_zoneidx) 4486 { 4487 pg_data_t *pgdat; 4488 enum zone_type curr_idx; 4489 4490 if (!managed_zone(zone)) 4491 return; 4492 4493 if (!cpuset_zone_allowed(zone, gfp_flags)) 4494 return; 4495 4496 pgdat = zone->zone_pgdat; 4497 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx); 4498 4499 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx) 4500 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx); 4501 4502 if (READ_ONCE(pgdat->kswapd_order) < order) 4503 WRITE_ONCE(pgdat->kswapd_order, order); 4504 4505 if (!waitqueue_active(&pgdat->kswapd_wait)) 4506 return; 4507 4508 /* Hopeless node, leave it to direct reclaim if possible */ 4509 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES || 4510 (pgdat_balanced(pgdat, order, highest_zoneidx) && 4511 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) { 4512 /* 4513 * There may be plenty of free memory available, but it's too 4514 * fragmented for high-order allocations. Wake up kcompactd 4515 * and rely on compaction_suitable() to determine if it's 4516 * needed. If it fails, it will defer subsequent attempts to 4517 * ratelimit its work. 4518 */ 4519 if (!(gfp_flags & __GFP_DIRECT_RECLAIM)) 4520 wakeup_kcompactd(pgdat, order, highest_zoneidx); 4521 return; 4522 } 4523 4524 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order, 4525 gfp_flags); 4526 wake_up_interruptible(&pgdat->kswapd_wait); 4527 } 4528 4529 #ifdef CONFIG_HIBERNATION 4530 /* 4531 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of 4532 * freed pages. 4533 * 4534 * Rather than trying to age LRUs the aim is to preserve the overall 4535 * LRU order by reclaiming preferentially 4536 * inactive > active > active referenced > active mapped 4537 */ 4538 unsigned long shrink_all_memory(unsigned long nr_to_reclaim) 4539 { 4540 struct scan_control sc = { 4541 .nr_to_reclaim = nr_to_reclaim, 4542 .gfp_mask = GFP_HIGHUSER_MOVABLE, 4543 .reclaim_idx = MAX_NR_ZONES - 1, 4544 .priority = DEF_PRIORITY, 4545 .may_writepage = 1, 4546 .may_unmap = 1, 4547 .may_swap = 1, 4548 .hibernation_mode = 1, 4549 }; 4550 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask); 4551 unsigned long nr_reclaimed; 4552 unsigned int noreclaim_flag; 4553 4554 fs_reclaim_acquire(sc.gfp_mask); 4555 noreclaim_flag = memalloc_noreclaim_save(); 4556 set_task_reclaim_state(current, &sc.reclaim_state); 4557 4558 nr_reclaimed = do_try_to_free_pages(zonelist, &sc); 4559 4560 set_task_reclaim_state(current, NULL); 4561 memalloc_noreclaim_restore(noreclaim_flag); 4562 fs_reclaim_release(sc.gfp_mask); 4563 4564 return nr_reclaimed; 4565 } 4566 #endif /* CONFIG_HIBERNATION */ 4567 4568 /* 4569 * This kswapd start function will be called by init and node-hot-add. 4570 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added. 4571 */ 4572 void kswapd_run(int nid) 4573 { 4574 pg_data_t *pgdat = NODE_DATA(nid); 4575 4576 if (pgdat->kswapd) 4577 return; 4578 4579 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid); 4580 if (IS_ERR(pgdat->kswapd)) { 4581 /* failure at boot is fatal */ 4582 BUG_ON(system_state < SYSTEM_RUNNING); 4583 pr_err("Failed to start kswapd on node %d\n", nid); 4584 pgdat->kswapd = NULL; 4585 } 4586 } 4587 4588 /* 4589 * Called by memory hotplug when all memory in a node is offlined. Caller must 4590 * hold mem_hotplug_begin/end(). 4591 */ 4592 void kswapd_stop(int nid) 4593 { 4594 struct task_struct *kswapd = NODE_DATA(nid)->kswapd; 4595 4596 if (kswapd) { 4597 kthread_stop(kswapd); 4598 NODE_DATA(nid)->kswapd = NULL; 4599 } 4600 } 4601 4602 static int __init kswapd_init(void) 4603 { 4604 int nid; 4605 4606 swap_setup(); 4607 for_each_node_state(nid, N_MEMORY) 4608 kswapd_run(nid); 4609 return 0; 4610 } 4611 4612 module_init(kswapd_init) 4613 4614 #ifdef CONFIG_NUMA 4615 /* 4616 * Node reclaim mode 4617 * 4618 * If non-zero call node_reclaim when the number of free pages falls below 4619 * the watermarks. 4620 */ 4621 int node_reclaim_mode __read_mostly; 4622 4623 /* 4624 * Priority for NODE_RECLAIM. This determines the fraction of pages 4625 * of a node considered for each zone_reclaim. 4 scans 1/16th of 4626 * a zone. 4627 */ 4628 #define NODE_RECLAIM_PRIORITY 4 4629 4630 /* 4631 * Percentage of pages in a zone that must be unmapped for node_reclaim to 4632 * occur. 4633 */ 4634 int sysctl_min_unmapped_ratio = 1; 4635 4636 /* 4637 * If the number of slab pages in a zone grows beyond this percentage then 4638 * slab reclaim needs to occur. 4639 */ 4640 int sysctl_min_slab_ratio = 5; 4641 4642 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat) 4643 { 4644 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED); 4645 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) + 4646 node_page_state(pgdat, NR_ACTIVE_FILE); 4647 4648 /* 4649 * It's possible for there to be more file mapped pages than 4650 * accounted for by the pages on the file LRU lists because 4651 * tmpfs pages accounted for as ANON can also be FILE_MAPPED 4652 */ 4653 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0; 4654 } 4655 4656 /* Work out how many page cache pages we can reclaim in this reclaim_mode */ 4657 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat) 4658 { 4659 unsigned long nr_pagecache_reclaimable; 4660 unsigned long delta = 0; 4661 4662 /* 4663 * If RECLAIM_UNMAP is set, then all file pages are considered 4664 * potentially reclaimable. Otherwise, we have to worry about 4665 * pages like swapcache and node_unmapped_file_pages() provides 4666 * a better estimate 4667 */ 4668 if (node_reclaim_mode & RECLAIM_UNMAP) 4669 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES); 4670 else 4671 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat); 4672 4673 /* If we can't clean pages, remove dirty pages from consideration */ 4674 if (!(node_reclaim_mode & RECLAIM_WRITE)) 4675 delta += node_page_state(pgdat, NR_FILE_DIRTY); 4676 4677 /* Watch for any possible underflows due to delta */ 4678 if (unlikely(delta > nr_pagecache_reclaimable)) 4679 delta = nr_pagecache_reclaimable; 4680 4681 return nr_pagecache_reclaimable - delta; 4682 } 4683 4684 /* 4685 * Try to free up some pages from this node through reclaim. 4686 */ 4687 static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order) 4688 { 4689 /* Minimum pages needed in order to stay on node */ 4690 const unsigned long nr_pages = 1 << order; 4691 struct task_struct *p = current; 4692 unsigned int noreclaim_flag; 4693 struct scan_control sc = { 4694 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX), 4695 .gfp_mask = current_gfp_context(gfp_mask), 4696 .order = order, 4697 .priority = NODE_RECLAIM_PRIORITY, 4698 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE), 4699 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP), 4700 .may_swap = 1, 4701 .reclaim_idx = gfp_zone(gfp_mask), 4702 }; 4703 unsigned long pflags; 4704 4705 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order, 4706 sc.gfp_mask); 4707 4708 cond_resched(); 4709 psi_memstall_enter(&pflags); 4710 fs_reclaim_acquire(sc.gfp_mask); 4711 /* 4712 * We need to be able to allocate from the reserves for RECLAIM_UNMAP 4713 */ 4714 noreclaim_flag = memalloc_noreclaim_save(); 4715 set_task_reclaim_state(p, &sc.reclaim_state); 4716 4717 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages || 4718 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) { 4719 /* 4720 * Free memory by calling shrink node with increasing 4721 * priorities until we have enough memory freed. 4722 */ 4723 do { 4724 shrink_node(pgdat, &sc); 4725 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0); 4726 } 4727 4728 set_task_reclaim_state(p, NULL); 4729 memalloc_noreclaim_restore(noreclaim_flag); 4730 fs_reclaim_release(sc.gfp_mask); 4731 psi_memstall_leave(&pflags); 4732 4733 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed); 4734 4735 return sc.nr_reclaimed >= nr_pages; 4736 } 4737 4738 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order) 4739 { 4740 int ret; 4741 4742 /* 4743 * Node reclaim reclaims unmapped file backed pages and 4744 * slab pages if we are over the defined limits. 4745 * 4746 * A small portion of unmapped file backed pages is needed for 4747 * file I/O otherwise pages read by file I/O will be immediately 4748 * thrown out if the node is overallocated. So we do not reclaim 4749 * if less than a specified percentage of the node is used by 4750 * unmapped file backed pages. 4751 */ 4752 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages && 4753 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <= 4754 pgdat->min_slab_pages) 4755 return NODE_RECLAIM_FULL; 4756 4757 /* 4758 * Do not scan if the allocation should not be delayed. 4759 */ 4760 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC)) 4761 return NODE_RECLAIM_NOSCAN; 4762 4763 /* 4764 * Only run node reclaim on the local node or on nodes that do not 4765 * have associated processors. This will favor the local processor 4766 * over remote processors and spread off node memory allocations 4767 * as wide as possible. 4768 */ 4769 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id()) 4770 return NODE_RECLAIM_NOSCAN; 4771 4772 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags)) 4773 return NODE_RECLAIM_NOSCAN; 4774 4775 ret = __node_reclaim(pgdat, gfp_mask, order); 4776 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags); 4777 4778 if (!ret) 4779 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED); 4780 4781 return ret; 4782 } 4783 #endif 4784 4785 /** 4786 * check_move_unevictable_pages - check pages for evictability and move to 4787 * appropriate zone lru list 4788 * @pvec: pagevec with lru pages to check 4789 * 4790 * Checks pages for evictability, if an evictable page is in the unevictable 4791 * lru list, moves it to the appropriate evictable lru list. This function 4792 * should be only used for lru pages. 4793 */ 4794 void check_move_unevictable_pages(struct pagevec *pvec) 4795 { 4796 struct lruvec *lruvec = NULL; 4797 int pgscanned = 0; 4798 int pgrescued = 0; 4799 int i; 4800 4801 for (i = 0; i < pvec->nr; i++) { 4802 struct page *page = pvec->pages[i]; 4803 struct folio *folio = page_folio(page); 4804 int nr_pages; 4805 4806 if (PageTransTail(page)) 4807 continue; 4808 4809 nr_pages = thp_nr_pages(page); 4810 pgscanned += nr_pages; 4811 4812 /* block memcg migration during page moving between lru */ 4813 if (!TestClearPageLRU(page)) 4814 continue; 4815 4816 lruvec = folio_lruvec_relock_irq(folio, lruvec); 4817 if (page_evictable(page) && PageUnevictable(page)) { 4818 del_page_from_lru_list(page, lruvec); 4819 ClearPageUnevictable(page); 4820 add_page_to_lru_list(page, lruvec); 4821 pgrescued += nr_pages; 4822 } 4823 SetPageLRU(page); 4824 } 4825 4826 if (lruvec) { 4827 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued); 4828 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned); 4829 unlock_page_lruvec_irq(lruvec); 4830 } else if (pgscanned) { 4831 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned); 4832 } 4833 } 4834 EXPORT_SYMBOL_GPL(check_move_unevictable_pages); 4835