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