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