1 /* 2 * linux/mm/vmscan.c 3 * 4 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds 5 * 6 * Swap reorganised 29.12.95, Stephen Tweedie. 7 * kswapd added: 7.1.96 sct 8 * Removed kswapd_ctl limits, and swap out as many pages as needed 9 * to bring the system back to freepages.high: 2.4.97, Rik van Riel. 10 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com). 11 * Multiqueue VM started 5.8.00, Rik van Riel. 12 */ 13 14 #include <linux/mm.h> 15 #include <linux/module.h> 16 #include <linux/gfp.h> 17 #include <linux/kernel_stat.h> 18 #include <linux/swap.h> 19 #include <linux/pagemap.h> 20 #include <linux/init.h> 21 #include <linux/highmem.h> 22 #include <linux/vmpressure.h> 23 #include <linux/vmstat.h> 24 #include <linux/file.h> 25 #include <linux/writeback.h> 26 #include <linux/blkdev.h> 27 #include <linux/buffer_head.h> /* for try_to_release_page(), 28 buffer_heads_over_limit */ 29 #include <linux/mm_inline.h> 30 #include <linux/backing-dev.h> 31 #include <linux/rmap.h> 32 #include <linux/topology.h> 33 #include <linux/cpu.h> 34 #include <linux/cpuset.h> 35 #include <linux/compaction.h> 36 #include <linux/notifier.h> 37 #include <linux/rwsem.h> 38 #include <linux/delay.h> 39 #include <linux/kthread.h> 40 #include <linux/freezer.h> 41 #include <linux/memcontrol.h> 42 #include <linux/delayacct.h> 43 #include <linux/sysctl.h> 44 #include <linux/oom.h> 45 #include <linux/prefetch.h> 46 47 #include <asm/tlbflush.h> 48 #include <asm/div64.h> 49 50 #include <linux/swapops.h> 51 #include <linux/balloon_compaction.h> 52 53 #include "internal.h" 54 55 #define CREATE_TRACE_POINTS 56 #include <trace/events/vmscan.h> 57 58 struct scan_control { 59 /* Incremented by the number of inactive pages that were scanned */ 60 unsigned long nr_scanned; 61 62 /* Number of pages freed so far during a call to shrink_zones() */ 63 unsigned long nr_reclaimed; 64 65 /* How many pages shrink_list() should reclaim */ 66 unsigned long nr_to_reclaim; 67 68 unsigned long hibernation_mode; 69 70 /* This context's GFP mask */ 71 gfp_t gfp_mask; 72 73 int may_writepage; 74 75 /* Can mapped pages be reclaimed? */ 76 int may_unmap; 77 78 /* Can pages be swapped as part of reclaim? */ 79 int may_swap; 80 81 int order; 82 83 /* Scan (total_size >> priority) pages at once */ 84 int priority; 85 86 /* 87 * The memory cgroup that hit its limit and as a result is the 88 * primary target of this reclaim invocation. 89 */ 90 struct mem_cgroup *target_mem_cgroup; 91 92 /* 93 * Nodemask of nodes allowed by the caller. If NULL, all nodes 94 * are scanned. 95 */ 96 nodemask_t *nodemask; 97 }; 98 99 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru)) 100 101 #ifdef ARCH_HAS_PREFETCH 102 #define prefetch_prev_lru_page(_page, _base, _field) \ 103 do { \ 104 if ((_page)->lru.prev != _base) { \ 105 struct page *prev; \ 106 \ 107 prev = lru_to_page(&(_page->lru)); \ 108 prefetch(&prev->_field); \ 109 } \ 110 } while (0) 111 #else 112 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0) 113 #endif 114 115 #ifdef ARCH_HAS_PREFETCHW 116 #define prefetchw_prev_lru_page(_page, _base, _field) \ 117 do { \ 118 if ((_page)->lru.prev != _base) { \ 119 struct page *prev; \ 120 \ 121 prev = lru_to_page(&(_page->lru)); \ 122 prefetchw(&prev->_field); \ 123 } \ 124 } while (0) 125 #else 126 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0) 127 #endif 128 129 /* 130 * From 0 .. 100. Higher means more swappy. 131 */ 132 int vm_swappiness = 60; 133 unsigned long vm_total_pages; /* The total number of pages which the VM controls */ 134 135 static LIST_HEAD(shrinker_list); 136 static DECLARE_RWSEM(shrinker_rwsem); 137 138 #ifdef CONFIG_MEMCG 139 static bool global_reclaim(struct scan_control *sc) 140 { 141 return !sc->target_mem_cgroup; 142 } 143 #else 144 static bool global_reclaim(struct scan_control *sc) 145 { 146 return true; 147 } 148 #endif 149 150 static unsigned long get_lru_size(struct lruvec *lruvec, enum lru_list lru) 151 { 152 if (!mem_cgroup_disabled()) 153 return mem_cgroup_get_lru_size(lruvec, lru); 154 155 return zone_page_state(lruvec_zone(lruvec), NR_LRU_BASE + lru); 156 } 157 158 /* 159 * Add a shrinker callback to be called from the vm 160 */ 161 void register_shrinker(struct shrinker *shrinker) 162 { 163 atomic_long_set(&shrinker->nr_in_batch, 0); 164 down_write(&shrinker_rwsem); 165 list_add_tail(&shrinker->list, &shrinker_list); 166 up_write(&shrinker_rwsem); 167 } 168 EXPORT_SYMBOL(register_shrinker); 169 170 /* 171 * Remove one 172 */ 173 void unregister_shrinker(struct shrinker *shrinker) 174 { 175 down_write(&shrinker_rwsem); 176 list_del(&shrinker->list); 177 up_write(&shrinker_rwsem); 178 } 179 EXPORT_SYMBOL(unregister_shrinker); 180 181 static inline int do_shrinker_shrink(struct shrinker *shrinker, 182 struct shrink_control *sc, 183 unsigned long nr_to_scan) 184 { 185 sc->nr_to_scan = nr_to_scan; 186 return (*shrinker->shrink)(shrinker, sc); 187 } 188 189 #define SHRINK_BATCH 128 190 /* 191 * Call the shrink functions to age shrinkable caches 192 * 193 * Here we assume it costs one seek to replace a lru page and that it also 194 * takes a seek to recreate a cache object. With this in mind we age equal 195 * percentages of the lru and ageable caches. This should balance the seeks 196 * generated by these structures. 197 * 198 * If the vm encountered mapped pages on the LRU it increase the pressure on 199 * slab to avoid swapping. 200 * 201 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits. 202 * 203 * `lru_pages' represents the number of on-LRU pages in all the zones which 204 * are eligible for the caller's allocation attempt. It is used for balancing 205 * slab reclaim versus page reclaim. 206 * 207 * Returns the number of slab objects which we shrunk. 208 */ 209 unsigned long shrink_slab(struct shrink_control *shrink, 210 unsigned long nr_pages_scanned, 211 unsigned long lru_pages) 212 { 213 struct shrinker *shrinker; 214 unsigned long ret = 0; 215 216 if (nr_pages_scanned == 0) 217 nr_pages_scanned = SWAP_CLUSTER_MAX; 218 219 if (!down_read_trylock(&shrinker_rwsem)) { 220 /* Assume we'll be able to shrink next time */ 221 ret = 1; 222 goto out; 223 } 224 225 list_for_each_entry(shrinker, &shrinker_list, list) { 226 unsigned long long delta; 227 long total_scan; 228 long max_pass; 229 int shrink_ret = 0; 230 long nr; 231 long new_nr; 232 long batch_size = shrinker->batch ? shrinker->batch 233 : SHRINK_BATCH; 234 235 max_pass = do_shrinker_shrink(shrinker, shrink, 0); 236 if (max_pass <= 0) 237 continue; 238 239 /* 240 * copy the current shrinker scan count into a local variable 241 * and zero it so that other concurrent shrinker invocations 242 * don't also do this scanning work. 243 */ 244 nr = atomic_long_xchg(&shrinker->nr_in_batch, 0); 245 246 total_scan = nr; 247 delta = (4 * nr_pages_scanned) / shrinker->seeks; 248 delta *= max_pass; 249 do_div(delta, lru_pages + 1); 250 total_scan += delta; 251 if (total_scan < 0) { 252 printk(KERN_ERR "shrink_slab: %pF negative objects to " 253 "delete nr=%ld\n", 254 shrinker->shrink, total_scan); 255 total_scan = max_pass; 256 } 257 258 /* 259 * We need to avoid excessive windup on filesystem shrinkers 260 * due to large numbers of GFP_NOFS allocations causing the 261 * shrinkers to return -1 all the time. This results in a large 262 * nr being built up so when a shrink that can do some work 263 * comes along it empties the entire cache due to nr >>> 264 * max_pass. This is bad for sustaining a working set in 265 * memory. 266 * 267 * Hence only allow the shrinker to scan the entire cache when 268 * a large delta change is calculated directly. 269 */ 270 if (delta < max_pass / 4) 271 total_scan = min(total_scan, max_pass / 2); 272 273 /* 274 * Avoid risking looping forever due to too large nr value: 275 * never try to free more than twice the estimate number of 276 * freeable entries. 277 */ 278 if (total_scan > max_pass * 2) 279 total_scan = max_pass * 2; 280 281 trace_mm_shrink_slab_start(shrinker, shrink, nr, 282 nr_pages_scanned, lru_pages, 283 max_pass, delta, total_scan); 284 285 while (total_scan >= batch_size) { 286 int nr_before; 287 288 nr_before = do_shrinker_shrink(shrinker, shrink, 0); 289 shrink_ret = do_shrinker_shrink(shrinker, shrink, 290 batch_size); 291 if (shrink_ret == -1) 292 break; 293 if (shrink_ret < nr_before) 294 ret += nr_before - shrink_ret; 295 count_vm_events(SLABS_SCANNED, batch_size); 296 total_scan -= batch_size; 297 298 cond_resched(); 299 } 300 301 /* 302 * move the unused scan count back into the shrinker in a 303 * manner that handles concurrent updates. If we exhausted the 304 * scan, there is no need to do an update. 305 */ 306 if (total_scan > 0) 307 new_nr = atomic_long_add_return(total_scan, 308 &shrinker->nr_in_batch); 309 else 310 new_nr = atomic_long_read(&shrinker->nr_in_batch); 311 312 trace_mm_shrink_slab_end(shrinker, shrink_ret, nr, new_nr); 313 } 314 up_read(&shrinker_rwsem); 315 out: 316 cond_resched(); 317 return ret; 318 } 319 320 static inline int is_page_cache_freeable(struct page *page) 321 { 322 /* 323 * A freeable page cache page is referenced only by the caller 324 * that isolated the page, the page cache radix tree and 325 * optional buffer heads at page->private. 326 */ 327 return page_count(page) - page_has_private(page) == 2; 328 } 329 330 static int may_write_to_queue(struct backing_dev_info *bdi, 331 struct scan_control *sc) 332 { 333 if (current->flags & PF_SWAPWRITE) 334 return 1; 335 if (!bdi_write_congested(bdi)) 336 return 1; 337 if (bdi == current->backing_dev_info) 338 return 1; 339 return 0; 340 } 341 342 /* 343 * We detected a synchronous write error writing a page out. Probably 344 * -ENOSPC. We need to propagate that into the address_space for a subsequent 345 * fsync(), msync() or close(). 346 * 347 * The tricky part is that after writepage we cannot touch the mapping: nothing 348 * prevents it from being freed up. But we have a ref on the page and once 349 * that page is locked, the mapping is pinned. 350 * 351 * We're allowed to run sleeping lock_page() here because we know the caller has 352 * __GFP_FS. 353 */ 354 static void handle_write_error(struct address_space *mapping, 355 struct page *page, int error) 356 { 357 lock_page(page); 358 if (page_mapping(page) == mapping) 359 mapping_set_error(mapping, error); 360 unlock_page(page); 361 } 362 363 /* possible outcome of pageout() */ 364 typedef enum { 365 /* failed to write page out, page is locked */ 366 PAGE_KEEP, 367 /* move page to the active list, page is locked */ 368 PAGE_ACTIVATE, 369 /* page has been sent to the disk successfully, page is unlocked */ 370 PAGE_SUCCESS, 371 /* page is clean and locked */ 372 PAGE_CLEAN, 373 } pageout_t; 374 375 /* 376 * pageout is called by shrink_page_list() for each dirty page. 377 * Calls ->writepage(). 378 */ 379 static pageout_t pageout(struct page *page, struct address_space *mapping, 380 struct scan_control *sc) 381 { 382 /* 383 * If the page is dirty, only perform writeback if that write 384 * will be non-blocking. To prevent this allocation from being 385 * stalled by pagecache activity. But note that there may be 386 * stalls if we need to run get_block(). We could test 387 * PagePrivate for that. 388 * 389 * If this process is currently in __generic_file_aio_write() against 390 * this page's queue, we can perform writeback even if that 391 * will block. 392 * 393 * If the page is swapcache, write it back even if that would 394 * block, for some throttling. This happens by accident, because 395 * swap_backing_dev_info is bust: it doesn't reflect the 396 * congestion state of the swapdevs. Easy to fix, if needed. 397 */ 398 if (!is_page_cache_freeable(page)) 399 return PAGE_KEEP; 400 if (!mapping) { 401 /* 402 * Some data journaling orphaned pages can have 403 * page->mapping == NULL while being dirty with clean buffers. 404 */ 405 if (page_has_private(page)) { 406 if (try_to_free_buffers(page)) { 407 ClearPageDirty(page); 408 printk("%s: orphaned page\n", __func__); 409 return PAGE_CLEAN; 410 } 411 } 412 return PAGE_KEEP; 413 } 414 if (mapping->a_ops->writepage == NULL) 415 return PAGE_ACTIVATE; 416 if (!may_write_to_queue(mapping->backing_dev_info, sc)) 417 return PAGE_KEEP; 418 419 if (clear_page_dirty_for_io(page)) { 420 int res; 421 struct writeback_control wbc = { 422 .sync_mode = WB_SYNC_NONE, 423 .nr_to_write = SWAP_CLUSTER_MAX, 424 .range_start = 0, 425 .range_end = LLONG_MAX, 426 .for_reclaim = 1, 427 }; 428 429 SetPageReclaim(page); 430 res = mapping->a_ops->writepage(page, &wbc); 431 if (res < 0) 432 handle_write_error(mapping, page, res); 433 if (res == AOP_WRITEPAGE_ACTIVATE) { 434 ClearPageReclaim(page); 435 return PAGE_ACTIVATE; 436 } 437 438 if (!PageWriteback(page)) { 439 /* synchronous write or broken a_ops? */ 440 ClearPageReclaim(page); 441 } 442 trace_mm_vmscan_writepage(page, trace_reclaim_flags(page)); 443 inc_zone_page_state(page, NR_VMSCAN_WRITE); 444 return PAGE_SUCCESS; 445 } 446 447 return PAGE_CLEAN; 448 } 449 450 /* 451 * Same as remove_mapping, but if the page is removed from the mapping, it 452 * gets returned with a refcount of 0. 453 */ 454 static int __remove_mapping(struct address_space *mapping, struct page *page) 455 { 456 BUG_ON(!PageLocked(page)); 457 BUG_ON(mapping != page_mapping(page)); 458 459 spin_lock_irq(&mapping->tree_lock); 460 /* 461 * The non racy check for a busy page. 462 * 463 * Must be careful with the order of the tests. When someone has 464 * a ref to the page, it may be possible that they dirty it then 465 * drop the reference. So if PageDirty is tested before page_count 466 * here, then the following race may occur: 467 * 468 * get_user_pages(&page); 469 * [user mapping goes away] 470 * write_to(page); 471 * !PageDirty(page) [good] 472 * SetPageDirty(page); 473 * put_page(page); 474 * !page_count(page) [good, discard it] 475 * 476 * [oops, our write_to data is lost] 477 * 478 * Reversing the order of the tests ensures such a situation cannot 479 * escape unnoticed. The smp_rmb is needed to ensure the page->flags 480 * load is not satisfied before that of page->_count. 481 * 482 * Note that if SetPageDirty is always performed via set_page_dirty, 483 * and thus under tree_lock, then this ordering is not required. 484 */ 485 if (!page_freeze_refs(page, 2)) 486 goto cannot_free; 487 /* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */ 488 if (unlikely(PageDirty(page))) { 489 page_unfreeze_refs(page, 2); 490 goto cannot_free; 491 } 492 493 if (PageSwapCache(page)) { 494 swp_entry_t swap = { .val = page_private(page) }; 495 __delete_from_swap_cache(page); 496 spin_unlock_irq(&mapping->tree_lock); 497 swapcache_free(swap, page); 498 } else { 499 void (*freepage)(struct page *); 500 501 freepage = mapping->a_ops->freepage; 502 503 __delete_from_page_cache(page); 504 spin_unlock_irq(&mapping->tree_lock); 505 mem_cgroup_uncharge_cache_page(page); 506 507 if (freepage != NULL) 508 freepage(page); 509 } 510 511 return 1; 512 513 cannot_free: 514 spin_unlock_irq(&mapping->tree_lock); 515 return 0; 516 } 517 518 /* 519 * Attempt to detach a locked page from its ->mapping. If it is dirty or if 520 * someone else has a ref on the page, abort and return 0. If it was 521 * successfully detached, return 1. Assumes the caller has a single ref on 522 * this page. 523 */ 524 int remove_mapping(struct address_space *mapping, struct page *page) 525 { 526 if (__remove_mapping(mapping, page)) { 527 /* 528 * Unfreezing the refcount with 1 rather than 2 effectively 529 * drops the pagecache ref for us without requiring another 530 * atomic operation. 531 */ 532 page_unfreeze_refs(page, 1); 533 return 1; 534 } 535 return 0; 536 } 537 538 /** 539 * putback_lru_page - put previously isolated page onto appropriate LRU list 540 * @page: page to be put back to appropriate lru list 541 * 542 * Add previously isolated @page to appropriate LRU list. 543 * Page may still be unevictable for other reasons. 544 * 545 * lru_lock must not be held, interrupts must be enabled. 546 */ 547 void putback_lru_page(struct page *page) 548 { 549 int lru; 550 int active = !!TestClearPageActive(page); 551 int was_unevictable = PageUnevictable(page); 552 553 VM_BUG_ON(PageLRU(page)); 554 555 redo: 556 ClearPageUnevictable(page); 557 558 if (page_evictable(page)) { 559 /* 560 * For evictable pages, we can use the cache. 561 * In event of a race, worst case is we end up with an 562 * unevictable page on [in]active list. 563 * We know how to handle that. 564 */ 565 lru = active + page_lru_base_type(page); 566 lru_cache_add_lru(page, lru); 567 } else { 568 /* 569 * Put unevictable pages directly on zone's unevictable 570 * list. 571 */ 572 lru = LRU_UNEVICTABLE; 573 add_page_to_unevictable_list(page); 574 /* 575 * When racing with an mlock or AS_UNEVICTABLE clearing 576 * (page is unlocked) make sure that if the other thread 577 * does not observe our setting of PG_lru and fails 578 * isolation/check_move_unevictable_pages, 579 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move 580 * the page back to the evictable list. 581 * 582 * The other side is TestClearPageMlocked() or shmem_lock(). 583 */ 584 smp_mb(); 585 } 586 587 /* 588 * page's status can change while we move it among lru. If an evictable 589 * page is on unevictable list, it never be freed. To avoid that, 590 * check after we added it to the list, again. 591 */ 592 if (lru == LRU_UNEVICTABLE && page_evictable(page)) { 593 if (!isolate_lru_page(page)) { 594 put_page(page); 595 goto redo; 596 } 597 /* This means someone else dropped this page from LRU 598 * So, it will be freed or putback to LRU again. There is 599 * nothing to do here. 600 */ 601 } 602 603 if (was_unevictable && lru != LRU_UNEVICTABLE) 604 count_vm_event(UNEVICTABLE_PGRESCUED); 605 else if (!was_unevictable && lru == LRU_UNEVICTABLE) 606 count_vm_event(UNEVICTABLE_PGCULLED); 607 608 put_page(page); /* drop ref from isolate */ 609 } 610 611 enum page_references { 612 PAGEREF_RECLAIM, 613 PAGEREF_RECLAIM_CLEAN, 614 PAGEREF_KEEP, 615 PAGEREF_ACTIVATE, 616 }; 617 618 static enum page_references page_check_references(struct page *page, 619 struct scan_control *sc) 620 { 621 int referenced_ptes, referenced_page; 622 unsigned long vm_flags; 623 624 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup, 625 &vm_flags); 626 referenced_page = TestClearPageReferenced(page); 627 628 /* 629 * Mlock lost the isolation race with us. Let try_to_unmap() 630 * move the page to the unevictable list. 631 */ 632 if (vm_flags & VM_LOCKED) 633 return PAGEREF_RECLAIM; 634 635 if (referenced_ptes) { 636 if (PageSwapBacked(page)) 637 return PAGEREF_ACTIVATE; 638 /* 639 * All mapped pages start out with page table 640 * references from the instantiating fault, so we need 641 * to look twice if a mapped file page is used more 642 * than once. 643 * 644 * Mark it and spare it for another trip around the 645 * inactive list. Another page table reference will 646 * lead to its activation. 647 * 648 * Note: the mark is set for activated pages as well 649 * so that recently deactivated but used pages are 650 * quickly recovered. 651 */ 652 SetPageReferenced(page); 653 654 if (referenced_page || referenced_ptes > 1) 655 return PAGEREF_ACTIVATE; 656 657 /* 658 * Activate file-backed executable pages after first usage. 659 */ 660 if (vm_flags & VM_EXEC) 661 return PAGEREF_ACTIVATE; 662 663 return PAGEREF_KEEP; 664 } 665 666 /* Reclaim if clean, defer dirty pages to writeback */ 667 if (referenced_page && !PageSwapBacked(page)) 668 return PAGEREF_RECLAIM_CLEAN; 669 670 return PAGEREF_RECLAIM; 671 } 672 673 /* 674 * shrink_page_list() returns the number of reclaimed pages 675 */ 676 static unsigned long shrink_page_list(struct list_head *page_list, 677 struct zone *zone, 678 struct scan_control *sc, 679 enum ttu_flags ttu_flags, 680 unsigned long *ret_nr_dirty, 681 unsigned long *ret_nr_writeback, 682 bool force_reclaim) 683 { 684 LIST_HEAD(ret_pages); 685 LIST_HEAD(free_pages); 686 int pgactivate = 0; 687 unsigned long nr_dirty = 0; 688 unsigned long nr_congested = 0; 689 unsigned long nr_reclaimed = 0; 690 unsigned long nr_writeback = 0; 691 692 cond_resched(); 693 694 mem_cgroup_uncharge_start(); 695 while (!list_empty(page_list)) { 696 struct address_space *mapping; 697 struct page *page; 698 int may_enter_fs; 699 enum page_references references = PAGEREF_RECLAIM_CLEAN; 700 701 cond_resched(); 702 703 page = lru_to_page(page_list); 704 list_del(&page->lru); 705 706 if (!trylock_page(page)) 707 goto keep; 708 709 VM_BUG_ON(PageActive(page)); 710 VM_BUG_ON(page_zone(page) != zone); 711 712 sc->nr_scanned++; 713 714 if (unlikely(!page_evictable(page))) 715 goto cull_mlocked; 716 717 if (!sc->may_unmap && page_mapped(page)) 718 goto keep_locked; 719 720 /* Double the slab pressure for mapped and swapcache pages */ 721 if (page_mapped(page) || PageSwapCache(page)) 722 sc->nr_scanned++; 723 724 may_enter_fs = (sc->gfp_mask & __GFP_FS) || 725 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO)); 726 727 if (PageWriteback(page)) { 728 /* 729 * memcg doesn't have any dirty pages throttling so we 730 * could easily OOM just because too many pages are in 731 * writeback and there is nothing else to reclaim. 732 * 733 * Require may_enter_fs to wait on writeback, because 734 * fs may not have submitted IO yet. And a loop driver 735 * thread might enter reclaim, and deadlock if it waits 736 * on a page for which it is needed to do the write 737 * (loop masks off __GFP_IO|__GFP_FS for this reason); 738 * but more thought would probably show more reasons. 739 */ 740 if (global_reclaim(sc) || 741 !PageReclaim(page) || !may_enter_fs) { 742 /* 743 * This is slightly racy - end_page_writeback() 744 * might have just cleared PageReclaim, then 745 * setting PageReclaim here end up interpreted 746 * as PageReadahead - but that does not matter 747 * enough to care. What we do want is for this 748 * page to have PageReclaim set next time memcg 749 * reclaim reaches the tests above, so it will 750 * then wait_on_page_writeback() to avoid OOM; 751 * and it's also appropriate in global reclaim. 752 */ 753 SetPageReclaim(page); 754 nr_writeback++; 755 goto keep_locked; 756 } 757 wait_on_page_writeback(page); 758 } 759 760 if (!force_reclaim) 761 references = page_check_references(page, sc); 762 763 switch (references) { 764 case PAGEREF_ACTIVATE: 765 goto activate_locked; 766 case PAGEREF_KEEP: 767 goto keep_locked; 768 case PAGEREF_RECLAIM: 769 case PAGEREF_RECLAIM_CLEAN: 770 ; /* try to reclaim the page below */ 771 } 772 773 /* 774 * Anonymous process memory has backing store? 775 * Try to allocate it some swap space here. 776 */ 777 if (PageAnon(page) && !PageSwapCache(page)) { 778 if (!(sc->gfp_mask & __GFP_IO)) 779 goto keep_locked; 780 if (!add_to_swap(page, page_list)) 781 goto activate_locked; 782 may_enter_fs = 1; 783 } 784 785 mapping = page_mapping(page); 786 787 /* 788 * The page is mapped into the page tables of one or more 789 * processes. Try to unmap it here. 790 */ 791 if (page_mapped(page) && mapping) { 792 switch (try_to_unmap(page, ttu_flags)) { 793 case SWAP_FAIL: 794 goto activate_locked; 795 case SWAP_AGAIN: 796 goto keep_locked; 797 case SWAP_MLOCK: 798 goto cull_mlocked; 799 case SWAP_SUCCESS: 800 ; /* try to free the page below */ 801 } 802 } 803 804 if (PageDirty(page)) { 805 nr_dirty++; 806 807 /* 808 * Only kswapd can writeback filesystem pages to 809 * avoid risk of stack overflow but do not writeback 810 * unless under significant pressure. 811 */ 812 if (page_is_file_cache(page) && 813 (!current_is_kswapd() || 814 sc->priority >= DEF_PRIORITY - 2)) { 815 /* 816 * Immediately reclaim when written back. 817 * Similar in principal to deactivate_page() 818 * except we already have the page isolated 819 * and know it's dirty 820 */ 821 inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE); 822 SetPageReclaim(page); 823 824 goto keep_locked; 825 } 826 827 if (references == PAGEREF_RECLAIM_CLEAN) 828 goto keep_locked; 829 if (!may_enter_fs) 830 goto keep_locked; 831 if (!sc->may_writepage) 832 goto keep_locked; 833 834 /* Page is dirty, try to write it out here */ 835 switch (pageout(page, mapping, sc)) { 836 case PAGE_KEEP: 837 nr_congested++; 838 goto keep_locked; 839 case PAGE_ACTIVATE: 840 goto activate_locked; 841 case PAGE_SUCCESS: 842 if (PageWriteback(page)) 843 goto keep; 844 if (PageDirty(page)) 845 goto keep; 846 847 /* 848 * A synchronous write - probably a ramdisk. Go 849 * ahead and try to reclaim the page. 850 */ 851 if (!trylock_page(page)) 852 goto keep; 853 if (PageDirty(page) || PageWriteback(page)) 854 goto keep_locked; 855 mapping = page_mapping(page); 856 case PAGE_CLEAN: 857 ; /* try to free the page below */ 858 } 859 } 860 861 /* 862 * If the page has buffers, try to free the buffer mappings 863 * associated with this page. If we succeed we try to free 864 * the page as well. 865 * 866 * We do this even if the page is PageDirty(). 867 * try_to_release_page() does not perform I/O, but it is 868 * possible for a page to have PageDirty set, but it is actually 869 * clean (all its buffers are clean). This happens if the 870 * buffers were written out directly, with submit_bh(). ext3 871 * will do this, as well as the blockdev mapping. 872 * try_to_release_page() will discover that cleanness and will 873 * drop the buffers and mark the page clean - it can be freed. 874 * 875 * Rarely, pages can have buffers and no ->mapping. These are 876 * the pages which were not successfully invalidated in 877 * truncate_complete_page(). We try to drop those buffers here 878 * and if that worked, and the page is no longer mapped into 879 * process address space (page_count == 1) it can be freed. 880 * Otherwise, leave the page on the LRU so it is swappable. 881 */ 882 if (page_has_private(page)) { 883 if (!try_to_release_page(page, sc->gfp_mask)) 884 goto activate_locked; 885 if (!mapping && page_count(page) == 1) { 886 unlock_page(page); 887 if (put_page_testzero(page)) 888 goto free_it; 889 else { 890 /* 891 * rare race with speculative reference. 892 * the speculative reference will free 893 * this page shortly, so we may 894 * increment nr_reclaimed here (and 895 * leave it off the LRU). 896 */ 897 nr_reclaimed++; 898 continue; 899 } 900 } 901 } 902 903 if (!mapping || !__remove_mapping(mapping, page)) 904 goto keep_locked; 905 906 /* 907 * At this point, we have no other references and there is 908 * no way to pick any more up (removed from LRU, removed 909 * from pagecache). Can use non-atomic bitops now (and 910 * we obviously don't have to worry about waking up a process 911 * waiting on the page lock, because there are no references. 912 */ 913 __clear_page_locked(page); 914 free_it: 915 nr_reclaimed++; 916 917 /* 918 * Is there need to periodically free_page_list? It would 919 * appear not as the counts should be low 920 */ 921 list_add(&page->lru, &free_pages); 922 continue; 923 924 cull_mlocked: 925 if (PageSwapCache(page)) 926 try_to_free_swap(page); 927 unlock_page(page); 928 list_add(&page->lru, &ret_pages); 929 continue; 930 931 activate_locked: 932 /* Not a candidate for swapping, so reclaim swap space. */ 933 if (PageSwapCache(page) && vm_swap_full()) 934 try_to_free_swap(page); 935 VM_BUG_ON(PageActive(page)); 936 SetPageActive(page); 937 pgactivate++; 938 keep_locked: 939 unlock_page(page); 940 keep: 941 list_add(&page->lru, &ret_pages); 942 VM_BUG_ON(PageLRU(page) || PageUnevictable(page)); 943 } 944 945 /* 946 * Tag a zone as congested if all the dirty pages encountered were 947 * backed by a congested BDI. In this case, reclaimers should just 948 * back off and wait for congestion to clear because further reclaim 949 * will encounter the same problem 950 */ 951 if (nr_dirty && nr_dirty == nr_congested && global_reclaim(sc)) 952 zone_set_flag(zone, ZONE_CONGESTED); 953 954 free_hot_cold_page_list(&free_pages, 1); 955 956 list_splice(&ret_pages, page_list); 957 count_vm_events(PGACTIVATE, pgactivate); 958 mem_cgroup_uncharge_end(); 959 *ret_nr_dirty += nr_dirty; 960 *ret_nr_writeback += nr_writeback; 961 return nr_reclaimed; 962 } 963 964 unsigned long reclaim_clean_pages_from_list(struct zone *zone, 965 struct list_head *page_list) 966 { 967 struct scan_control sc = { 968 .gfp_mask = GFP_KERNEL, 969 .priority = DEF_PRIORITY, 970 .may_unmap = 1, 971 }; 972 unsigned long ret, dummy1, dummy2; 973 struct page *page, *next; 974 LIST_HEAD(clean_pages); 975 976 list_for_each_entry_safe(page, next, page_list, lru) { 977 if (page_is_file_cache(page) && !PageDirty(page) && 978 !isolated_balloon_page(page)) { 979 ClearPageActive(page); 980 list_move(&page->lru, &clean_pages); 981 } 982 } 983 984 ret = shrink_page_list(&clean_pages, zone, &sc, 985 TTU_UNMAP|TTU_IGNORE_ACCESS, 986 &dummy1, &dummy2, true); 987 list_splice(&clean_pages, page_list); 988 __mod_zone_page_state(zone, NR_ISOLATED_FILE, -ret); 989 return ret; 990 } 991 992 /* 993 * Attempt to remove the specified page from its LRU. Only take this page 994 * if it is of the appropriate PageActive status. Pages which are being 995 * freed elsewhere are also ignored. 996 * 997 * page: page to consider 998 * mode: one of the LRU isolation modes defined above 999 * 1000 * returns 0 on success, -ve errno on failure. 1001 */ 1002 int __isolate_lru_page(struct page *page, isolate_mode_t mode) 1003 { 1004 int ret = -EINVAL; 1005 1006 /* Only take pages on the LRU. */ 1007 if (!PageLRU(page)) 1008 return ret; 1009 1010 /* Compaction should not handle unevictable pages but CMA can do so */ 1011 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE)) 1012 return ret; 1013 1014 ret = -EBUSY; 1015 1016 /* 1017 * To minimise LRU disruption, the caller can indicate that it only 1018 * wants to isolate pages it will be able to operate on without 1019 * blocking - clean pages for the most part. 1020 * 1021 * ISOLATE_CLEAN means that only clean pages should be isolated. This 1022 * is used by reclaim when it is cannot write to backing storage 1023 * 1024 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages 1025 * that it is possible to migrate without blocking 1026 */ 1027 if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) { 1028 /* All the caller can do on PageWriteback is block */ 1029 if (PageWriteback(page)) 1030 return ret; 1031 1032 if (PageDirty(page)) { 1033 struct address_space *mapping; 1034 1035 /* ISOLATE_CLEAN means only clean pages */ 1036 if (mode & ISOLATE_CLEAN) 1037 return ret; 1038 1039 /* 1040 * Only pages without mappings or that have a 1041 * ->migratepage callback are possible to migrate 1042 * without blocking 1043 */ 1044 mapping = page_mapping(page); 1045 if (mapping && !mapping->a_ops->migratepage) 1046 return ret; 1047 } 1048 } 1049 1050 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page)) 1051 return ret; 1052 1053 if (likely(get_page_unless_zero(page))) { 1054 /* 1055 * Be careful not to clear PageLRU until after we're 1056 * sure the page is not being freed elsewhere -- the 1057 * page release code relies on it. 1058 */ 1059 ClearPageLRU(page); 1060 ret = 0; 1061 } 1062 1063 return ret; 1064 } 1065 1066 /* 1067 * zone->lru_lock is heavily contended. Some of the functions that 1068 * shrink the lists perform better by taking out a batch of pages 1069 * and working on them outside the LRU lock. 1070 * 1071 * For pagecache intensive workloads, this function is the hottest 1072 * spot in the kernel (apart from copy_*_user functions). 1073 * 1074 * Appropriate locks must be held before calling this function. 1075 * 1076 * @nr_to_scan: The number of pages to look through on the list. 1077 * @lruvec: The LRU vector to pull pages from. 1078 * @dst: The temp list to put pages on to. 1079 * @nr_scanned: The number of pages that were scanned. 1080 * @sc: The scan_control struct for this reclaim session 1081 * @mode: One of the LRU isolation modes 1082 * @lru: LRU list id for isolating 1083 * 1084 * returns how many pages were moved onto *@dst. 1085 */ 1086 static unsigned long isolate_lru_pages(unsigned long nr_to_scan, 1087 struct lruvec *lruvec, struct list_head *dst, 1088 unsigned long *nr_scanned, struct scan_control *sc, 1089 isolate_mode_t mode, enum lru_list lru) 1090 { 1091 struct list_head *src = &lruvec->lists[lru]; 1092 unsigned long nr_taken = 0; 1093 unsigned long scan; 1094 1095 for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) { 1096 struct page *page; 1097 int nr_pages; 1098 1099 page = lru_to_page(src); 1100 prefetchw_prev_lru_page(page, src, flags); 1101 1102 VM_BUG_ON(!PageLRU(page)); 1103 1104 switch (__isolate_lru_page(page, mode)) { 1105 case 0: 1106 nr_pages = hpage_nr_pages(page); 1107 mem_cgroup_update_lru_size(lruvec, lru, -nr_pages); 1108 list_move(&page->lru, dst); 1109 nr_taken += nr_pages; 1110 break; 1111 1112 case -EBUSY: 1113 /* else it is being freed elsewhere */ 1114 list_move(&page->lru, src); 1115 continue; 1116 1117 default: 1118 BUG(); 1119 } 1120 } 1121 1122 *nr_scanned = scan; 1123 trace_mm_vmscan_lru_isolate(sc->order, nr_to_scan, scan, 1124 nr_taken, mode, is_file_lru(lru)); 1125 return nr_taken; 1126 } 1127 1128 /** 1129 * isolate_lru_page - tries to isolate a page from its LRU list 1130 * @page: page to isolate from its LRU list 1131 * 1132 * Isolates a @page from an LRU list, clears PageLRU and adjusts the 1133 * vmstat statistic corresponding to whatever LRU list the page was on. 1134 * 1135 * Returns 0 if the page was removed from an LRU list. 1136 * Returns -EBUSY if the page was not on an LRU list. 1137 * 1138 * The returned page will have PageLRU() cleared. If it was found on 1139 * the active list, it will have PageActive set. If it was found on 1140 * the unevictable list, it will have the PageUnevictable bit set. That flag 1141 * may need to be cleared by the caller before letting the page go. 1142 * 1143 * The vmstat statistic corresponding to the list on which the page was 1144 * found will be decremented. 1145 * 1146 * Restrictions: 1147 * (1) Must be called with an elevated refcount on the page. This is a 1148 * fundamentnal difference from isolate_lru_pages (which is called 1149 * without a stable reference). 1150 * (2) the lru_lock must not be held. 1151 * (3) interrupts must be enabled. 1152 */ 1153 int isolate_lru_page(struct page *page) 1154 { 1155 int ret = -EBUSY; 1156 1157 VM_BUG_ON(!page_count(page)); 1158 1159 if (PageLRU(page)) { 1160 struct zone *zone = page_zone(page); 1161 struct lruvec *lruvec; 1162 1163 spin_lock_irq(&zone->lru_lock); 1164 lruvec = mem_cgroup_page_lruvec(page, zone); 1165 if (PageLRU(page)) { 1166 int lru = page_lru(page); 1167 get_page(page); 1168 ClearPageLRU(page); 1169 del_page_from_lru_list(page, lruvec, lru); 1170 ret = 0; 1171 } 1172 spin_unlock_irq(&zone->lru_lock); 1173 } 1174 return ret; 1175 } 1176 1177 /* 1178 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and 1179 * then get resheduled. When there are massive number of tasks doing page 1180 * allocation, such sleeping direct reclaimers may keep piling up on each CPU, 1181 * the LRU list will go small and be scanned faster than necessary, leading to 1182 * unnecessary swapping, thrashing and OOM. 1183 */ 1184 static int too_many_isolated(struct zone *zone, int file, 1185 struct scan_control *sc) 1186 { 1187 unsigned long inactive, isolated; 1188 1189 if (current_is_kswapd()) 1190 return 0; 1191 1192 if (!global_reclaim(sc)) 1193 return 0; 1194 1195 if (file) { 1196 inactive = zone_page_state(zone, NR_INACTIVE_FILE); 1197 isolated = zone_page_state(zone, NR_ISOLATED_FILE); 1198 } else { 1199 inactive = zone_page_state(zone, NR_INACTIVE_ANON); 1200 isolated = zone_page_state(zone, NR_ISOLATED_ANON); 1201 } 1202 1203 /* 1204 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they 1205 * won't get blocked by normal direct-reclaimers, forming a circular 1206 * deadlock. 1207 */ 1208 if ((sc->gfp_mask & GFP_IOFS) == GFP_IOFS) 1209 inactive >>= 3; 1210 1211 return isolated > inactive; 1212 } 1213 1214 static noinline_for_stack void 1215 putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list) 1216 { 1217 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat; 1218 struct zone *zone = lruvec_zone(lruvec); 1219 LIST_HEAD(pages_to_free); 1220 1221 /* 1222 * Put back any unfreeable pages. 1223 */ 1224 while (!list_empty(page_list)) { 1225 struct page *page = lru_to_page(page_list); 1226 int lru; 1227 1228 VM_BUG_ON(PageLRU(page)); 1229 list_del(&page->lru); 1230 if (unlikely(!page_evictable(page))) { 1231 spin_unlock_irq(&zone->lru_lock); 1232 putback_lru_page(page); 1233 spin_lock_irq(&zone->lru_lock); 1234 continue; 1235 } 1236 1237 lruvec = mem_cgroup_page_lruvec(page, zone); 1238 1239 SetPageLRU(page); 1240 lru = page_lru(page); 1241 add_page_to_lru_list(page, lruvec, lru); 1242 1243 if (is_active_lru(lru)) { 1244 int file = is_file_lru(lru); 1245 int numpages = hpage_nr_pages(page); 1246 reclaim_stat->recent_rotated[file] += numpages; 1247 } 1248 if (put_page_testzero(page)) { 1249 __ClearPageLRU(page); 1250 __ClearPageActive(page); 1251 del_page_from_lru_list(page, lruvec, lru); 1252 1253 if (unlikely(PageCompound(page))) { 1254 spin_unlock_irq(&zone->lru_lock); 1255 (*get_compound_page_dtor(page))(page); 1256 spin_lock_irq(&zone->lru_lock); 1257 } else 1258 list_add(&page->lru, &pages_to_free); 1259 } 1260 } 1261 1262 /* 1263 * To save our caller's stack, now use input list for pages to free. 1264 */ 1265 list_splice(&pages_to_free, page_list); 1266 } 1267 1268 /* 1269 * shrink_inactive_list() is a helper for shrink_zone(). It returns the number 1270 * of reclaimed pages 1271 */ 1272 static noinline_for_stack unsigned long 1273 shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec, 1274 struct scan_control *sc, enum lru_list lru) 1275 { 1276 LIST_HEAD(page_list); 1277 unsigned long nr_scanned; 1278 unsigned long nr_reclaimed = 0; 1279 unsigned long nr_taken; 1280 unsigned long nr_dirty = 0; 1281 unsigned long nr_writeback = 0; 1282 isolate_mode_t isolate_mode = 0; 1283 int file = is_file_lru(lru); 1284 struct zone *zone = lruvec_zone(lruvec); 1285 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat; 1286 1287 while (unlikely(too_many_isolated(zone, file, sc))) { 1288 congestion_wait(BLK_RW_ASYNC, HZ/10); 1289 1290 /* We are about to die and free our memory. Return now. */ 1291 if (fatal_signal_pending(current)) 1292 return SWAP_CLUSTER_MAX; 1293 } 1294 1295 lru_add_drain(); 1296 1297 if (!sc->may_unmap) 1298 isolate_mode |= ISOLATE_UNMAPPED; 1299 if (!sc->may_writepage) 1300 isolate_mode |= ISOLATE_CLEAN; 1301 1302 spin_lock_irq(&zone->lru_lock); 1303 1304 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list, 1305 &nr_scanned, sc, isolate_mode, lru); 1306 1307 __mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken); 1308 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken); 1309 1310 if (global_reclaim(sc)) { 1311 zone->pages_scanned += nr_scanned; 1312 if (current_is_kswapd()) 1313 __count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scanned); 1314 else 1315 __count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scanned); 1316 } 1317 spin_unlock_irq(&zone->lru_lock); 1318 1319 if (nr_taken == 0) 1320 return 0; 1321 1322 nr_reclaimed = shrink_page_list(&page_list, zone, sc, TTU_UNMAP, 1323 &nr_dirty, &nr_writeback, false); 1324 1325 spin_lock_irq(&zone->lru_lock); 1326 1327 reclaim_stat->recent_scanned[file] += nr_taken; 1328 1329 if (global_reclaim(sc)) { 1330 if (current_is_kswapd()) 1331 __count_zone_vm_events(PGSTEAL_KSWAPD, zone, 1332 nr_reclaimed); 1333 else 1334 __count_zone_vm_events(PGSTEAL_DIRECT, zone, 1335 nr_reclaimed); 1336 } 1337 1338 putback_inactive_pages(lruvec, &page_list); 1339 1340 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken); 1341 1342 spin_unlock_irq(&zone->lru_lock); 1343 1344 free_hot_cold_page_list(&page_list, 1); 1345 1346 /* 1347 * If reclaim is isolating dirty pages under writeback, it implies 1348 * that the long-lived page allocation rate is exceeding the page 1349 * laundering rate. Either the global limits are not being effective 1350 * at throttling processes due to the page distribution throughout 1351 * zones or there is heavy usage of a slow backing device. The 1352 * only option is to throttle from reclaim context which is not ideal 1353 * as there is no guarantee the dirtying process is throttled in the 1354 * same way balance_dirty_pages() manages. 1355 * 1356 * This scales the number of dirty pages that must be under writeback 1357 * before throttling depending on priority. It is a simple backoff 1358 * function that has the most effect in the range DEF_PRIORITY to 1359 * DEF_PRIORITY-2 which is the priority reclaim is considered to be 1360 * in trouble and reclaim is considered to be in trouble. 1361 * 1362 * DEF_PRIORITY 100% isolated pages must be PageWriteback to throttle 1363 * DEF_PRIORITY-1 50% must be PageWriteback 1364 * DEF_PRIORITY-2 25% must be PageWriteback, kswapd in trouble 1365 * ... 1366 * DEF_PRIORITY-6 For SWAP_CLUSTER_MAX isolated pages, throttle if any 1367 * isolated page is PageWriteback 1368 */ 1369 if (nr_writeback && nr_writeback >= 1370 (nr_taken >> (DEF_PRIORITY - sc->priority))) 1371 wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10); 1372 1373 trace_mm_vmscan_lru_shrink_inactive(zone->zone_pgdat->node_id, 1374 zone_idx(zone), 1375 nr_scanned, nr_reclaimed, 1376 sc->priority, 1377 trace_shrink_flags(file)); 1378 return nr_reclaimed; 1379 } 1380 1381 /* 1382 * This moves pages from the active list to the inactive list. 1383 * 1384 * We move them the other way if the page is referenced by one or more 1385 * processes, from rmap. 1386 * 1387 * If the pages are mostly unmapped, the processing is fast and it is 1388 * appropriate to hold zone->lru_lock across the whole operation. But if 1389 * the pages are mapped, the processing is slow (page_referenced()) so we 1390 * should drop zone->lru_lock around each page. It's impossible to balance 1391 * this, so instead we remove the pages from the LRU while processing them. 1392 * It is safe to rely on PG_active against the non-LRU pages in here because 1393 * nobody will play with that bit on a non-LRU page. 1394 * 1395 * The downside is that we have to touch page->_count against each page. 1396 * But we had to alter page->flags anyway. 1397 */ 1398 1399 static void move_active_pages_to_lru(struct lruvec *lruvec, 1400 struct list_head *list, 1401 struct list_head *pages_to_free, 1402 enum lru_list lru) 1403 { 1404 struct zone *zone = lruvec_zone(lruvec); 1405 unsigned long pgmoved = 0; 1406 struct page *page; 1407 int nr_pages; 1408 1409 while (!list_empty(list)) { 1410 page = lru_to_page(list); 1411 lruvec = mem_cgroup_page_lruvec(page, zone); 1412 1413 VM_BUG_ON(PageLRU(page)); 1414 SetPageLRU(page); 1415 1416 nr_pages = hpage_nr_pages(page); 1417 mem_cgroup_update_lru_size(lruvec, lru, nr_pages); 1418 list_move(&page->lru, &lruvec->lists[lru]); 1419 pgmoved += nr_pages; 1420 1421 if (put_page_testzero(page)) { 1422 __ClearPageLRU(page); 1423 __ClearPageActive(page); 1424 del_page_from_lru_list(page, lruvec, lru); 1425 1426 if (unlikely(PageCompound(page))) { 1427 spin_unlock_irq(&zone->lru_lock); 1428 (*get_compound_page_dtor(page))(page); 1429 spin_lock_irq(&zone->lru_lock); 1430 } else 1431 list_add(&page->lru, pages_to_free); 1432 } 1433 } 1434 __mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved); 1435 if (!is_active_lru(lru)) 1436 __count_vm_events(PGDEACTIVATE, pgmoved); 1437 } 1438 1439 static void shrink_active_list(unsigned long nr_to_scan, 1440 struct lruvec *lruvec, 1441 struct scan_control *sc, 1442 enum lru_list lru) 1443 { 1444 unsigned long nr_taken; 1445 unsigned long nr_scanned; 1446 unsigned long vm_flags; 1447 LIST_HEAD(l_hold); /* The pages which were snipped off */ 1448 LIST_HEAD(l_active); 1449 LIST_HEAD(l_inactive); 1450 struct page *page; 1451 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat; 1452 unsigned long nr_rotated = 0; 1453 isolate_mode_t isolate_mode = 0; 1454 int file = is_file_lru(lru); 1455 struct zone *zone = lruvec_zone(lruvec); 1456 1457 lru_add_drain(); 1458 1459 if (!sc->may_unmap) 1460 isolate_mode |= ISOLATE_UNMAPPED; 1461 if (!sc->may_writepage) 1462 isolate_mode |= ISOLATE_CLEAN; 1463 1464 spin_lock_irq(&zone->lru_lock); 1465 1466 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold, 1467 &nr_scanned, sc, isolate_mode, lru); 1468 if (global_reclaim(sc)) 1469 zone->pages_scanned += nr_scanned; 1470 1471 reclaim_stat->recent_scanned[file] += nr_taken; 1472 1473 __count_zone_vm_events(PGREFILL, zone, nr_scanned); 1474 __mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken); 1475 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken); 1476 spin_unlock_irq(&zone->lru_lock); 1477 1478 while (!list_empty(&l_hold)) { 1479 cond_resched(); 1480 page = lru_to_page(&l_hold); 1481 list_del(&page->lru); 1482 1483 if (unlikely(!page_evictable(page))) { 1484 putback_lru_page(page); 1485 continue; 1486 } 1487 1488 if (unlikely(buffer_heads_over_limit)) { 1489 if (page_has_private(page) && trylock_page(page)) { 1490 if (page_has_private(page)) 1491 try_to_release_page(page, 0); 1492 unlock_page(page); 1493 } 1494 } 1495 1496 if (page_referenced(page, 0, sc->target_mem_cgroup, 1497 &vm_flags)) { 1498 nr_rotated += hpage_nr_pages(page); 1499 /* 1500 * Identify referenced, file-backed active pages and 1501 * give them one more trip around the active list. So 1502 * that executable code get better chances to stay in 1503 * memory under moderate memory pressure. Anon pages 1504 * are not likely to be evicted by use-once streaming 1505 * IO, plus JVM can create lots of anon VM_EXEC pages, 1506 * so we ignore them here. 1507 */ 1508 if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) { 1509 list_add(&page->lru, &l_active); 1510 continue; 1511 } 1512 } 1513 1514 ClearPageActive(page); /* we are de-activating */ 1515 list_add(&page->lru, &l_inactive); 1516 } 1517 1518 /* 1519 * Move pages back to the lru list. 1520 */ 1521 spin_lock_irq(&zone->lru_lock); 1522 /* 1523 * Count referenced pages from currently used mappings as rotated, 1524 * even though only some of them are actually re-activated. This 1525 * helps balance scan pressure between file and anonymous pages in 1526 * get_scan_ratio. 1527 */ 1528 reclaim_stat->recent_rotated[file] += nr_rotated; 1529 1530 move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru); 1531 move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE); 1532 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken); 1533 spin_unlock_irq(&zone->lru_lock); 1534 1535 free_hot_cold_page_list(&l_hold, 1); 1536 } 1537 1538 #ifdef CONFIG_SWAP 1539 static int inactive_anon_is_low_global(struct zone *zone) 1540 { 1541 unsigned long active, inactive; 1542 1543 active = zone_page_state(zone, NR_ACTIVE_ANON); 1544 inactive = zone_page_state(zone, NR_INACTIVE_ANON); 1545 1546 if (inactive * zone->inactive_ratio < active) 1547 return 1; 1548 1549 return 0; 1550 } 1551 1552 /** 1553 * inactive_anon_is_low - check if anonymous pages need to be deactivated 1554 * @lruvec: LRU vector to check 1555 * 1556 * Returns true if the zone does not have enough inactive anon pages, 1557 * meaning some active anon pages need to be deactivated. 1558 */ 1559 static int inactive_anon_is_low(struct lruvec *lruvec) 1560 { 1561 /* 1562 * If we don't have swap space, anonymous page deactivation 1563 * is pointless. 1564 */ 1565 if (!total_swap_pages) 1566 return 0; 1567 1568 if (!mem_cgroup_disabled()) 1569 return mem_cgroup_inactive_anon_is_low(lruvec); 1570 1571 return inactive_anon_is_low_global(lruvec_zone(lruvec)); 1572 } 1573 #else 1574 static inline int inactive_anon_is_low(struct lruvec *lruvec) 1575 { 1576 return 0; 1577 } 1578 #endif 1579 1580 /** 1581 * inactive_file_is_low - check if file pages need to be deactivated 1582 * @lruvec: LRU vector to check 1583 * 1584 * When the system is doing streaming IO, memory pressure here 1585 * ensures that active file pages get deactivated, until more 1586 * than half of the file pages are on the inactive list. 1587 * 1588 * Once we get to that situation, protect the system's working 1589 * set from being evicted by disabling active file page aging. 1590 * 1591 * This uses a different ratio than the anonymous pages, because 1592 * the page cache uses a use-once replacement algorithm. 1593 */ 1594 static int inactive_file_is_low(struct lruvec *lruvec) 1595 { 1596 unsigned long inactive; 1597 unsigned long active; 1598 1599 inactive = get_lru_size(lruvec, LRU_INACTIVE_FILE); 1600 active = get_lru_size(lruvec, LRU_ACTIVE_FILE); 1601 1602 return active > inactive; 1603 } 1604 1605 static int inactive_list_is_low(struct lruvec *lruvec, enum lru_list lru) 1606 { 1607 if (is_file_lru(lru)) 1608 return inactive_file_is_low(lruvec); 1609 else 1610 return inactive_anon_is_low(lruvec); 1611 } 1612 1613 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan, 1614 struct lruvec *lruvec, struct scan_control *sc) 1615 { 1616 if (is_active_lru(lru)) { 1617 if (inactive_list_is_low(lruvec, lru)) 1618 shrink_active_list(nr_to_scan, lruvec, sc, lru); 1619 return 0; 1620 } 1621 1622 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru); 1623 } 1624 1625 static int vmscan_swappiness(struct scan_control *sc) 1626 { 1627 if (global_reclaim(sc)) 1628 return vm_swappiness; 1629 return mem_cgroup_swappiness(sc->target_mem_cgroup); 1630 } 1631 1632 enum scan_balance { 1633 SCAN_EQUAL, 1634 SCAN_FRACT, 1635 SCAN_ANON, 1636 SCAN_FILE, 1637 }; 1638 1639 /* 1640 * Determine how aggressively the anon and file LRU lists should be 1641 * scanned. The relative value of each set of LRU lists is determined 1642 * by looking at the fraction of the pages scanned we did rotate back 1643 * onto the active list instead of evict. 1644 * 1645 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan 1646 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan 1647 */ 1648 static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc, 1649 unsigned long *nr) 1650 { 1651 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat; 1652 u64 fraction[2]; 1653 u64 denominator = 0; /* gcc */ 1654 struct zone *zone = lruvec_zone(lruvec); 1655 unsigned long anon_prio, file_prio; 1656 enum scan_balance scan_balance; 1657 unsigned long anon, file, free; 1658 bool force_scan = false; 1659 unsigned long ap, fp; 1660 enum lru_list lru; 1661 1662 /* 1663 * If the zone or memcg is small, nr[l] can be 0. This 1664 * results in no scanning on this priority and a potential 1665 * priority drop. Global direct reclaim can go to the next 1666 * zone and tends to have no problems. Global kswapd is for 1667 * zone balancing and it needs to scan a minimum amount. When 1668 * reclaiming for a memcg, a priority drop can cause high 1669 * latencies, so it's better to scan a minimum amount there as 1670 * well. 1671 */ 1672 if (current_is_kswapd() && zone->all_unreclaimable) 1673 force_scan = true; 1674 if (!global_reclaim(sc)) 1675 force_scan = true; 1676 1677 /* If we have no swap space, do not bother scanning anon pages. */ 1678 if (!sc->may_swap || (get_nr_swap_pages() <= 0)) { 1679 scan_balance = SCAN_FILE; 1680 goto out; 1681 } 1682 1683 /* 1684 * Global reclaim will swap to prevent OOM even with no 1685 * swappiness, but memcg users want to use this knob to 1686 * disable swapping for individual groups completely when 1687 * using the memory controller's swap limit feature would be 1688 * too expensive. 1689 */ 1690 if (!global_reclaim(sc) && !vmscan_swappiness(sc)) { 1691 scan_balance = SCAN_FILE; 1692 goto out; 1693 } 1694 1695 /* 1696 * Do not apply any pressure balancing cleverness when the 1697 * system is close to OOM, scan both anon and file equally 1698 * (unless the swappiness setting disagrees with swapping). 1699 */ 1700 if (!sc->priority && vmscan_swappiness(sc)) { 1701 scan_balance = SCAN_EQUAL; 1702 goto out; 1703 } 1704 1705 anon = get_lru_size(lruvec, LRU_ACTIVE_ANON) + 1706 get_lru_size(lruvec, LRU_INACTIVE_ANON); 1707 file = get_lru_size(lruvec, LRU_ACTIVE_FILE) + 1708 get_lru_size(lruvec, LRU_INACTIVE_FILE); 1709 1710 /* 1711 * If it's foreseeable that reclaiming the file cache won't be 1712 * enough to get the zone back into a desirable shape, we have 1713 * to swap. Better start now and leave the - probably heavily 1714 * thrashing - remaining file pages alone. 1715 */ 1716 if (global_reclaim(sc)) { 1717 free = zone_page_state(zone, NR_FREE_PAGES); 1718 if (unlikely(file + free <= high_wmark_pages(zone))) { 1719 scan_balance = SCAN_ANON; 1720 goto out; 1721 } 1722 } 1723 1724 /* 1725 * There is enough inactive page cache, do not reclaim 1726 * anything from the anonymous working set right now. 1727 */ 1728 if (!inactive_file_is_low(lruvec)) { 1729 scan_balance = SCAN_FILE; 1730 goto out; 1731 } 1732 1733 scan_balance = SCAN_FRACT; 1734 1735 /* 1736 * With swappiness at 100, anonymous and file have the same priority. 1737 * This scanning priority is essentially the inverse of IO cost. 1738 */ 1739 anon_prio = vmscan_swappiness(sc); 1740 file_prio = 200 - anon_prio; 1741 1742 /* 1743 * OK, so we have swap space and a fair amount of page cache 1744 * pages. We use the recently rotated / recently scanned 1745 * ratios to determine how valuable each cache is. 1746 * 1747 * Because workloads change over time (and to avoid overflow) 1748 * we keep these statistics as a floating average, which ends 1749 * up weighing recent references more than old ones. 1750 * 1751 * anon in [0], file in [1] 1752 */ 1753 spin_lock_irq(&zone->lru_lock); 1754 if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) { 1755 reclaim_stat->recent_scanned[0] /= 2; 1756 reclaim_stat->recent_rotated[0] /= 2; 1757 } 1758 1759 if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) { 1760 reclaim_stat->recent_scanned[1] /= 2; 1761 reclaim_stat->recent_rotated[1] /= 2; 1762 } 1763 1764 /* 1765 * The amount of pressure on anon vs file pages is inversely 1766 * proportional to the fraction of recently scanned pages on 1767 * each list that were recently referenced and in active use. 1768 */ 1769 ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1); 1770 ap /= reclaim_stat->recent_rotated[0] + 1; 1771 1772 fp = file_prio * (reclaim_stat->recent_scanned[1] + 1); 1773 fp /= reclaim_stat->recent_rotated[1] + 1; 1774 spin_unlock_irq(&zone->lru_lock); 1775 1776 fraction[0] = ap; 1777 fraction[1] = fp; 1778 denominator = ap + fp + 1; 1779 out: 1780 for_each_evictable_lru(lru) { 1781 int file = is_file_lru(lru); 1782 unsigned long size; 1783 unsigned long scan; 1784 1785 size = get_lru_size(lruvec, lru); 1786 scan = size >> sc->priority; 1787 1788 if (!scan && force_scan) 1789 scan = min(size, SWAP_CLUSTER_MAX); 1790 1791 switch (scan_balance) { 1792 case SCAN_EQUAL: 1793 /* Scan lists relative to size */ 1794 break; 1795 case SCAN_FRACT: 1796 /* 1797 * Scan types proportional to swappiness and 1798 * their relative recent reclaim efficiency. 1799 */ 1800 scan = div64_u64(scan * fraction[file], denominator); 1801 break; 1802 case SCAN_FILE: 1803 case SCAN_ANON: 1804 /* Scan one type exclusively */ 1805 if ((scan_balance == SCAN_FILE) != file) 1806 scan = 0; 1807 break; 1808 default: 1809 /* Look ma, no brain */ 1810 BUG(); 1811 } 1812 nr[lru] = scan; 1813 } 1814 } 1815 1816 /* 1817 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim. 1818 */ 1819 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc) 1820 { 1821 unsigned long nr[NR_LRU_LISTS]; 1822 unsigned long nr_to_scan; 1823 enum lru_list lru; 1824 unsigned long nr_reclaimed = 0; 1825 unsigned long nr_to_reclaim = sc->nr_to_reclaim; 1826 struct blk_plug plug; 1827 1828 get_scan_count(lruvec, sc, nr); 1829 1830 blk_start_plug(&plug); 1831 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] || 1832 nr[LRU_INACTIVE_FILE]) { 1833 for_each_evictable_lru(lru) { 1834 if (nr[lru]) { 1835 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX); 1836 nr[lru] -= nr_to_scan; 1837 1838 nr_reclaimed += shrink_list(lru, nr_to_scan, 1839 lruvec, sc); 1840 } 1841 } 1842 /* 1843 * On large memory systems, scan >> priority can become 1844 * really large. This is fine for the starting priority; 1845 * we want to put equal scanning pressure on each zone. 1846 * However, if the VM has a harder time of freeing pages, 1847 * with multiple processes reclaiming pages, the total 1848 * freeing target can get unreasonably large. 1849 */ 1850 if (nr_reclaimed >= nr_to_reclaim && 1851 sc->priority < DEF_PRIORITY) 1852 break; 1853 } 1854 blk_finish_plug(&plug); 1855 sc->nr_reclaimed += nr_reclaimed; 1856 1857 /* 1858 * Even if we did not try to evict anon pages at all, we want to 1859 * rebalance the anon lru active/inactive ratio. 1860 */ 1861 if (inactive_anon_is_low(lruvec)) 1862 shrink_active_list(SWAP_CLUSTER_MAX, lruvec, 1863 sc, LRU_ACTIVE_ANON); 1864 1865 throttle_vm_writeout(sc->gfp_mask); 1866 } 1867 1868 /* Use reclaim/compaction for costly allocs or under memory pressure */ 1869 static bool in_reclaim_compaction(struct scan_control *sc) 1870 { 1871 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order && 1872 (sc->order > PAGE_ALLOC_COSTLY_ORDER || 1873 sc->priority < DEF_PRIORITY - 2)) 1874 return true; 1875 1876 return false; 1877 } 1878 1879 /* 1880 * Reclaim/compaction is used for high-order allocation requests. It reclaims 1881 * order-0 pages before compacting the zone. should_continue_reclaim() returns 1882 * true if more pages should be reclaimed such that when the page allocator 1883 * calls try_to_compact_zone() that it will have enough free pages to succeed. 1884 * It will give up earlier than that if there is difficulty reclaiming pages. 1885 */ 1886 static inline bool should_continue_reclaim(struct zone *zone, 1887 unsigned long nr_reclaimed, 1888 unsigned long nr_scanned, 1889 struct scan_control *sc) 1890 { 1891 unsigned long pages_for_compaction; 1892 unsigned long inactive_lru_pages; 1893 1894 /* If not in reclaim/compaction mode, stop */ 1895 if (!in_reclaim_compaction(sc)) 1896 return false; 1897 1898 /* Consider stopping depending on scan and reclaim activity */ 1899 if (sc->gfp_mask & __GFP_REPEAT) { 1900 /* 1901 * For __GFP_REPEAT allocations, stop reclaiming if the 1902 * full LRU list has been scanned and we are still failing 1903 * to reclaim pages. This full LRU scan is potentially 1904 * expensive but a __GFP_REPEAT caller really wants to succeed 1905 */ 1906 if (!nr_reclaimed && !nr_scanned) 1907 return false; 1908 } else { 1909 /* 1910 * For non-__GFP_REPEAT allocations which can presumably 1911 * fail without consequence, stop if we failed to reclaim 1912 * any pages from the last SWAP_CLUSTER_MAX number of 1913 * pages that were scanned. This will return to the 1914 * caller faster at the risk reclaim/compaction and 1915 * the resulting allocation attempt fails 1916 */ 1917 if (!nr_reclaimed) 1918 return false; 1919 } 1920 1921 /* 1922 * If we have not reclaimed enough pages for compaction and the 1923 * inactive lists are large enough, continue reclaiming 1924 */ 1925 pages_for_compaction = (2UL << sc->order); 1926 inactive_lru_pages = zone_page_state(zone, NR_INACTIVE_FILE); 1927 if (get_nr_swap_pages() > 0) 1928 inactive_lru_pages += zone_page_state(zone, NR_INACTIVE_ANON); 1929 if (sc->nr_reclaimed < pages_for_compaction && 1930 inactive_lru_pages > pages_for_compaction) 1931 return true; 1932 1933 /* If compaction would go ahead or the allocation would succeed, stop */ 1934 switch (compaction_suitable(zone, sc->order)) { 1935 case COMPACT_PARTIAL: 1936 case COMPACT_CONTINUE: 1937 return false; 1938 default: 1939 return true; 1940 } 1941 } 1942 1943 static void shrink_zone(struct zone *zone, struct scan_control *sc) 1944 { 1945 unsigned long nr_reclaimed, nr_scanned; 1946 1947 do { 1948 struct mem_cgroup *root = sc->target_mem_cgroup; 1949 struct mem_cgroup_reclaim_cookie reclaim = { 1950 .zone = zone, 1951 .priority = sc->priority, 1952 }; 1953 struct mem_cgroup *memcg; 1954 1955 nr_reclaimed = sc->nr_reclaimed; 1956 nr_scanned = sc->nr_scanned; 1957 1958 memcg = mem_cgroup_iter(root, NULL, &reclaim); 1959 do { 1960 struct lruvec *lruvec; 1961 1962 lruvec = mem_cgroup_zone_lruvec(zone, memcg); 1963 1964 shrink_lruvec(lruvec, sc); 1965 1966 /* 1967 * Direct reclaim and kswapd have to scan all memory 1968 * cgroups to fulfill the overall scan target for the 1969 * zone. 1970 * 1971 * Limit reclaim, on the other hand, only cares about 1972 * nr_to_reclaim pages to be reclaimed and it will 1973 * retry with decreasing priority if one round over the 1974 * whole hierarchy is not sufficient. 1975 */ 1976 if (!global_reclaim(sc) && 1977 sc->nr_reclaimed >= sc->nr_to_reclaim) { 1978 mem_cgroup_iter_break(root, memcg); 1979 break; 1980 } 1981 memcg = mem_cgroup_iter(root, memcg, &reclaim); 1982 } while (memcg); 1983 1984 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, 1985 sc->nr_scanned - nr_scanned, 1986 sc->nr_reclaimed - nr_reclaimed); 1987 1988 } while (should_continue_reclaim(zone, sc->nr_reclaimed - nr_reclaimed, 1989 sc->nr_scanned - nr_scanned, sc)); 1990 } 1991 1992 /* Returns true if compaction should go ahead for a high-order request */ 1993 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc) 1994 { 1995 unsigned long balance_gap, watermark; 1996 bool watermark_ok; 1997 1998 /* Do not consider compaction for orders reclaim is meant to satisfy */ 1999 if (sc->order <= PAGE_ALLOC_COSTLY_ORDER) 2000 return false; 2001 2002 /* 2003 * Compaction takes time to run and there are potentially other 2004 * callers using the pages just freed. Continue reclaiming until 2005 * there is a buffer of free pages available to give compaction 2006 * a reasonable chance of completing and allocating the page 2007 */ 2008 balance_gap = min(low_wmark_pages(zone), 2009 (zone->managed_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) / 2010 KSWAPD_ZONE_BALANCE_GAP_RATIO); 2011 watermark = high_wmark_pages(zone) + balance_gap + (2UL << sc->order); 2012 watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, 0, 0); 2013 2014 /* 2015 * If compaction is deferred, reclaim up to a point where 2016 * compaction will have a chance of success when re-enabled 2017 */ 2018 if (compaction_deferred(zone, sc->order)) 2019 return watermark_ok; 2020 2021 /* If compaction is not ready to start, keep reclaiming */ 2022 if (!compaction_suitable(zone, sc->order)) 2023 return false; 2024 2025 return watermark_ok; 2026 } 2027 2028 /* 2029 * This is the direct reclaim path, for page-allocating processes. We only 2030 * try to reclaim pages from zones which will satisfy the caller's allocation 2031 * request. 2032 * 2033 * We reclaim from a zone even if that zone is over high_wmark_pages(zone). 2034 * Because: 2035 * a) The caller may be trying to free *extra* pages to satisfy a higher-order 2036 * allocation or 2037 * b) The target zone may be at high_wmark_pages(zone) but the lower zones 2038 * must go *over* high_wmark_pages(zone) to satisfy the `incremental min' 2039 * zone defense algorithm. 2040 * 2041 * If a zone is deemed to be full of pinned pages then just give it a light 2042 * scan then give up on it. 2043 * 2044 * This function returns true if a zone is being reclaimed for a costly 2045 * high-order allocation and compaction is ready to begin. This indicates to 2046 * the caller that it should consider retrying the allocation instead of 2047 * further reclaim. 2048 */ 2049 static bool shrink_zones(struct zonelist *zonelist, struct scan_control *sc) 2050 { 2051 struct zoneref *z; 2052 struct zone *zone; 2053 unsigned long nr_soft_reclaimed; 2054 unsigned long nr_soft_scanned; 2055 bool aborted_reclaim = false; 2056 2057 /* 2058 * If the number of buffer_heads in the machine exceeds the maximum 2059 * allowed level, force direct reclaim to scan the highmem zone as 2060 * highmem pages could be pinning lowmem pages storing buffer_heads 2061 */ 2062 if (buffer_heads_over_limit) 2063 sc->gfp_mask |= __GFP_HIGHMEM; 2064 2065 for_each_zone_zonelist_nodemask(zone, z, zonelist, 2066 gfp_zone(sc->gfp_mask), sc->nodemask) { 2067 if (!populated_zone(zone)) 2068 continue; 2069 /* 2070 * Take care memory controller reclaiming has small influence 2071 * to global LRU. 2072 */ 2073 if (global_reclaim(sc)) { 2074 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL)) 2075 continue; 2076 if (zone->all_unreclaimable && 2077 sc->priority != DEF_PRIORITY) 2078 continue; /* Let kswapd poll it */ 2079 if (IS_ENABLED(CONFIG_COMPACTION)) { 2080 /* 2081 * If we already have plenty of memory free for 2082 * compaction in this zone, don't free any more. 2083 * Even though compaction is invoked for any 2084 * non-zero order, only frequent costly order 2085 * reclamation is disruptive enough to become a 2086 * noticeable problem, like transparent huge 2087 * page allocations. 2088 */ 2089 if (compaction_ready(zone, sc)) { 2090 aborted_reclaim = true; 2091 continue; 2092 } 2093 } 2094 /* 2095 * This steals pages from memory cgroups over softlimit 2096 * and returns the number of reclaimed pages and 2097 * scanned pages. This works for global memory pressure 2098 * and balancing, not for a memcg's limit. 2099 */ 2100 nr_soft_scanned = 0; 2101 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone, 2102 sc->order, sc->gfp_mask, 2103 &nr_soft_scanned); 2104 sc->nr_reclaimed += nr_soft_reclaimed; 2105 sc->nr_scanned += nr_soft_scanned; 2106 /* need some check for avoid more shrink_zone() */ 2107 } 2108 2109 shrink_zone(zone, sc); 2110 } 2111 2112 return aborted_reclaim; 2113 } 2114 2115 static unsigned long zone_reclaimable_pages(struct zone *zone) 2116 { 2117 int nr; 2118 2119 nr = zone_page_state(zone, NR_ACTIVE_FILE) + 2120 zone_page_state(zone, NR_INACTIVE_FILE); 2121 2122 if (get_nr_swap_pages() > 0) 2123 nr += zone_page_state(zone, NR_ACTIVE_ANON) + 2124 zone_page_state(zone, NR_INACTIVE_ANON); 2125 2126 return nr; 2127 } 2128 2129 static bool zone_reclaimable(struct zone *zone) 2130 { 2131 return zone->pages_scanned < zone_reclaimable_pages(zone) * 6; 2132 } 2133 2134 /* All zones in zonelist are unreclaimable? */ 2135 static bool all_unreclaimable(struct zonelist *zonelist, 2136 struct scan_control *sc) 2137 { 2138 struct zoneref *z; 2139 struct zone *zone; 2140 2141 for_each_zone_zonelist_nodemask(zone, z, zonelist, 2142 gfp_zone(sc->gfp_mask), sc->nodemask) { 2143 if (!populated_zone(zone)) 2144 continue; 2145 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL)) 2146 continue; 2147 if (!zone->all_unreclaimable) 2148 return false; 2149 } 2150 2151 return true; 2152 } 2153 2154 /* 2155 * This is the main entry point to direct page reclaim. 2156 * 2157 * If a full scan of the inactive list fails to free enough memory then we 2158 * are "out of memory" and something needs to be killed. 2159 * 2160 * If the caller is !__GFP_FS then the probability of a failure is reasonably 2161 * high - the zone may be full of dirty or under-writeback pages, which this 2162 * caller can't do much about. We kick the writeback threads and take explicit 2163 * naps in the hope that some of these pages can be written. But if the 2164 * allocating task holds filesystem locks which prevent writeout this might not 2165 * work, and the allocation attempt will fail. 2166 * 2167 * returns: 0, if no pages reclaimed 2168 * else, the number of pages reclaimed 2169 */ 2170 static unsigned long do_try_to_free_pages(struct zonelist *zonelist, 2171 struct scan_control *sc, 2172 struct shrink_control *shrink) 2173 { 2174 unsigned long total_scanned = 0; 2175 struct reclaim_state *reclaim_state = current->reclaim_state; 2176 struct zoneref *z; 2177 struct zone *zone; 2178 unsigned long writeback_threshold; 2179 bool aborted_reclaim; 2180 2181 delayacct_freepages_start(); 2182 2183 if (global_reclaim(sc)) 2184 count_vm_event(ALLOCSTALL); 2185 2186 do { 2187 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup, 2188 sc->priority); 2189 sc->nr_scanned = 0; 2190 aborted_reclaim = shrink_zones(zonelist, sc); 2191 2192 /* 2193 * Don't shrink slabs when reclaiming memory from 2194 * over limit cgroups 2195 */ 2196 if (global_reclaim(sc)) { 2197 unsigned long lru_pages = 0; 2198 for_each_zone_zonelist(zone, z, zonelist, 2199 gfp_zone(sc->gfp_mask)) { 2200 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL)) 2201 continue; 2202 2203 lru_pages += zone_reclaimable_pages(zone); 2204 } 2205 2206 shrink_slab(shrink, sc->nr_scanned, lru_pages); 2207 if (reclaim_state) { 2208 sc->nr_reclaimed += reclaim_state->reclaimed_slab; 2209 reclaim_state->reclaimed_slab = 0; 2210 } 2211 } 2212 total_scanned += sc->nr_scanned; 2213 if (sc->nr_reclaimed >= sc->nr_to_reclaim) 2214 goto out; 2215 2216 /* 2217 * If we're getting trouble reclaiming, start doing 2218 * writepage even in laptop mode. 2219 */ 2220 if (sc->priority < DEF_PRIORITY - 2) 2221 sc->may_writepage = 1; 2222 2223 /* 2224 * Try to write back as many pages as we just scanned. This 2225 * tends to cause slow streaming writers to write data to the 2226 * disk smoothly, at the dirtying rate, which is nice. But 2227 * that's undesirable in laptop mode, where we *want* lumpy 2228 * writeout. So in laptop mode, write out the whole world. 2229 */ 2230 writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2; 2231 if (total_scanned > writeback_threshold) { 2232 wakeup_flusher_threads(laptop_mode ? 0 : total_scanned, 2233 WB_REASON_TRY_TO_FREE_PAGES); 2234 sc->may_writepage = 1; 2235 } 2236 2237 /* Take a nap, wait for some writeback to complete */ 2238 if (!sc->hibernation_mode && sc->nr_scanned && 2239 sc->priority < DEF_PRIORITY - 2) { 2240 struct zone *preferred_zone; 2241 2242 first_zones_zonelist(zonelist, gfp_zone(sc->gfp_mask), 2243 &cpuset_current_mems_allowed, 2244 &preferred_zone); 2245 wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/10); 2246 } 2247 } while (--sc->priority >= 0); 2248 2249 out: 2250 delayacct_freepages_end(); 2251 2252 if (sc->nr_reclaimed) 2253 return sc->nr_reclaimed; 2254 2255 /* 2256 * As hibernation is going on, kswapd is freezed so that it can't mark 2257 * the zone into all_unreclaimable. Thus bypassing all_unreclaimable 2258 * check. 2259 */ 2260 if (oom_killer_disabled) 2261 return 0; 2262 2263 /* Aborted reclaim to try compaction? don't OOM, then */ 2264 if (aborted_reclaim) 2265 return 1; 2266 2267 /* top priority shrink_zones still had more to do? don't OOM, then */ 2268 if (global_reclaim(sc) && !all_unreclaimable(zonelist, sc)) 2269 return 1; 2270 2271 return 0; 2272 } 2273 2274 static bool pfmemalloc_watermark_ok(pg_data_t *pgdat) 2275 { 2276 struct zone *zone; 2277 unsigned long pfmemalloc_reserve = 0; 2278 unsigned long free_pages = 0; 2279 int i; 2280 bool wmark_ok; 2281 2282 for (i = 0; i <= ZONE_NORMAL; i++) { 2283 zone = &pgdat->node_zones[i]; 2284 if (!populated_zone(zone)) 2285 continue; 2286 2287 pfmemalloc_reserve += min_wmark_pages(zone); 2288 free_pages += zone_page_state(zone, NR_FREE_PAGES); 2289 } 2290 2291 /* If there are no reserves (unexpected config) then do not throttle */ 2292 if (!pfmemalloc_reserve) 2293 return true; 2294 2295 wmark_ok = free_pages > pfmemalloc_reserve / 2; 2296 2297 /* kswapd must be awake if processes are being throttled */ 2298 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) { 2299 pgdat->classzone_idx = min(pgdat->classzone_idx, 2300 (enum zone_type)ZONE_NORMAL); 2301 wake_up_interruptible(&pgdat->kswapd_wait); 2302 } 2303 2304 return wmark_ok; 2305 } 2306 2307 /* 2308 * Throttle direct reclaimers if backing storage is backed by the network 2309 * and the PFMEMALLOC reserve for the preferred node is getting dangerously 2310 * depleted. kswapd will continue to make progress and wake the processes 2311 * when the low watermark is reached. 2312 * 2313 * Returns true if a fatal signal was delivered during throttling. If this 2314 * happens, the page allocator should not consider triggering the OOM killer. 2315 */ 2316 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist, 2317 nodemask_t *nodemask) 2318 { 2319 struct zoneref *z; 2320 struct zone *zone; 2321 pg_data_t *pgdat = NULL; 2322 2323 /* 2324 * Kernel threads should not be throttled as they may be indirectly 2325 * responsible for cleaning pages necessary for reclaim to make forward 2326 * progress. kjournald for example may enter direct reclaim while 2327 * committing a transaction where throttling it could forcing other 2328 * processes to block on log_wait_commit(). 2329 */ 2330 if (current->flags & PF_KTHREAD) 2331 goto out; 2332 2333 /* 2334 * If a fatal signal is pending, this process should not throttle. 2335 * It should return quickly so it can exit and free its memory 2336 */ 2337 if (fatal_signal_pending(current)) 2338 goto out; 2339 2340 /* 2341 * Check if the pfmemalloc reserves are ok by finding the first node 2342 * with a usable ZONE_NORMAL or lower zone. The expectation is that 2343 * GFP_KERNEL will be required for allocating network buffers when 2344 * swapping over the network so ZONE_HIGHMEM is unusable. 2345 * 2346 * Throttling is based on the first usable node and throttled processes 2347 * wait on a queue until kswapd makes progress and wakes them. There 2348 * is an affinity then between processes waking up and where reclaim 2349 * progress has been made assuming the process wakes on the same node. 2350 * More importantly, processes running on remote nodes will not compete 2351 * for remote pfmemalloc reserves and processes on different nodes 2352 * should make reasonable progress. 2353 */ 2354 for_each_zone_zonelist_nodemask(zone, z, zonelist, 2355 gfp_mask, nodemask) { 2356 if (zone_idx(zone) > ZONE_NORMAL) 2357 continue; 2358 2359 /* Throttle based on the first usable node */ 2360 pgdat = zone->zone_pgdat; 2361 if (pfmemalloc_watermark_ok(pgdat)) 2362 goto out; 2363 break; 2364 } 2365 2366 /* If no zone was usable by the allocation flags then do not throttle */ 2367 if (!pgdat) 2368 goto out; 2369 2370 /* Account for the throttling */ 2371 count_vm_event(PGSCAN_DIRECT_THROTTLE); 2372 2373 /* 2374 * If the caller cannot enter the filesystem, it's possible that it 2375 * is due to the caller holding an FS lock or performing a journal 2376 * transaction in the case of a filesystem like ext[3|4]. In this case, 2377 * it is not safe to block on pfmemalloc_wait as kswapd could be 2378 * blocked waiting on the same lock. Instead, throttle for up to a 2379 * second before continuing. 2380 */ 2381 if (!(gfp_mask & __GFP_FS)) { 2382 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait, 2383 pfmemalloc_watermark_ok(pgdat), HZ); 2384 2385 goto check_pending; 2386 } 2387 2388 /* Throttle until kswapd wakes the process */ 2389 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait, 2390 pfmemalloc_watermark_ok(pgdat)); 2391 2392 check_pending: 2393 if (fatal_signal_pending(current)) 2394 return true; 2395 2396 out: 2397 return false; 2398 } 2399 2400 unsigned long try_to_free_pages(struct zonelist *zonelist, int order, 2401 gfp_t gfp_mask, nodemask_t *nodemask) 2402 { 2403 unsigned long nr_reclaimed; 2404 struct scan_control sc = { 2405 .gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)), 2406 .may_writepage = !laptop_mode, 2407 .nr_to_reclaim = SWAP_CLUSTER_MAX, 2408 .may_unmap = 1, 2409 .may_swap = 1, 2410 .order = order, 2411 .priority = DEF_PRIORITY, 2412 .target_mem_cgroup = NULL, 2413 .nodemask = nodemask, 2414 }; 2415 struct shrink_control shrink = { 2416 .gfp_mask = sc.gfp_mask, 2417 }; 2418 2419 /* 2420 * Do not enter reclaim if fatal signal was delivered while throttled. 2421 * 1 is returned so that the page allocator does not OOM kill at this 2422 * point. 2423 */ 2424 if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask)) 2425 return 1; 2426 2427 trace_mm_vmscan_direct_reclaim_begin(order, 2428 sc.may_writepage, 2429 gfp_mask); 2430 2431 nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink); 2432 2433 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed); 2434 2435 return nr_reclaimed; 2436 } 2437 2438 #ifdef CONFIG_MEMCG 2439 2440 unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg, 2441 gfp_t gfp_mask, bool noswap, 2442 struct zone *zone, 2443 unsigned long *nr_scanned) 2444 { 2445 struct scan_control sc = { 2446 .nr_scanned = 0, 2447 .nr_to_reclaim = SWAP_CLUSTER_MAX, 2448 .may_writepage = !laptop_mode, 2449 .may_unmap = 1, 2450 .may_swap = !noswap, 2451 .order = 0, 2452 .priority = 0, 2453 .target_mem_cgroup = memcg, 2454 }; 2455 struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg); 2456 2457 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) | 2458 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK); 2459 2460 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order, 2461 sc.may_writepage, 2462 sc.gfp_mask); 2463 2464 /* 2465 * NOTE: Although we can get the priority field, using it 2466 * here is not a good idea, since it limits the pages we can scan. 2467 * if we don't reclaim here, the shrink_zone from balance_pgdat 2468 * will pick up pages from other mem cgroup's as well. We hack 2469 * the priority and make it zero. 2470 */ 2471 shrink_lruvec(lruvec, &sc); 2472 2473 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed); 2474 2475 *nr_scanned = sc.nr_scanned; 2476 return sc.nr_reclaimed; 2477 } 2478 2479 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg, 2480 gfp_t gfp_mask, 2481 bool noswap) 2482 { 2483 struct zonelist *zonelist; 2484 unsigned long nr_reclaimed; 2485 int nid; 2486 struct scan_control sc = { 2487 .may_writepage = !laptop_mode, 2488 .may_unmap = 1, 2489 .may_swap = !noswap, 2490 .nr_to_reclaim = SWAP_CLUSTER_MAX, 2491 .order = 0, 2492 .priority = DEF_PRIORITY, 2493 .target_mem_cgroup = memcg, 2494 .nodemask = NULL, /* we don't care the placement */ 2495 .gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) | 2496 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK), 2497 }; 2498 struct shrink_control shrink = { 2499 .gfp_mask = sc.gfp_mask, 2500 }; 2501 2502 /* 2503 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't 2504 * take care of from where we get pages. So the node where we start the 2505 * scan does not need to be the current node. 2506 */ 2507 nid = mem_cgroup_select_victim_node(memcg); 2508 2509 zonelist = NODE_DATA(nid)->node_zonelists; 2510 2511 trace_mm_vmscan_memcg_reclaim_begin(0, 2512 sc.may_writepage, 2513 sc.gfp_mask); 2514 2515 nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink); 2516 2517 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed); 2518 2519 return nr_reclaimed; 2520 } 2521 #endif 2522 2523 static void age_active_anon(struct zone *zone, struct scan_control *sc) 2524 { 2525 struct mem_cgroup *memcg; 2526 2527 if (!total_swap_pages) 2528 return; 2529 2530 memcg = mem_cgroup_iter(NULL, NULL, NULL); 2531 do { 2532 struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg); 2533 2534 if (inactive_anon_is_low(lruvec)) 2535 shrink_active_list(SWAP_CLUSTER_MAX, lruvec, 2536 sc, LRU_ACTIVE_ANON); 2537 2538 memcg = mem_cgroup_iter(NULL, memcg, NULL); 2539 } while (memcg); 2540 } 2541 2542 static bool zone_balanced(struct zone *zone, int order, 2543 unsigned long balance_gap, int classzone_idx) 2544 { 2545 if (!zone_watermark_ok_safe(zone, order, high_wmark_pages(zone) + 2546 balance_gap, classzone_idx, 0)) 2547 return false; 2548 2549 if (IS_ENABLED(CONFIG_COMPACTION) && order && 2550 !compaction_suitable(zone, order)) 2551 return false; 2552 2553 return true; 2554 } 2555 2556 /* 2557 * pgdat_balanced() is used when checking if a node is balanced. 2558 * 2559 * For order-0, all zones must be balanced! 2560 * 2561 * For high-order allocations only zones that meet watermarks and are in a 2562 * zone allowed by the callers classzone_idx are added to balanced_pages. The 2563 * total of balanced pages must be at least 25% of the zones allowed by 2564 * classzone_idx for the node to be considered balanced. Forcing all zones to 2565 * be balanced for high orders can cause excessive reclaim when there are 2566 * imbalanced zones. 2567 * The choice of 25% is due to 2568 * o a 16M DMA zone that is balanced will not balance a zone on any 2569 * reasonable sized machine 2570 * o On all other machines, the top zone must be at least a reasonable 2571 * percentage of the middle zones. For example, on 32-bit x86, highmem 2572 * would need to be at least 256M for it to be balance a whole node. 2573 * Similarly, on x86-64 the Normal zone would need to be at least 1G 2574 * to balance a node on its own. These seemed like reasonable ratios. 2575 */ 2576 static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx) 2577 { 2578 unsigned long managed_pages = 0; 2579 unsigned long balanced_pages = 0; 2580 int i; 2581 2582 /* Check the watermark levels */ 2583 for (i = 0; i <= classzone_idx; i++) { 2584 struct zone *zone = pgdat->node_zones + i; 2585 2586 if (!populated_zone(zone)) 2587 continue; 2588 2589 managed_pages += zone->managed_pages; 2590 2591 /* 2592 * A special case here: 2593 * 2594 * balance_pgdat() skips over all_unreclaimable after 2595 * DEF_PRIORITY. Effectively, it considers them balanced so 2596 * they must be considered balanced here as well! 2597 */ 2598 if (zone->all_unreclaimable) { 2599 balanced_pages += zone->managed_pages; 2600 continue; 2601 } 2602 2603 if (zone_balanced(zone, order, 0, i)) 2604 balanced_pages += zone->managed_pages; 2605 else if (!order) 2606 return false; 2607 } 2608 2609 if (order) 2610 return balanced_pages >= (managed_pages >> 2); 2611 else 2612 return true; 2613 } 2614 2615 /* 2616 * Prepare kswapd for sleeping. This verifies that there are no processes 2617 * waiting in throttle_direct_reclaim() and that watermarks have been met. 2618 * 2619 * Returns true if kswapd is ready to sleep 2620 */ 2621 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, long remaining, 2622 int classzone_idx) 2623 { 2624 /* If a direct reclaimer woke kswapd within HZ/10, it's premature */ 2625 if (remaining) 2626 return false; 2627 2628 /* 2629 * The throttled processes are normally woken up in balance_pgdat() as 2630 * soon as pfmemalloc_watermark_ok() is true. But there is a potential 2631 * race between when kswapd checks the watermarks and a process gets 2632 * throttled. There is also a potential race if processes get 2633 * throttled, kswapd wakes, a large process exits thereby balancing the 2634 * zones, which causes kswapd to exit balance_pgdat() before reaching 2635 * the wake up checks. If kswapd is going to sleep, no process should 2636 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If 2637 * the wake up is premature, processes will wake kswapd and get 2638 * throttled again. The difference from wake ups in balance_pgdat() is 2639 * that here we are under prepare_to_wait(). 2640 */ 2641 if (waitqueue_active(&pgdat->pfmemalloc_wait)) 2642 wake_up_all(&pgdat->pfmemalloc_wait); 2643 2644 return pgdat_balanced(pgdat, order, classzone_idx); 2645 } 2646 2647 /* 2648 * For kswapd, balance_pgdat() will work across all this node's zones until 2649 * they are all at high_wmark_pages(zone). 2650 * 2651 * Returns the final order kswapd was reclaiming at 2652 * 2653 * There is special handling here for zones which are full of pinned pages. 2654 * This can happen if the pages are all mlocked, or if they are all used by 2655 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb. 2656 * What we do is to detect the case where all pages in the zone have been 2657 * scanned twice and there has been zero successful reclaim. Mark the zone as 2658 * dead and from now on, only perform a short scan. Basically we're polling 2659 * the zone for when the problem goes away. 2660 * 2661 * kswapd scans the zones in the highmem->normal->dma direction. It skips 2662 * zones which have free_pages > high_wmark_pages(zone), but once a zone is 2663 * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the 2664 * lower zones regardless of the number of free pages in the lower zones. This 2665 * interoperates with the page allocator fallback scheme to ensure that aging 2666 * of pages is balanced across the zones. 2667 */ 2668 static unsigned long balance_pgdat(pg_data_t *pgdat, int order, 2669 int *classzone_idx) 2670 { 2671 bool pgdat_is_balanced = false; 2672 int i; 2673 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */ 2674 struct reclaim_state *reclaim_state = current->reclaim_state; 2675 unsigned long nr_soft_reclaimed; 2676 unsigned long nr_soft_scanned; 2677 struct scan_control sc = { 2678 .gfp_mask = GFP_KERNEL, 2679 .may_unmap = 1, 2680 .may_swap = 1, 2681 /* 2682 * kswapd doesn't want to be bailed out while reclaim. because 2683 * we want to put equal scanning pressure on each zone. 2684 */ 2685 .nr_to_reclaim = ULONG_MAX, 2686 .order = order, 2687 .target_mem_cgroup = NULL, 2688 }; 2689 struct shrink_control shrink = { 2690 .gfp_mask = sc.gfp_mask, 2691 }; 2692 loop_again: 2693 sc.priority = DEF_PRIORITY; 2694 sc.nr_reclaimed = 0; 2695 sc.may_writepage = !laptop_mode; 2696 count_vm_event(PAGEOUTRUN); 2697 2698 do { 2699 unsigned long lru_pages = 0; 2700 2701 /* 2702 * Scan in the highmem->dma direction for the highest 2703 * zone which needs scanning 2704 */ 2705 for (i = pgdat->nr_zones - 1; i >= 0; i--) { 2706 struct zone *zone = pgdat->node_zones + i; 2707 2708 if (!populated_zone(zone)) 2709 continue; 2710 2711 if (zone->all_unreclaimable && 2712 sc.priority != DEF_PRIORITY) 2713 continue; 2714 2715 /* 2716 * Do some background aging of the anon list, to give 2717 * pages a chance to be referenced before reclaiming. 2718 */ 2719 age_active_anon(zone, &sc); 2720 2721 /* 2722 * If the number of buffer_heads in the machine 2723 * exceeds the maximum allowed level and this node 2724 * has a highmem zone, force kswapd to reclaim from 2725 * it to relieve lowmem pressure. 2726 */ 2727 if (buffer_heads_over_limit && is_highmem_idx(i)) { 2728 end_zone = i; 2729 break; 2730 } 2731 2732 if (!zone_balanced(zone, order, 0, 0)) { 2733 end_zone = i; 2734 break; 2735 } else { 2736 /* If balanced, clear the congested flag */ 2737 zone_clear_flag(zone, ZONE_CONGESTED); 2738 } 2739 } 2740 2741 if (i < 0) { 2742 pgdat_is_balanced = true; 2743 goto out; 2744 } 2745 2746 for (i = 0; i <= end_zone; i++) { 2747 struct zone *zone = pgdat->node_zones + i; 2748 2749 lru_pages += zone_reclaimable_pages(zone); 2750 } 2751 2752 /* 2753 * Now scan the zone in the dma->highmem direction, stopping 2754 * at the last zone which needs scanning. 2755 * 2756 * We do this because the page allocator works in the opposite 2757 * direction. This prevents the page allocator from allocating 2758 * pages behind kswapd's direction of progress, which would 2759 * cause too much scanning of the lower zones. 2760 */ 2761 for (i = 0; i <= end_zone; i++) { 2762 struct zone *zone = pgdat->node_zones + i; 2763 int nr_slab, testorder; 2764 unsigned long balance_gap; 2765 2766 if (!populated_zone(zone)) 2767 continue; 2768 2769 if (zone->all_unreclaimable && 2770 sc.priority != DEF_PRIORITY) 2771 continue; 2772 2773 sc.nr_scanned = 0; 2774 2775 nr_soft_scanned = 0; 2776 /* 2777 * Call soft limit reclaim before calling shrink_zone. 2778 */ 2779 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone, 2780 order, sc.gfp_mask, 2781 &nr_soft_scanned); 2782 sc.nr_reclaimed += nr_soft_reclaimed; 2783 2784 /* 2785 * We put equal pressure on every zone, unless 2786 * one zone has way too many pages free 2787 * already. The "too many pages" is defined 2788 * as the high wmark plus a "gap" where the 2789 * gap is either the low watermark or 1% 2790 * of the zone, whichever is smaller. 2791 */ 2792 balance_gap = min(low_wmark_pages(zone), 2793 (zone->managed_pages + 2794 KSWAPD_ZONE_BALANCE_GAP_RATIO-1) / 2795 KSWAPD_ZONE_BALANCE_GAP_RATIO); 2796 /* 2797 * Kswapd reclaims only single pages with compaction 2798 * enabled. Trying too hard to reclaim until contiguous 2799 * free pages have become available can hurt performance 2800 * by evicting too much useful data from memory. 2801 * Do not reclaim more than needed for compaction. 2802 */ 2803 testorder = order; 2804 if (IS_ENABLED(CONFIG_COMPACTION) && order && 2805 compaction_suitable(zone, order) != 2806 COMPACT_SKIPPED) 2807 testorder = 0; 2808 2809 if ((buffer_heads_over_limit && is_highmem_idx(i)) || 2810 !zone_balanced(zone, testorder, 2811 balance_gap, end_zone)) { 2812 shrink_zone(zone, &sc); 2813 2814 reclaim_state->reclaimed_slab = 0; 2815 nr_slab = shrink_slab(&shrink, sc.nr_scanned, lru_pages); 2816 sc.nr_reclaimed += reclaim_state->reclaimed_slab; 2817 2818 if (nr_slab == 0 && !zone_reclaimable(zone)) 2819 zone->all_unreclaimable = 1; 2820 } 2821 2822 /* 2823 * If we're getting trouble reclaiming, start doing 2824 * writepage even in laptop mode. 2825 */ 2826 if (sc.priority < DEF_PRIORITY - 2) 2827 sc.may_writepage = 1; 2828 2829 if (zone->all_unreclaimable) { 2830 if (end_zone && end_zone == i) 2831 end_zone--; 2832 continue; 2833 } 2834 2835 if (zone_balanced(zone, testorder, 0, end_zone)) 2836 /* 2837 * If a zone reaches its high watermark, 2838 * consider it to be no longer congested. It's 2839 * possible there are dirty pages backed by 2840 * congested BDIs but as pressure is relieved, 2841 * speculatively avoid congestion waits 2842 */ 2843 zone_clear_flag(zone, ZONE_CONGESTED); 2844 } 2845 2846 /* 2847 * If the low watermark is met there is no need for processes 2848 * to be throttled on pfmemalloc_wait as they should not be 2849 * able to safely make forward progress. Wake them 2850 */ 2851 if (waitqueue_active(&pgdat->pfmemalloc_wait) && 2852 pfmemalloc_watermark_ok(pgdat)) 2853 wake_up(&pgdat->pfmemalloc_wait); 2854 2855 if (pgdat_balanced(pgdat, order, *classzone_idx)) { 2856 pgdat_is_balanced = true; 2857 break; /* kswapd: all done */ 2858 } 2859 2860 /* 2861 * We do this so kswapd doesn't build up large priorities for 2862 * example when it is freeing in parallel with allocators. It 2863 * matches the direct reclaim path behaviour in terms of impact 2864 * on zone->*_priority. 2865 */ 2866 if (sc.nr_reclaimed >= SWAP_CLUSTER_MAX) 2867 break; 2868 } while (--sc.priority >= 0); 2869 2870 out: 2871 if (!pgdat_is_balanced) { 2872 cond_resched(); 2873 2874 try_to_freeze(); 2875 2876 /* 2877 * Fragmentation may mean that the system cannot be 2878 * rebalanced for high-order allocations in all zones. 2879 * At this point, if nr_reclaimed < SWAP_CLUSTER_MAX, 2880 * it means the zones have been fully scanned and are still 2881 * not balanced. For high-order allocations, there is 2882 * little point trying all over again as kswapd may 2883 * infinite loop. 2884 * 2885 * Instead, recheck all watermarks at order-0 as they 2886 * are the most important. If watermarks are ok, kswapd will go 2887 * back to sleep. High-order users can still perform direct 2888 * reclaim if they wish. 2889 */ 2890 if (sc.nr_reclaimed < SWAP_CLUSTER_MAX) 2891 order = sc.order = 0; 2892 2893 goto loop_again; 2894 } 2895 2896 /* 2897 * If kswapd was reclaiming at a higher order, it has the option of 2898 * sleeping without all zones being balanced. Before it does, it must 2899 * ensure that the watermarks for order-0 on *all* zones are met and 2900 * that the congestion flags are cleared. The congestion flag must 2901 * be cleared as kswapd is the only mechanism that clears the flag 2902 * and it is potentially going to sleep here. 2903 */ 2904 if (order) { 2905 int zones_need_compaction = 1; 2906 2907 for (i = 0; i <= end_zone; i++) { 2908 struct zone *zone = pgdat->node_zones + i; 2909 2910 if (!populated_zone(zone)) 2911 continue; 2912 2913 /* Check if the memory needs to be defragmented. */ 2914 if (zone_watermark_ok(zone, order, 2915 low_wmark_pages(zone), *classzone_idx, 0)) 2916 zones_need_compaction = 0; 2917 } 2918 2919 if (zones_need_compaction) 2920 compact_pgdat(pgdat, order); 2921 } 2922 2923 /* 2924 * Return the order we were reclaiming at so prepare_kswapd_sleep() 2925 * makes a decision on the order we were last reclaiming at. However, 2926 * if another caller entered the allocator slow path while kswapd 2927 * was awake, order will remain at the higher level 2928 */ 2929 *classzone_idx = end_zone; 2930 return order; 2931 } 2932 2933 static void kswapd_try_to_sleep(pg_data_t *pgdat, int order, int classzone_idx) 2934 { 2935 long remaining = 0; 2936 DEFINE_WAIT(wait); 2937 2938 if (freezing(current) || kthread_should_stop()) 2939 return; 2940 2941 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE); 2942 2943 /* Try to sleep for a short interval */ 2944 if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) { 2945 remaining = schedule_timeout(HZ/10); 2946 finish_wait(&pgdat->kswapd_wait, &wait); 2947 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE); 2948 } 2949 2950 /* 2951 * After a short sleep, check if it was a premature sleep. If not, then 2952 * go fully to sleep until explicitly woken up. 2953 */ 2954 if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) { 2955 trace_mm_vmscan_kswapd_sleep(pgdat->node_id); 2956 2957 /* 2958 * vmstat counters are not perfectly accurate and the estimated 2959 * value for counters such as NR_FREE_PAGES can deviate from the 2960 * true value by nr_online_cpus * threshold. To avoid the zone 2961 * watermarks being breached while under pressure, we reduce the 2962 * per-cpu vmstat threshold while kswapd is awake and restore 2963 * them before going back to sleep. 2964 */ 2965 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold); 2966 2967 /* 2968 * Compaction records what page blocks it recently failed to 2969 * isolate pages from and skips them in the future scanning. 2970 * When kswapd is going to sleep, it is reasonable to assume 2971 * that pages and compaction may succeed so reset the cache. 2972 */ 2973 reset_isolation_suitable(pgdat); 2974 2975 if (!kthread_should_stop()) 2976 schedule(); 2977 2978 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold); 2979 } else { 2980 if (remaining) 2981 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY); 2982 else 2983 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY); 2984 } 2985 finish_wait(&pgdat->kswapd_wait, &wait); 2986 } 2987 2988 /* 2989 * The background pageout daemon, started as a kernel thread 2990 * from the init process. 2991 * 2992 * This basically trickles out pages so that we have _some_ 2993 * free memory available even if there is no other activity 2994 * that frees anything up. This is needed for things like routing 2995 * etc, where we otherwise might have all activity going on in 2996 * asynchronous contexts that cannot page things out. 2997 * 2998 * If there are applications that are active memory-allocators 2999 * (most normal use), this basically shouldn't matter. 3000 */ 3001 static int kswapd(void *p) 3002 { 3003 unsigned long order, new_order; 3004 unsigned balanced_order; 3005 int classzone_idx, new_classzone_idx; 3006 int balanced_classzone_idx; 3007 pg_data_t *pgdat = (pg_data_t*)p; 3008 struct task_struct *tsk = current; 3009 3010 struct reclaim_state reclaim_state = { 3011 .reclaimed_slab = 0, 3012 }; 3013 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id); 3014 3015 lockdep_set_current_reclaim_state(GFP_KERNEL); 3016 3017 if (!cpumask_empty(cpumask)) 3018 set_cpus_allowed_ptr(tsk, cpumask); 3019 current->reclaim_state = &reclaim_state; 3020 3021 /* 3022 * Tell the memory management that we're a "memory allocator", 3023 * and that if we need more memory we should get access to it 3024 * regardless (see "__alloc_pages()"). "kswapd" should 3025 * never get caught in the normal page freeing logic. 3026 * 3027 * (Kswapd normally doesn't need memory anyway, but sometimes 3028 * you need a small amount of memory in order to be able to 3029 * page out something else, and this flag essentially protects 3030 * us from recursively trying to free more memory as we're 3031 * trying to free the first piece of memory in the first place). 3032 */ 3033 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD; 3034 set_freezable(); 3035 3036 order = new_order = 0; 3037 balanced_order = 0; 3038 classzone_idx = new_classzone_idx = pgdat->nr_zones - 1; 3039 balanced_classzone_idx = classzone_idx; 3040 for ( ; ; ) { 3041 bool ret; 3042 3043 /* 3044 * If the last balance_pgdat was unsuccessful it's unlikely a 3045 * new request of a similar or harder type will succeed soon 3046 * so consider going to sleep on the basis we reclaimed at 3047 */ 3048 if (balanced_classzone_idx >= new_classzone_idx && 3049 balanced_order == new_order) { 3050 new_order = pgdat->kswapd_max_order; 3051 new_classzone_idx = pgdat->classzone_idx; 3052 pgdat->kswapd_max_order = 0; 3053 pgdat->classzone_idx = pgdat->nr_zones - 1; 3054 } 3055 3056 if (order < new_order || classzone_idx > new_classzone_idx) { 3057 /* 3058 * Don't sleep if someone wants a larger 'order' 3059 * allocation or has tigher zone constraints 3060 */ 3061 order = new_order; 3062 classzone_idx = new_classzone_idx; 3063 } else { 3064 kswapd_try_to_sleep(pgdat, balanced_order, 3065 balanced_classzone_idx); 3066 order = pgdat->kswapd_max_order; 3067 classzone_idx = pgdat->classzone_idx; 3068 new_order = order; 3069 new_classzone_idx = classzone_idx; 3070 pgdat->kswapd_max_order = 0; 3071 pgdat->classzone_idx = pgdat->nr_zones - 1; 3072 } 3073 3074 ret = try_to_freeze(); 3075 if (kthread_should_stop()) 3076 break; 3077 3078 /* 3079 * We can speed up thawing tasks if we don't call balance_pgdat 3080 * after returning from the refrigerator 3081 */ 3082 if (!ret) { 3083 trace_mm_vmscan_kswapd_wake(pgdat->node_id, order); 3084 balanced_classzone_idx = classzone_idx; 3085 balanced_order = balance_pgdat(pgdat, order, 3086 &balanced_classzone_idx); 3087 } 3088 } 3089 3090 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD); 3091 current->reclaim_state = NULL; 3092 lockdep_clear_current_reclaim_state(); 3093 3094 return 0; 3095 } 3096 3097 /* 3098 * A zone is low on free memory, so wake its kswapd task to service it. 3099 */ 3100 void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx) 3101 { 3102 pg_data_t *pgdat; 3103 3104 if (!populated_zone(zone)) 3105 return; 3106 3107 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL)) 3108 return; 3109 pgdat = zone->zone_pgdat; 3110 if (pgdat->kswapd_max_order < order) { 3111 pgdat->kswapd_max_order = order; 3112 pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx); 3113 } 3114 if (!waitqueue_active(&pgdat->kswapd_wait)) 3115 return; 3116 if (zone_watermark_ok_safe(zone, order, low_wmark_pages(zone), 0, 0)) 3117 return; 3118 3119 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order); 3120 wake_up_interruptible(&pgdat->kswapd_wait); 3121 } 3122 3123 #ifdef CONFIG_HIBERNATION 3124 /* 3125 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of 3126 * freed pages. 3127 * 3128 * Rather than trying to age LRUs the aim is to preserve the overall 3129 * LRU order by reclaiming preferentially 3130 * inactive > active > active referenced > active mapped 3131 */ 3132 unsigned long shrink_all_memory(unsigned long nr_to_reclaim) 3133 { 3134 struct reclaim_state reclaim_state; 3135 struct scan_control sc = { 3136 .gfp_mask = GFP_HIGHUSER_MOVABLE, 3137 .may_swap = 1, 3138 .may_unmap = 1, 3139 .may_writepage = 1, 3140 .nr_to_reclaim = nr_to_reclaim, 3141 .hibernation_mode = 1, 3142 .order = 0, 3143 .priority = DEF_PRIORITY, 3144 }; 3145 struct shrink_control shrink = { 3146 .gfp_mask = sc.gfp_mask, 3147 }; 3148 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask); 3149 struct task_struct *p = current; 3150 unsigned long nr_reclaimed; 3151 3152 p->flags |= PF_MEMALLOC; 3153 lockdep_set_current_reclaim_state(sc.gfp_mask); 3154 reclaim_state.reclaimed_slab = 0; 3155 p->reclaim_state = &reclaim_state; 3156 3157 nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink); 3158 3159 p->reclaim_state = NULL; 3160 lockdep_clear_current_reclaim_state(); 3161 p->flags &= ~PF_MEMALLOC; 3162 3163 return nr_reclaimed; 3164 } 3165 #endif /* CONFIG_HIBERNATION */ 3166 3167 /* It's optimal to keep kswapds on the same CPUs as their memory, but 3168 not required for correctness. So if the last cpu in a node goes 3169 away, we get changed to run anywhere: as the first one comes back, 3170 restore their cpu bindings. */ 3171 static int cpu_callback(struct notifier_block *nfb, unsigned long action, 3172 void *hcpu) 3173 { 3174 int nid; 3175 3176 if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) { 3177 for_each_node_state(nid, N_MEMORY) { 3178 pg_data_t *pgdat = NODE_DATA(nid); 3179 const struct cpumask *mask; 3180 3181 mask = cpumask_of_node(pgdat->node_id); 3182 3183 if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids) 3184 /* One of our CPUs online: restore mask */ 3185 set_cpus_allowed_ptr(pgdat->kswapd, mask); 3186 } 3187 } 3188 return NOTIFY_OK; 3189 } 3190 3191 /* 3192 * This kswapd start function will be called by init and node-hot-add. 3193 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added. 3194 */ 3195 int kswapd_run(int nid) 3196 { 3197 pg_data_t *pgdat = NODE_DATA(nid); 3198 int ret = 0; 3199 3200 if (pgdat->kswapd) 3201 return 0; 3202 3203 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid); 3204 if (IS_ERR(pgdat->kswapd)) { 3205 /* failure at boot is fatal */ 3206 BUG_ON(system_state == SYSTEM_BOOTING); 3207 pr_err("Failed to start kswapd on node %d\n", nid); 3208 ret = PTR_ERR(pgdat->kswapd); 3209 pgdat->kswapd = NULL; 3210 } 3211 return ret; 3212 } 3213 3214 /* 3215 * Called by memory hotplug when all memory in a node is offlined. Caller must 3216 * hold lock_memory_hotplug(). 3217 */ 3218 void kswapd_stop(int nid) 3219 { 3220 struct task_struct *kswapd = NODE_DATA(nid)->kswapd; 3221 3222 if (kswapd) { 3223 kthread_stop(kswapd); 3224 NODE_DATA(nid)->kswapd = NULL; 3225 } 3226 } 3227 3228 static int __init kswapd_init(void) 3229 { 3230 int nid; 3231 3232 swap_setup(); 3233 for_each_node_state(nid, N_MEMORY) 3234 kswapd_run(nid); 3235 hotcpu_notifier(cpu_callback, 0); 3236 return 0; 3237 } 3238 3239 module_init(kswapd_init) 3240 3241 #ifdef CONFIG_NUMA 3242 /* 3243 * Zone reclaim mode 3244 * 3245 * If non-zero call zone_reclaim when the number of free pages falls below 3246 * the watermarks. 3247 */ 3248 int zone_reclaim_mode __read_mostly; 3249 3250 #define RECLAIM_OFF 0 3251 #define RECLAIM_ZONE (1<<0) /* Run shrink_inactive_list on the zone */ 3252 #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */ 3253 #define RECLAIM_SWAP (1<<2) /* Swap pages out during reclaim */ 3254 3255 /* 3256 * Priority for ZONE_RECLAIM. This determines the fraction of pages 3257 * of a node considered for each zone_reclaim. 4 scans 1/16th of 3258 * a zone. 3259 */ 3260 #define ZONE_RECLAIM_PRIORITY 4 3261 3262 /* 3263 * Percentage of pages in a zone that must be unmapped for zone_reclaim to 3264 * occur. 3265 */ 3266 int sysctl_min_unmapped_ratio = 1; 3267 3268 /* 3269 * If the number of slab pages in a zone grows beyond this percentage then 3270 * slab reclaim needs to occur. 3271 */ 3272 int sysctl_min_slab_ratio = 5; 3273 3274 static inline unsigned long zone_unmapped_file_pages(struct zone *zone) 3275 { 3276 unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED); 3277 unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) + 3278 zone_page_state(zone, NR_ACTIVE_FILE); 3279 3280 /* 3281 * It's possible for there to be more file mapped pages than 3282 * accounted for by the pages on the file LRU lists because 3283 * tmpfs pages accounted for as ANON can also be FILE_MAPPED 3284 */ 3285 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0; 3286 } 3287 3288 /* Work out how many page cache pages we can reclaim in this reclaim_mode */ 3289 static long zone_pagecache_reclaimable(struct zone *zone) 3290 { 3291 long nr_pagecache_reclaimable; 3292 long delta = 0; 3293 3294 /* 3295 * If RECLAIM_SWAP is set, then all file pages are considered 3296 * potentially reclaimable. Otherwise, we have to worry about 3297 * pages like swapcache and zone_unmapped_file_pages() provides 3298 * a better estimate 3299 */ 3300 if (zone_reclaim_mode & RECLAIM_SWAP) 3301 nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES); 3302 else 3303 nr_pagecache_reclaimable = zone_unmapped_file_pages(zone); 3304 3305 /* If we can't clean pages, remove dirty pages from consideration */ 3306 if (!(zone_reclaim_mode & RECLAIM_WRITE)) 3307 delta += zone_page_state(zone, NR_FILE_DIRTY); 3308 3309 /* Watch for any possible underflows due to delta */ 3310 if (unlikely(delta > nr_pagecache_reclaimable)) 3311 delta = nr_pagecache_reclaimable; 3312 3313 return nr_pagecache_reclaimable - delta; 3314 } 3315 3316 /* 3317 * Try to free up some pages from this zone through reclaim. 3318 */ 3319 static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order) 3320 { 3321 /* Minimum pages needed in order to stay on node */ 3322 const unsigned long nr_pages = 1 << order; 3323 struct task_struct *p = current; 3324 struct reclaim_state reclaim_state; 3325 struct scan_control sc = { 3326 .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE), 3327 .may_unmap = !!(zone_reclaim_mode & RECLAIM_SWAP), 3328 .may_swap = 1, 3329 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX), 3330 .gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)), 3331 .order = order, 3332 .priority = ZONE_RECLAIM_PRIORITY, 3333 }; 3334 struct shrink_control shrink = { 3335 .gfp_mask = sc.gfp_mask, 3336 }; 3337 unsigned long nr_slab_pages0, nr_slab_pages1; 3338 3339 cond_resched(); 3340 /* 3341 * We need to be able to allocate from the reserves for RECLAIM_SWAP 3342 * and we also need to be able to write out pages for RECLAIM_WRITE 3343 * and RECLAIM_SWAP. 3344 */ 3345 p->flags |= PF_MEMALLOC | PF_SWAPWRITE; 3346 lockdep_set_current_reclaim_state(gfp_mask); 3347 reclaim_state.reclaimed_slab = 0; 3348 p->reclaim_state = &reclaim_state; 3349 3350 if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) { 3351 /* 3352 * Free memory by calling shrink zone with increasing 3353 * priorities until we have enough memory freed. 3354 */ 3355 do { 3356 shrink_zone(zone, &sc); 3357 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0); 3358 } 3359 3360 nr_slab_pages0 = zone_page_state(zone, NR_SLAB_RECLAIMABLE); 3361 if (nr_slab_pages0 > zone->min_slab_pages) { 3362 /* 3363 * shrink_slab() does not currently allow us to determine how 3364 * many pages were freed in this zone. So we take the current 3365 * number of slab pages and shake the slab until it is reduced 3366 * by the same nr_pages that we used for reclaiming unmapped 3367 * pages. 3368 * 3369 * Note that shrink_slab will free memory on all zones and may 3370 * take a long time. 3371 */ 3372 for (;;) { 3373 unsigned long lru_pages = zone_reclaimable_pages(zone); 3374 3375 /* No reclaimable slab or very low memory pressure */ 3376 if (!shrink_slab(&shrink, sc.nr_scanned, lru_pages)) 3377 break; 3378 3379 /* Freed enough memory */ 3380 nr_slab_pages1 = zone_page_state(zone, 3381 NR_SLAB_RECLAIMABLE); 3382 if (nr_slab_pages1 + nr_pages <= nr_slab_pages0) 3383 break; 3384 } 3385 3386 /* 3387 * Update nr_reclaimed by the number of slab pages we 3388 * reclaimed from this zone. 3389 */ 3390 nr_slab_pages1 = zone_page_state(zone, NR_SLAB_RECLAIMABLE); 3391 if (nr_slab_pages1 < nr_slab_pages0) 3392 sc.nr_reclaimed += nr_slab_pages0 - nr_slab_pages1; 3393 } 3394 3395 p->reclaim_state = NULL; 3396 current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE); 3397 lockdep_clear_current_reclaim_state(); 3398 return sc.nr_reclaimed >= nr_pages; 3399 } 3400 3401 int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order) 3402 { 3403 int node_id; 3404 int ret; 3405 3406 /* 3407 * Zone reclaim reclaims unmapped file backed pages and 3408 * slab pages if we are over the defined limits. 3409 * 3410 * A small portion of unmapped file backed pages is needed for 3411 * file I/O otherwise pages read by file I/O will be immediately 3412 * thrown out if the zone is overallocated. So we do not reclaim 3413 * if less than a specified percentage of the zone is used by 3414 * unmapped file backed pages. 3415 */ 3416 if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages && 3417 zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages) 3418 return ZONE_RECLAIM_FULL; 3419 3420 if (zone->all_unreclaimable) 3421 return ZONE_RECLAIM_FULL; 3422 3423 /* 3424 * Do not scan if the allocation should not be delayed. 3425 */ 3426 if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC)) 3427 return ZONE_RECLAIM_NOSCAN; 3428 3429 /* 3430 * Only run zone reclaim on the local zone or on zones that do not 3431 * have associated processors. This will favor the local processor 3432 * over remote processors and spread off node memory allocations 3433 * as wide as possible. 3434 */ 3435 node_id = zone_to_nid(zone); 3436 if (node_state(node_id, N_CPU) && node_id != numa_node_id()) 3437 return ZONE_RECLAIM_NOSCAN; 3438 3439 if (zone_test_and_set_flag(zone, ZONE_RECLAIM_LOCKED)) 3440 return ZONE_RECLAIM_NOSCAN; 3441 3442 ret = __zone_reclaim(zone, gfp_mask, order); 3443 zone_clear_flag(zone, ZONE_RECLAIM_LOCKED); 3444 3445 if (!ret) 3446 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED); 3447 3448 return ret; 3449 } 3450 #endif 3451 3452 /* 3453 * page_evictable - test whether a page is evictable 3454 * @page: the page to test 3455 * 3456 * Test whether page is evictable--i.e., should be placed on active/inactive 3457 * lists vs unevictable list. 3458 * 3459 * Reasons page might not be evictable: 3460 * (1) page's mapping marked unevictable 3461 * (2) page is part of an mlocked VMA 3462 * 3463 */ 3464 int page_evictable(struct page *page) 3465 { 3466 return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page); 3467 } 3468 3469 #ifdef CONFIG_SHMEM 3470 /** 3471 * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list 3472 * @pages: array of pages to check 3473 * @nr_pages: number of pages to check 3474 * 3475 * Checks pages for evictability and moves them to the appropriate lru list. 3476 * 3477 * This function is only used for SysV IPC SHM_UNLOCK. 3478 */ 3479 void check_move_unevictable_pages(struct page **pages, int nr_pages) 3480 { 3481 struct lruvec *lruvec; 3482 struct zone *zone = NULL; 3483 int pgscanned = 0; 3484 int pgrescued = 0; 3485 int i; 3486 3487 for (i = 0; i < nr_pages; i++) { 3488 struct page *page = pages[i]; 3489 struct zone *pagezone; 3490 3491 pgscanned++; 3492 pagezone = page_zone(page); 3493 if (pagezone != zone) { 3494 if (zone) 3495 spin_unlock_irq(&zone->lru_lock); 3496 zone = pagezone; 3497 spin_lock_irq(&zone->lru_lock); 3498 } 3499 lruvec = mem_cgroup_page_lruvec(page, zone); 3500 3501 if (!PageLRU(page) || !PageUnevictable(page)) 3502 continue; 3503 3504 if (page_evictable(page)) { 3505 enum lru_list lru = page_lru_base_type(page); 3506 3507 VM_BUG_ON(PageActive(page)); 3508 ClearPageUnevictable(page); 3509 del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE); 3510 add_page_to_lru_list(page, lruvec, lru); 3511 pgrescued++; 3512 } 3513 } 3514 3515 if (zone) { 3516 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued); 3517 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned); 3518 spin_unlock_irq(&zone->lru_lock); 3519 } 3520 } 3521 #endif /* CONFIG_SHMEM */ 3522 3523 static void warn_scan_unevictable_pages(void) 3524 { 3525 printk_once(KERN_WARNING 3526 "%s: The scan_unevictable_pages sysctl/node-interface has been " 3527 "disabled for lack of a legitimate use case. If you have " 3528 "one, please send an email to linux-mm@kvack.org.\n", 3529 current->comm); 3530 } 3531 3532 /* 3533 * scan_unevictable_pages [vm] sysctl handler. On demand re-scan of 3534 * all nodes' unevictable lists for evictable pages 3535 */ 3536 unsigned long scan_unevictable_pages; 3537 3538 int scan_unevictable_handler(struct ctl_table *table, int write, 3539 void __user *buffer, 3540 size_t *length, loff_t *ppos) 3541 { 3542 warn_scan_unevictable_pages(); 3543 proc_doulongvec_minmax(table, write, buffer, length, ppos); 3544 scan_unevictable_pages = 0; 3545 return 0; 3546 } 3547 3548 #ifdef CONFIG_NUMA 3549 /* 3550 * per node 'scan_unevictable_pages' attribute. On demand re-scan of 3551 * a specified node's per zone unevictable lists for evictable pages. 3552 */ 3553 3554 static ssize_t read_scan_unevictable_node(struct device *dev, 3555 struct device_attribute *attr, 3556 char *buf) 3557 { 3558 warn_scan_unevictable_pages(); 3559 return sprintf(buf, "\n"); /* always zero; should fit... */ 3560 } 3561 3562 static ssize_t write_scan_unevictable_node(struct device *dev, 3563 struct device_attribute *attr, 3564 const char *buf, size_t count) 3565 { 3566 warn_scan_unevictable_pages(); 3567 return 1; 3568 } 3569 3570 3571 static DEVICE_ATTR(scan_unevictable_pages, S_IRUGO | S_IWUSR, 3572 read_scan_unevictable_node, 3573 write_scan_unevictable_node); 3574 3575 int scan_unevictable_register_node(struct node *node) 3576 { 3577 return device_create_file(&node->dev, &dev_attr_scan_unevictable_pages); 3578 } 3579 3580 void scan_unevictable_unregister_node(struct node *node) 3581 { 3582 device_remove_file(&node->dev, &dev_attr_scan_unevictable_pages); 3583 } 3584 #endif 3585
Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.