4 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
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.
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/vmstat.h>
23 #include <linux/file.h>
24 #include <linux/writeback.h>
25 #include <linux/blkdev.h>
26 #include <linux/buffer_head.h> /* for try_to_release_page(),
27 buffer_heads_over_limit */
28 #include <linux/mm_inline.h>
29 #include <linux/pagevec.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/notifier.h>
36 #include <linux/rwsem.h>
37 #include <linux/delay.h>
38 #include <linux/kthread.h>
39 #include <linux/freezer.h>
40 #include <linux/memcontrol.h>
41 #include <linux/delayacct.h>
42 #include <linux/sysctl.h>
44 #include <asm/tlbflush.h>
45 #include <asm/div64.h>
47 #include <linux/swapops.h>
51 #define CREATE_TRACE_POINTS
52 #include <trace/events/vmscan.h>
61 /* Incremented by the number of inactive pages that were scanned */
62 unsigned long nr_scanned;
64 /* Number of pages freed so far during a call to shrink_zones() */
65 unsigned long nr_reclaimed;
67 /* How many pages shrink_list() should reclaim */
68 unsigned long nr_to_reclaim;
70 unsigned long hibernation_mode;
72 /* This context's GFP mask */
77 /* Can mapped pages be reclaimed? */
80 /* Can pages be swapped as part of reclaim? */
88 * Intend to reclaim enough continuous memory rather than reclaim
89 * enough amount of memory. i.e, mode for high order allocation.
91 enum lumpy_mode lumpy_reclaim_mode;
93 /* Which cgroup do we reclaim from */
94 struct mem_cgroup *mem_cgroup;
97 * Nodemask of nodes allowed by the caller. If NULL, all nodes
100 nodemask_t *nodemask;
103 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
105 #ifdef ARCH_HAS_PREFETCH
106 #define prefetch_prev_lru_page(_page, _base, _field) \
108 if ((_page)->lru.prev != _base) { \
111 prev = lru_to_page(&(_page->lru)); \
112 prefetch(&prev->_field); \
116 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
119 #ifdef ARCH_HAS_PREFETCHW
120 #define prefetchw_prev_lru_page(_page, _base, _field) \
122 if ((_page)->lru.prev != _base) { \
125 prev = lru_to_page(&(_page->lru)); \
126 prefetchw(&prev->_field); \
130 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
134 * From 0 .. 100. Higher means more swappy.
136 int vm_swappiness = 60;
137 long vm_total_pages; /* The total number of pages which the VM controls */
139 static LIST_HEAD(shrinker_list);
140 static DECLARE_RWSEM(shrinker_rwsem);
142 #ifdef CONFIG_CGROUP_MEM_RES_CTLR
143 #define scanning_global_lru(sc) (!(sc)->mem_cgroup)
145 #define scanning_global_lru(sc) (1)
148 static struct zone_reclaim_stat *get_reclaim_stat(struct zone *zone,
149 struct scan_control *sc)
151 if (!scanning_global_lru(sc))
152 return mem_cgroup_get_reclaim_stat(sc->mem_cgroup, zone);
154 return &zone->reclaim_stat;
157 static unsigned long zone_nr_lru_pages(struct zone *zone,
158 struct scan_control *sc, enum lru_list lru)
160 if (!scanning_global_lru(sc))
161 return mem_cgroup_zone_nr_pages(sc->mem_cgroup, zone, lru);
163 return zone_page_state(zone, NR_LRU_BASE + lru);
168 * Add a shrinker callback to be called from the vm
170 void register_shrinker(struct shrinker *shrinker)
173 down_write(&shrinker_rwsem);
174 list_add_tail(&shrinker->list, &shrinker_list);
175 up_write(&shrinker_rwsem);
177 EXPORT_SYMBOL(register_shrinker);
182 void unregister_shrinker(struct shrinker *shrinker)
184 down_write(&shrinker_rwsem);
185 list_del(&shrinker->list);
186 up_write(&shrinker_rwsem);
188 EXPORT_SYMBOL(unregister_shrinker);
190 #define SHRINK_BATCH 128
192 * Call the shrink functions to age shrinkable caches
194 * Here we assume it costs one seek to replace a lru page and that it also
195 * takes a seek to recreate a cache object. With this in mind we age equal
196 * percentages of the lru and ageable caches. This should balance the seeks
197 * generated by these structures.
199 * If the vm encountered mapped pages on the LRU it increase the pressure on
200 * slab to avoid swapping.
202 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
204 * `lru_pages' represents the number of on-LRU pages in all the zones which
205 * are eligible for the caller's allocation attempt. It is used for balancing
206 * slab reclaim versus page reclaim.
208 * Returns the number of slab objects which we shrunk.
210 unsigned long shrink_slab(unsigned long scanned, gfp_t gfp_mask,
211 unsigned long lru_pages)
213 struct shrinker *shrinker;
214 unsigned long ret = 0;
217 scanned = SWAP_CLUSTER_MAX;
219 if (!down_read_trylock(&shrinker_rwsem))
220 return 1; /* Assume we'll be able to shrink next time */
222 list_for_each_entry(shrinker, &shrinker_list, list) {
223 unsigned long long delta;
224 unsigned long total_scan;
225 unsigned long max_pass;
227 max_pass = (*shrinker->shrink)(shrinker, 0, gfp_mask);
228 delta = (4 * scanned) / shrinker->seeks;
230 do_div(delta, lru_pages + 1);
231 shrinker->nr += delta;
232 if (shrinker->nr < 0) {
233 printk(KERN_ERR "shrink_slab: %pF negative objects to "
235 shrinker->shrink, shrinker->nr);
236 shrinker->nr = max_pass;
240 * Avoid risking looping forever due to too large nr value:
241 * never try to free more than twice the estimate number of
244 if (shrinker->nr > max_pass * 2)
245 shrinker->nr = max_pass * 2;
247 total_scan = shrinker->nr;
250 while (total_scan >= SHRINK_BATCH) {
251 long this_scan = SHRINK_BATCH;
255 nr_before = (*shrinker->shrink)(shrinker, 0, gfp_mask);
256 shrink_ret = (*shrinker->shrink)(shrinker, this_scan,
258 if (shrink_ret == -1)
260 if (shrink_ret < nr_before)
261 ret += nr_before - shrink_ret;
262 count_vm_events(SLABS_SCANNED, this_scan);
263 total_scan -= this_scan;
268 shrinker->nr += total_scan;
270 up_read(&shrinker_rwsem);
274 static void set_lumpy_reclaim_mode(int priority, struct scan_control *sc,
277 enum lumpy_mode mode = sync ? LUMPY_MODE_SYNC : LUMPY_MODE_ASYNC;
280 * Some reclaim have alredy been failed. No worth to try synchronous
283 if (sync && sc->lumpy_reclaim_mode == LUMPY_MODE_NONE)
287 * If we need a large contiguous chunk of memory, or have
288 * trouble getting a small set of contiguous pages, we
289 * will reclaim both active and inactive pages.
291 if (sc->order > PAGE_ALLOC_COSTLY_ORDER)
292 sc->lumpy_reclaim_mode = mode;
293 else if (sc->order && priority < DEF_PRIORITY - 2)
294 sc->lumpy_reclaim_mode = mode;
296 sc->lumpy_reclaim_mode = LUMPY_MODE_NONE;
299 static void disable_lumpy_reclaim_mode(struct scan_control *sc)
301 sc->lumpy_reclaim_mode = LUMPY_MODE_NONE;
304 static inline int is_page_cache_freeable(struct page *page)
307 * A freeable page cache page is referenced only by the caller
308 * that isolated the page, the page cache radix tree and
309 * optional buffer heads at page->private.
311 return page_count(page) - page_has_private(page) == 2;
314 static int may_write_to_queue(struct backing_dev_info *bdi,
315 struct scan_control *sc)
317 if (current->flags & PF_SWAPWRITE)
319 if (!bdi_write_congested(bdi))
321 if (bdi == current->backing_dev_info)
324 /* lumpy reclaim for hugepage often need a lot of write */
325 if (sc->order > PAGE_ALLOC_COSTLY_ORDER)
331 * We detected a synchronous write error writing a page out. Probably
332 * -ENOSPC. We need to propagate that into the address_space for a subsequent
333 * fsync(), msync() or close().
335 * The tricky part is that after writepage we cannot touch the mapping: nothing
336 * prevents it from being freed up. But we have a ref on the page and once
337 * that page is locked, the mapping is pinned.
339 * We're allowed to run sleeping lock_page() here because we know the caller has
342 static void handle_write_error(struct address_space *mapping,
343 struct page *page, int error)
345 lock_page_nosync(page);
346 if (page_mapping(page) == mapping)
347 mapping_set_error(mapping, error);
351 /* possible outcome of pageout() */
353 /* failed to write page out, page is locked */
355 /* move page to the active list, page is locked */
357 /* page has been sent to the disk successfully, page is unlocked */
359 /* page is clean and locked */
364 * pageout is called by shrink_page_list() for each dirty page.
365 * Calls ->writepage().
367 static pageout_t pageout(struct page *page, struct address_space *mapping,
368 struct scan_control *sc)
371 * If the page is dirty, only perform writeback if that write
372 * will be non-blocking. To prevent this allocation from being
373 * stalled by pagecache activity. But note that there may be
374 * stalls if we need to run get_block(). We could test
375 * PagePrivate for that.
377 * If this process is currently in __generic_file_aio_write() against
378 * this page's queue, we can perform writeback even if that
381 * If the page is swapcache, write it back even if that would
382 * block, for some throttling. This happens by accident, because
383 * swap_backing_dev_info is bust: it doesn't reflect the
384 * congestion state of the swapdevs. Easy to fix, if needed.
386 if (!is_page_cache_freeable(page))
390 * Some data journaling orphaned pages can have
391 * page->mapping == NULL while being dirty with clean buffers.
393 if (page_has_private(page)) {
394 if (try_to_free_buffers(page)) {
395 ClearPageDirty(page);
396 printk("%s: orphaned page\n", __func__);
402 if (mapping->a_ops->writepage == NULL)
403 return PAGE_ACTIVATE;
404 if (!may_write_to_queue(mapping->backing_dev_info, sc))
407 if (clear_page_dirty_for_io(page)) {
409 struct writeback_control wbc = {
410 .sync_mode = WB_SYNC_NONE,
411 .nr_to_write = SWAP_CLUSTER_MAX,
413 .range_end = LLONG_MAX,
417 SetPageReclaim(page);
418 res = mapping->a_ops->writepage(page, &wbc);
420 handle_write_error(mapping, page, res);
421 if (res == AOP_WRITEPAGE_ACTIVATE) {
422 ClearPageReclaim(page);
423 return PAGE_ACTIVATE;
427 * Wait on writeback if requested to. This happens when
428 * direct reclaiming a large contiguous area and the
429 * first attempt to free a range of pages fails.
431 if (PageWriteback(page) &&
432 sc->lumpy_reclaim_mode == LUMPY_MODE_SYNC)
433 wait_on_page_writeback(page);
435 if (!PageWriteback(page)) {
436 /* synchronous write or broken a_ops? */
437 ClearPageReclaim(page);
439 trace_mm_vmscan_writepage(page,
440 trace_reclaim_flags(page, sc->lumpy_reclaim_mode));
441 inc_zone_page_state(page, NR_VMSCAN_WRITE);
449 * Same as remove_mapping, but if the page is removed from the mapping, it
450 * gets returned with a refcount of 0.
452 static int __remove_mapping(struct address_space *mapping, struct page *page)
454 BUG_ON(!PageLocked(page));
455 BUG_ON(mapping != page_mapping(page));
457 spin_lock_irq(&mapping->tree_lock);
459 * The non racy check for a busy page.
461 * Must be careful with the order of the tests. When someone has
462 * a ref to the page, it may be possible that they dirty it then
463 * drop the reference. So if PageDirty is tested before page_count
464 * here, then the following race may occur:
466 * get_user_pages(&page);
467 * [user mapping goes away]
469 * !PageDirty(page) [good]
470 * SetPageDirty(page);
472 * !page_count(page) [good, discard it]
474 * [oops, our write_to data is lost]
476 * Reversing the order of the tests ensures such a situation cannot
477 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
478 * load is not satisfied before that of page->_count.
480 * Note that if SetPageDirty is always performed via set_page_dirty,
481 * and thus under tree_lock, then this ordering is not required.
483 if (!page_freeze_refs(page, 2))
485 /* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
486 if (unlikely(PageDirty(page))) {
487 page_unfreeze_refs(page, 2);
491 if (PageSwapCache(page)) {
492 swp_entry_t swap = { .val = page_private(page) };
493 __delete_from_swap_cache(page);
494 spin_unlock_irq(&mapping->tree_lock);
495 swapcache_free(swap, page);
497 void (*freepage)(struct page *);
499 freepage = mapping->a_ops->freepage;
501 __remove_from_page_cache(page);
502 spin_unlock_irq(&mapping->tree_lock);
503 mem_cgroup_uncharge_cache_page(page);
505 if (freepage != NULL)
512 spin_unlock_irq(&mapping->tree_lock);
517 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
518 * someone else has a ref on the page, abort and return 0. If it was
519 * successfully detached, return 1. Assumes the caller has a single ref on
522 int remove_mapping(struct address_space *mapping, struct page *page)
524 if (__remove_mapping(mapping, page)) {
526 * Unfreezing the refcount with 1 rather than 2 effectively
527 * drops the pagecache ref for us without requiring another
530 page_unfreeze_refs(page, 1);
537 * putback_lru_page - put previously isolated page onto appropriate LRU list
538 * @page: page to be put back to appropriate lru list
540 * Add previously isolated @page to appropriate LRU list.
541 * Page may still be unevictable for other reasons.
543 * lru_lock must not be held, interrupts must be enabled.
545 void putback_lru_page(struct page *page)
548 int active = !!TestClearPageActive(page);
549 int was_unevictable = PageUnevictable(page);
551 VM_BUG_ON(PageLRU(page));
554 ClearPageUnevictable(page);
556 if (page_evictable(page, NULL)) {
558 * For evictable pages, we can use the cache.
559 * In event of a race, worst case is we end up with an
560 * unevictable page on [in]active list.
561 * We know how to handle that.
563 lru = active + page_lru_base_type(page);
564 lru_cache_add_lru(page, lru);
567 * Put unevictable pages directly on zone's unevictable
570 lru = LRU_UNEVICTABLE;
571 add_page_to_unevictable_list(page);
573 * When racing with an mlock clearing (page is
574 * unlocked), make sure that if the other thread does
575 * not observe our setting of PG_lru and fails
576 * isolation, we see PG_mlocked cleared below and move
577 * the page back to the evictable list.
579 * The other side is TestClearPageMlocked().
585 * page's status can change while we move it among lru. If an evictable
586 * page is on unevictable list, it never be freed. To avoid that,
587 * check after we added it to the list, again.
589 if (lru == LRU_UNEVICTABLE && page_evictable(page, NULL)) {
590 if (!isolate_lru_page(page)) {
594 /* This means someone else dropped this page from LRU
595 * So, it will be freed or putback to LRU again. There is
596 * nothing to do here.
600 if (was_unevictable && lru != LRU_UNEVICTABLE)
601 count_vm_event(UNEVICTABLE_PGRESCUED);
602 else if (!was_unevictable && lru == LRU_UNEVICTABLE)
603 count_vm_event(UNEVICTABLE_PGCULLED);
605 put_page(page); /* drop ref from isolate */
608 enum page_references {
610 PAGEREF_RECLAIM_CLEAN,
615 static enum page_references page_check_references(struct page *page,
616 struct scan_control *sc)
618 int referenced_ptes, referenced_page;
619 unsigned long vm_flags;
621 referenced_ptes = page_referenced(page, 1, sc->mem_cgroup, &vm_flags);
622 referenced_page = TestClearPageReferenced(page);
624 /* Lumpy reclaim - ignore references */
625 if (sc->lumpy_reclaim_mode != LUMPY_MODE_NONE)
626 return PAGEREF_RECLAIM;
629 * Mlock lost the isolation race with us. Let try_to_unmap()
630 * move the page to the unevictable list.
632 if (vm_flags & VM_LOCKED)
633 return PAGEREF_RECLAIM;
635 if (referenced_ptes) {
637 return PAGEREF_ACTIVATE;
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
644 * Mark it and spare it for another trip around the
645 * inactive list. Another page table reference will
646 * lead to its activation.
648 * Note: the mark is set for activated pages as well
649 * so that recently deactivated but used pages are
652 SetPageReferenced(page);
655 return PAGEREF_ACTIVATE;
660 /* Reclaim if clean, defer dirty pages to writeback */
661 if (referenced_page && !PageSwapBacked(page))
662 return PAGEREF_RECLAIM_CLEAN;
664 return PAGEREF_RECLAIM;
667 static noinline_for_stack void free_page_list(struct list_head *free_pages)
669 struct pagevec freed_pvec;
670 struct page *page, *tmp;
672 pagevec_init(&freed_pvec, 1);
674 list_for_each_entry_safe(page, tmp, free_pages, lru) {
675 list_del(&page->lru);
676 if (!pagevec_add(&freed_pvec, page)) {
677 __pagevec_free(&freed_pvec);
678 pagevec_reinit(&freed_pvec);
682 pagevec_free(&freed_pvec);
686 * shrink_page_list() returns the number of reclaimed pages
688 static unsigned long shrink_page_list(struct list_head *page_list,
690 struct scan_control *sc)
692 LIST_HEAD(ret_pages);
693 LIST_HEAD(free_pages);
695 unsigned long nr_dirty = 0;
696 unsigned long nr_congested = 0;
697 unsigned long nr_reclaimed = 0;
701 while (!list_empty(page_list)) {
702 enum page_references references;
703 struct address_space *mapping;
709 page = lru_to_page(page_list);
710 list_del(&page->lru);
712 if (!trylock_page(page))
715 VM_BUG_ON(PageActive(page));
716 VM_BUG_ON(page_zone(page) != zone);
720 if (unlikely(!page_evictable(page, NULL)))
723 if (!sc->may_unmap && page_mapped(page))
726 /* Double the slab pressure for mapped and swapcache pages */
727 if (page_mapped(page) || PageSwapCache(page))
730 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
731 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
733 if (PageWriteback(page)) {
735 * Synchronous reclaim is performed in two passes,
736 * first an asynchronous pass over the list to
737 * start parallel writeback, and a second synchronous
738 * pass to wait for the IO to complete. Wait here
739 * for any page for which writeback has already
742 if (sc->lumpy_reclaim_mode == LUMPY_MODE_SYNC &&
744 wait_on_page_writeback(page);
751 references = page_check_references(page, sc);
752 switch (references) {
753 case PAGEREF_ACTIVATE:
754 goto activate_locked;
757 case PAGEREF_RECLAIM:
758 case PAGEREF_RECLAIM_CLEAN:
759 ; /* try to reclaim the page below */
763 * Anonymous process memory has backing store?
764 * Try to allocate it some swap space here.
766 if (PageAnon(page) && !PageSwapCache(page)) {
767 if (!(sc->gfp_mask & __GFP_IO))
769 if (!add_to_swap(page))
770 goto activate_locked;
774 mapping = page_mapping(page);
777 * The page is mapped into the page tables of one or more
778 * processes. Try to unmap it here.
780 if (page_mapped(page) && mapping) {
781 switch (try_to_unmap(page, TTU_UNMAP)) {
783 goto activate_locked;
789 ; /* try to free the page below */
793 if (PageDirty(page)) {
796 if (references == PAGEREF_RECLAIM_CLEAN)
800 if (!sc->may_writepage)
803 /* Page is dirty, try to write it out here */
804 switch (pageout(page, mapping, sc)) {
809 goto activate_locked;
811 if (PageWriteback(page))
817 * A synchronous write - probably a ramdisk. Go
818 * ahead and try to reclaim the page.
820 if (!trylock_page(page))
822 if (PageDirty(page) || PageWriteback(page))
824 mapping = page_mapping(page);
826 ; /* try to free the page below */
831 * If the page has buffers, try to free the buffer mappings
832 * associated with this page. If we succeed we try to free
835 * We do this even if the page is PageDirty().
836 * try_to_release_page() does not perform I/O, but it is
837 * possible for a page to have PageDirty set, but it is actually
838 * clean (all its buffers are clean). This happens if the
839 * buffers were written out directly, with submit_bh(). ext3
840 * will do this, as well as the blockdev mapping.
841 * try_to_release_page() will discover that cleanness and will
842 * drop the buffers and mark the page clean - it can be freed.
844 * Rarely, pages can have buffers and no ->mapping. These are
845 * the pages which were not successfully invalidated in
846 * truncate_complete_page(). We try to drop those buffers here
847 * and if that worked, and the page is no longer mapped into
848 * process address space (page_count == 1) it can be freed.
849 * Otherwise, leave the page on the LRU so it is swappable.
851 if (page_has_private(page)) {
852 if (!try_to_release_page(page, sc->gfp_mask))
853 goto activate_locked;
854 if (!mapping && page_count(page) == 1) {
856 if (put_page_testzero(page))
860 * rare race with speculative reference.
861 * the speculative reference will free
862 * this page shortly, so we may
863 * increment nr_reclaimed here (and
864 * leave it off the LRU).
872 if (!mapping || !__remove_mapping(mapping, page))
876 * At this point, we have no other references and there is
877 * no way to pick any more up (removed from LRU, removed
878 * from pagecache). Can use non-atomic bitops now (and
879 * we obviously don't have to worry about waking up a process
880 * waiting on the page lock, because there are no references.
882 __clear_page_locked(page);
887 * Is there need to periodically free_page_list? It would
888 * appear not as the counts should be low
890 list_add(&page->lru, &free_pages);
894 if (PageSwapCache(page))
895 try_to_free_swap(page);
897 putback_lru_page(page);
898 disable_lumpy_reclaim_mode(sc);
902 /* Not a candidate for swapping, so reclaim swap space. */
903 if (PageSwapCache(page) && vm_swap_full())
904 try_to_free_swap(page);
905 VM_BUG_ON(PageActive(page));
911 disable_lumpy_reclaim_mode(sc);
913 list_add(&page->lru, &ret_pages);
914 VM_BUG_ON(PageLRU(page) || PageUnevictable(page));
918 * Tag a zone as congested if all the dirty pages encountered were
919 * backed by a congested BDI. In this case, reclaimers should just
920 * back off and wait for congestion to clear because further reclaim
921 * will encounter the same problem
923 if (nr_dirty == nr_congested && nr_dirty != 0)
924 zone_set_flag(zone, ZONE_CONGESTED);
926 free_page_list(&free_pages);
928 list_splice(&ret_pages, page_list);
929 count_vm_events(PGACTIVATE, pgactivate);
934 * Attempt to remove the specified page from its LRU. Only take this page
935 * if it is of the appropriate PageActive status. Pages which are being
936 * freed elsewhere are also ignored.
938 * page: page to consider
939 * mode: one of the LRU isolation modes defined above
941 * returns 0 on success, -ve errno on failure.
943 int __isolate_lru_page(struct page *page, int mode, int file)
947 /* Only take pages on the LRU. */
952 * When checking the active state, we need to be sure we are
953 * dealing with comparible boolean values. Take the logical not
956 if (mode != ISOLATE_BOTH && (!PageActive(page) != !mode))
959 if (mode != ISOLATE_BOTH && page_is_file_cache(page) != file)
963 * When this function is being called for lumpy reclaim, we
964 * initially look into all LRU pages, active, inactive and
965 * unevictable; only give shrink_page_list evictable pages.
967 if (PageUnevictable(page))
972 if (likely(get_page_unless_zero(page))) {
974 * Be careful not to clear PageLRU until after we're
975 * sure the page is not being freed elsewhere -- the
976 * page release code relies on it.
986 * zone->lru_lock is heavily contended. Some of the functions that
987 * shrink the lists perform better by taking out a batch of pages
988 * and working on them outside the LRU lock.
990 * For pagecache intensive workloads, this function is the hottest
991 * spot in the kernel (apart from copy_*_user functions).
993 * Appropriate locks must be held before calling this function.
995 * @nr_to_scan: The number of pages to look through on the list.
996 * @src: The LRU list to pull pages off.
997 * @dst: The temp list to put pages on to.
998 * @scanned: The number of pages that were scanned.
999 * @order: The caller's attempted allocation order
1000 * @mode: One of the LRU isolation modes
1001 * @file: True [1] if isolating file [!anon] pages
1003 * returns how many pages were moved onto *@dst.
1005 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
1006 struct list_head *src, struct list_head *dst,
1007 unsigned long *scanned, int order, int mode, int file)
1009 unsigned long nr_taken = 0;
1010 unsigned long nr_lumpy_taken = 0;
1011 unsigned long nr_lumpy_dirty = 0;
1012 unsigned long nr_lumpy_failed = 0;
1015 for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
1018 unsigned long end_pfn;
1019 unsigned long page_pfn;
1022 page = lru_to_page(src);
1023 prefetchw_prev_lru_page(page, src, flags);
1025 VM_BUG_ON(!PageLRU(page));
1027 switch (__isolate_lru_page(page, mode, file)) {
1029 list_move(&page->lru, dst);
1030 mem_cgroup_del_lru(page);
1035 /* else it is being freed elsewhere */
1036 list_move(&page->lru, src);
1037 mem_cgroup_rotate_lru_list(page, page_lru(page));
1048 * Attempt to take all pages in the order aligned region
1049 * surrounding the tag page. Only take those pages of
1050 * the same active state as that tag page. We may safely
1051 * round the target page pfn down to the requested order
1052 * as the mem_map is guarenteed valid out to MAX_ORDER,
1053 * where that page is in a different zone we will detect
1054 * it from its zone id and abort this block scan.
1056 zone_id = page_zone_id(page);
1057 page_pfn = page_to_pfn(page);
1058 pfn = page_pfn & ~((1 << order) - 1);
1059 end_pfn = pfn + (1 << order);
1060 for (; pfn < end_pfn; pfn++) {
1061 struct page *cursor_page;
1063 /* The target page is in the block, ignore it. */
1064 if (unlikely(pfn == page_pfn))
1067 /* Avoid holes within the zone. */
1068 if (unlikely(!pfn_valid_within(pfn)))
1071 cursor_page = pfn_to_page(pfn);
1073 /* Check that we have not crossed a zone boundary. */
1074 if (unlikely(page_zone_id(cursor_page) != zone_id))
1078 * If we don't have enough swap space, reclaiming of
1079 * anon page which don't already have a swap slot is
1082 if (nr_swap_pages <= 0 && PageAnon(cursor_page) &&
1083 !PageSwapCache(cursor_page))
1086 if (__isolate_lru_page(cursor_page, mode, file) == 0) {
1087 list_move(&cursor_page->lru, dst);
1088 mem_cgroup_del_lru(cursor_page);
1091 if (PageDirty(cursor_page))
1095 /* the page is freed already. */
1096 if (!page_count(cursor_page))
1102 /* If we break out of the loop above, lumpy reclaim failed */
1109 trace_mm_vmscan_lru_isolate(order,
1112 nr_lumpy_taken, nr_lumpy_dirty, nr_lumpy_failed,
1117 static unsigned long isolate_pages_global(unsigned long nr,
1118 struct list_head *dst,
1119 unsigned long *scanned, int order,
1120 int mode, struct zone *z,
1121 int active, int file)
1128 return isolate_lru_pages(nr, &z->lru[lru].list, dst, scanned, order,
1133 * clear_active_flags() is a helper for shrink_active_list(), clearing
1134 * any active bits from the pages in the list.
1136 static unsigned long clear_active_flags(struct list_head *page_list,
1137 unsigned int *count)
1143 list_for_each_entry(page, page_list, lru) {
1144 lru = page_lru_base_type(page);
1145 if (PageActive(page)) {
1147 ClearPageActive(page);
1158 * isolate_lru_page - tries to isolate a page from its LRU list
1159 * @page: page to isolate from its LRU list
1161 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
1162 * vmstat statistic corresponding to whatever LRU list the page was on.
1164 * Returns 0 if the page was removed from an LRU list.
1165 * Returns -EBUSY if the page was not on an LRU list.
1167 * The returned page will have PageLRU() cleared. If it was found on
1168 * the active list, it will have PageActive set. If it was found on
1169 * the unevictable list, it will have the PageUnevictable bit set. That flag
1170 * may need to be cleared by the caller before letting the page go.
1172 * The vmstat statistic corresponding to the list on which the page was
1173 * found will be decremented.
1176 * (1) Must be called with an elevated refcount on the page. This is a
1177 * fundamentnal difference from isolate_lru_pages (which is called
1178 * without a stable reference).
1179 * (2) the lru_lock must not be held.
1180 * (3) interrupts must be enabled.
1182 int isolate_lru_page(struct page *page)
1186 if (PageLRU(page)) {
1187 struct zone *zone = page_zone(page);
1189 spin_lock_irq(&zone->lru_lock);
1190 if (PageLRU(page) && get_page_unless_zero(page)) {
1191 int lru = page_lru(page);
1195 del_page_from_lru_list(zone, page, lru);
1197 spin_unlock_irq(&zone->lru_lock);
1203 * Are there way too many processes in the direct reclaim path already?
1205 static int too_many_isolated(struct zone *zone, int file,
1206 struct scan_control *sc)
1208 unsigned long inactive, isolated;
1210 if (current_is_kswapd())
1213 if (!scanning_global_lru(sc))
1217 inactive = zone_page_state(zone, NR_INACTIVE_FILE);
1218 isolated = zone_page_state(zone, NR_ISOLATED_FILE);
1220 inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1221 isolated = zone_page_state(zone, NR_ISOLATED_ANON);
1224 return isolated > inactive;
1228 * TODO: Try merging with migrations version of putback_lru_pages
1230 static noinline_for_stack void
1231 putback_lru_pages(struct zone *zone, struct scan_control *sc,
1232 unsigned long nr_anon, unsigned long nr_file,
1233 struct list_head *page_list)
1236 struct pagevec pvec;
1237 struct zone_reclaim_stat *reclaim_stat = get_reclaim_stat(zone, sc);
1239 pagevec_init(&pvec, 1);
1242 * Put back any unfreeable pages.
1244 spin_lock(&zone->lru_lock);
1245 while (!list_empty(page_list)) {
1247 page = lru_to_page(page_list);
1248 VM_BUG_ON(PageLRU(page));
1249 list_del(&page->lru);
1250 if (unlikely(!page_evictable(page, NULL))) {
1251 spin_unlock_irq(&zone->lru_lock);
1252 putback_lru_page(page);
1253 spin_lock_irq(&zone->lru_lock);
1257 lru = page_lru(page);
1258 add_page_to_lru_list(zone, page, lru);
1259 if (is_active_lru(lru)) {
1260 int file = is_file_lru(lru);
1261 reclaim_stat->recent_rotated[file]++;
1263 if (!pagevec_add(&pvec, page)) {
1264 spin_unlock_irq(&zone->lru_lock);
1265 __pagevec_release(&pvec);
1266 spin_lock_irq(&zone->lru_lock);
1269 __mod_zone_page_state(zone, NR_ISOLATED_ANON, -nr_anon);
1270 __mod_zone_page_state(zone, NR_ISOLATED_FILE, -nr_file);
1272 spin_unlock_irq(&zone->lru_lock);
1273 pagevec_release(&pvec);
1276 static noinline_for_stack void update_isolated_counts(struct zone *zone,
1277 struct scan_control *sc,
1278 unsigned long *nr_anon,
1279 unsigned long *nr_file,
1280 struct list_head *isolated_list)
1282 unsigned long nr_active;
1283 unsigned int count[NR_LRU_LISTS] = { 0, };
1284 struct zone_reclaim_stat *reclaim_stat = get_reclaim_stat(zone, sc);
1286 nr_active = clear_active_flags(isolated_list, count);
1287 __count_vm_events(PGDEACTIVATE, nr_active);
1289 __mod_zone_page_state(zone, NR_ACTIVE_FILE,
1290 -count[LRU_ACTIVE_FILE]);
1291 __mod_zone_page_state(zone, NR_INACTIVE_FILE,
1292 -count[LRU_INACTIVE_FILE]);
1293 __mod_zone_page_state(zone, NR_ACTIVE_ANON,
1294 -count[LRU_ACTIVE_ANON]);
1295 __mod_zone_page_state(zone, NR_INACTIVE_ANON,
1296 -count[LRU_INACTIVE_ANON]);
1298 *nr_anon = count[LRU_ACTIVE_ANON] + count[LRU_INACTIVE_ANON];
1299 *nr_file = count[LRU_ACTIVE_FILE] + count[LRU_INACTIVE_FILE];
1300 __mod_zone_page_state(zone, NR_ISOLATED_ANON, *nr_anon);
1301 __mod_zone_page_state(zone, NR_ISOLATED_FILE, *nr_file);
1303 reclaim_stat->recent_scanned[0] += *nr_anon;
1304 reclaim_stat->recent_scanned[1] += *nr_file;
1308 * Returns true if the caller should wait to clean dirty/writeback pages.
1310 * If we are direct reclaiming for contiguous pages and we do not reclaim
1311 * everything in the list, try again and wait for writeback IO to complete.
1312 * This will stall high-order allocations noticeably. Only do that when really
1313 * need to free the pages under high memory pressure.
1315 static inline bool should_reclaim_stall(unsigned long nr_taken,
1316 unsigned long nr_freed,
1318 struct scan_control *sc)
1320 int lumpy_stall_priority;
1322 /* kswapd should not stall on sync IO */
1323 if (current_is_kswapd())
1326 /* Only stall on lumpy reclaim */
1327 if (sc->lumpy_reclaim_mode == LUMPY_MODE_NONE)
1330 /* If we have relaimed everything on the isolated list, no stall */
1331 if (nr_freed == nr_taken)
1335 * For high-order allocations, there are two stall thresholds.
1336 * High-cost allocations stall immediately where as lower
1337 * order allocations such as stacks require the scanning
1338 * priority to be much higher before stalling.
1340 if (sc->order > PAGE_ALLOC_COSTLY_ORDER)
1341 lumpy_stall_priority = DEF_PRIORITY;
1343 lumpy_stall_priority = DEF_PRIORITY / 3;
1345 return priority <= lumpy_stall_priority;
1349 * shrink_inactive_list() is a helper for shrink_zone(). It returns the number
1350 * of reclaimed pages
1352 static noinline_for_stack unsigned long
1353 shrink_inactive_list(unsigned long nr_to_scan, struct zone *zone,
1354 struct scan_control *sc, int priority, int file)
1356 LIST_HEAD(page_list);
1357 unsigned long nr_scanned;
1358 unsigned long nr_reclaimed = 0;
1359 unsigned long nr_taken;
1360 unsigned long nr_anon;
1361 unsigned long nr_file;
1363 while (unlikely(too_many_isolated(zone, file, sc))) {
1364 congestion_wait(BLK_RW_ASYNC, HZ/10);
1366 /* We are about to die and free our memory. Return now. */
1367 if (fatal_signal_pending(current))
1368 return SWAP_CLUSTER_MAX;
1371 set_lumpy_reclaim_mode(priority, sc, false);
1373 spin_lock_irq(&zone->lru_lock);
1375 if (scanning_global_lru(sc)) {
1376 nr_taken = isolate_pages_global(nr_to_scan,
1377 &page_list, &nr_scanned, sc->order,
1378 sc->lumpy_reclaim_mode == LUMPY_MODE_NONE ?
1379 ISOLATE_INACTIVE : ISOLATE_BOTH,
1381 zone->pages_scanned += nr_scanned;
1382 if (current_is_kswapd())
1383 __count_zone_vm_events(PGSCAN_KSWAPD, zone,
1386 __count_zone_vm_events(PGSCAN_DIRECT, zone,
1389 nr_taken = mem_cgroup_isolate_pages(nr_to_scan,
1390 &page_list, &nr_scanned, sc->order,
1391 sc->lumpy_reclaim_mode == LUMPY_MODE_NONE ?
1392 ISOLATE_INACTIVE : ISOLATE_BOTH,
1393 zone, sc->mem_cgroup,
1396 * mem_cgroup_isolate_pages() keeps track of
1397 * scanned pages on its own.
1401 if (nr_taken == 0) {
1402 spin_unlock_irq(&zone->lru_lock);
1406 update_isolated_counts(zone, sc, &nr_anon, &nr_file, &page_list);
1408 spin_unlock_irq(&zone->lru_lock);
1410 nr_reclaimed = shrink_page_list(&page_list, zone, sc);
1412 /* Check if we should syncronously wait for writeback */
1413 if (should_reclaim_stall(nr_taken, nr_reclaimed, priority, sc)) {
1414 set_lumpy_reclaim_mode(priority, sc, true);
1415 nr_reclaimed += shrink_page_list(&page_list, zone, sc);
1418 local_irq_disable();
1419 if (current_is_kswapd())
1420 __count_vm_events(KSWAPD_STEAL, nr_reclaimed);
1421 __count_zone_vm_events(PGSTEAL, zone, nr_reclaimed);
1423 putback_lru_pages(zone, sc, nr_anon, nr_file, &page_list);
1425 trace_mm_vmscan_lru_shrink_inactive(zone->zone_pgdat->node_id,
1427 nr_scanned, nr_reclaimed,
1429 trace_shrink_flags(file, sc->lumpy_reclaim_mode));
1430 return nr_reclaimed;
1434 * This moves pages from the active list to the inactive list.
1436 * We move them the other way if the page is referenced by one or more
1437 * processes, from rmap.
1439 * If the pages are mostly unmapped, the processing is fast and it is
1440 * appropriate to hold zone->lru_lock across the whole operation. But if
1441 * the pages are mapped, the processing is slow (page_referenced()) so we
1442 * should drop zone->lru_lock around each page. It's impossible to balance
1443 * this, so instead we remove the pages from the LRU while processing them.
1444 * It is safe to rely on PG_active against the non-LRU pages in here because
1445 * nobody will play with that bit on a non-LRU page.
1447 * The downside is that we have to touch page->_count against each page.
1448 * But we had to alter page->flags anyway.
1451 static void move_active_pages_to_lru(struct zone *zone,
1452 struct list_head *list,
1455 unsigned long pgmoved = 0;
1456 struct pagevec pvec;
1459 pagevec_init(&pvec, 1);
1461 while (!list_empty(list)) {
1462 page = lru_to_page(list);
1464 VM_BUG_ON(PageLRU(page));
1467 list_move(&page->lru, &zone->lru[lru].list);
1468 mem_cgroup_add_lru_list(page, lru);
1471 if (!pagevec_add(&pvec, page) || list_empty(list)) {
1472 spin_unlock_irq(&zone->lru_lock);
1473 if (buffer_heads_over_limit)
1474 pagevec_strip(&pvec);
1475 __pagevec_release(&pvec);
1476 spin_lock_irq(&zone->lru_lock);
1479 __mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved);
1480 if (!is_active_lru(lru))
1481 __count_vm_events(PGDEACTIVATE, pgmoved);
1484 static void shrink_active_list(unsigned long nr_pages, struct zone *zone,
1485 struct scan_control *sc, int priority, int file)
1487 unsigned long nr_taken;
1488 unsigned long pgscanned;
1489 unsigned long vm_flags;
1490 LIST_HEAD(l_hold); /* The pages which were snipped off */
1491 LIST_HEAD(l_active);
1492 LIST_HEAD(l_inactive);
1494 struct zone_reclaim_stat *reclaim_stat = get_reclaim_stat(zone, sc);
1495 unsigned long nr_rotated = 0;
1498 spin_lock_irq(&zone->lru_lock);
1499 if (scanning_global_lru(sc)) {
1500 nr_taken = isolate_pages_global(nr_pages, &l_hold,
1501 &pgscanned, sc->order,
1502 ISOLATE_ACTIVE, zone,
1504 zone->pages_scanned += pgscanned;
1506 nr_taken = mem_cgroup_isolate_pages(nr_pages, &l_hold,
1507 &pgscanned, sc->order,
1508 ISOLATE_ACTIVE, zone,
1509 sc->mem_cgroup, 1, file);
1511 * mem_cgroup_isolate_pages() keeps track of
1512 * scanned pages on its own.
1516 reclaim_stat->recent_scanned[file] += nr_taken;
1518 __count_zone_vm_events(PGREFILL, zone, pgscanned);
1520 __mod_zone_page_state(zone, NR_ACTIVE_FILE, -nr_taken);
1522 __mod_zone_page_state(zone, NR_ACTIVE_ANON, -nr_taken);
1523 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
1524 spin_unlock_irq(&zone->lru_lock);
1526 while (!list_empty(&l_hold)) {
1528 page = lru_to_page(&l_hold);
1529 list_del(&page->lru);
1531 if (unlikely(!page_evictable(page, NULL))) {
1532 putback_lru_page(page);
1536 if (page_referenced(page, 0, sc->mem_cgroup, &vm_flags)) {
1539 * Identify referenced, file-backed active pages and
1540 * give them one more trip around the active list. So
1541 * that executable code get better chances to stay in
1542 * memory under moderate memory pressure. Anon pages
1543 * are not likely to be evicted by use-once streaming
1544 * IO, plus JVM can create lots of anon VM_EXEC pages,
1545 * so we ignore them here.
1547 if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
1548 list_add(&page->lru, &l_active);
1553 ClearPageActive(page); /* we are de-activating */
1554 list_add(&page->lru, &l_inactive);
1558 * Move pages back to the lru list.
1560 spin_lock_irq(&zone->lru_lock);
1562 * Count referenced pages from currently used mappings as rotated,
1563 * even though only some of them are actually re-activated. This
1564 * helps balance scan pressure between file and anonymous pages in
1567 reclaim_stat->recent_rotated[file] += nr_rotated;
1569 move_active_pages_to_lru(zone, &l_active,
1570 LRU_ACTIVE + file * LRU_FILE);
1571 move_active_pages_to_lru(zone, &l_inactive,
1572 LRU_BASE + file * LRU_FILE);
1573 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1574 spin_unlock_irq(&zone->lru_lock);
1578 static int inactive_anon_is_low_global(struct zone *zone)
1580 unsigned long active, inactive;
1582 active = zone_page_state(zone, NR_ACTIVE_ANON);
1583 inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1585 if (inactive * zone->inactive_ratio < active)
1592 * inactive_anon_is_low - check if anonymous pages need to be deactivated
1593 * @zone: zone to check
1594 * @sc: scan control of this context
1596 * Returns true if the zone does not have enough inactive anon pages,
1597 * meaning some active anon pages need to be deactivated.
1599 static int inactive_anon_is_low(struct zone *zone, struct scan_control *sc)
1604 * If we don't have swap space, anonymous page deactivation
1607 if (!total_swap_pages)
1610 if (scanning_global_lru(sc))
1611 low = inactive_anon_is_low_global(zone);
1613 low = mem_cgroup_inactive_anon_is_low(sc->mem_cgroup);
1617 static inline int inactive_anon_is_low(struct zone *zone,
1618 struct scan_control *sc)
1624 static int inactive_file_is_low_global(struct zone *zone)
1626 unsigned long active, inactive;
1628 active = zone_page_state(zone, NR_ACTIVE_FILE);
1629 inactive = zone_page_state(zone, NR_INACTIVE_FILE);
1631 return (active > inactive);
1635 * inactive_file_is_low - check if file pages need to be deactivated
1636 * @zone: zone to check
1637 * @sc: scan control of this context
1639 * When the system is doing streaming IO, memory pressure here
1640 * ensures that active file pages get deactivated, until more
1641 * than half of the file pages are on the inactive list.
1643 * Once we get to that situation, protect the system's working
1644 * set from being evicted by disabling active file page aging.
1646 * This uses a different ratio than the anonymous pages, because
1647 * the page cache uses a use-once replacement algorithm.
1649 static int inactive_file_is_low(struct zone *zone, struct scan_control *sc)
1653 if (scanning_global_lru(sc))
1654 low = inactive_file_is_low_global(zone);
1656 low = mem_cgroup_inactive_file_is_low(sc->mem_cgroup);
1660 static int inactive_list_is_low(struct zone *zone, struct scan_control *sc,
1664 return inactive_file_is_low(zone, sc);
1666 return inactive_anon_is_low(zone, sc);
1669 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
1670 struct zone *zone, struct scan_control *sc, int priority)
1672 int file = is_file_lru(lru);
1674 if (is_active_lru(lru)) {
1675 if (inactive_list_is_low(zone, sc, file))
1676 shrink_active_list(nr_to_scan, zone, sc, priority, file);
1680 return shrink_inactive_list(nr_to_scan, zone, sc, priority, file);
1684 * Smallish @nr_to_scan's are deposited in @nr_saved_scan,
1685 * until we collected @swap_cluster_max pages to scan.
1687 static unsigned long nr_scan_try_batch(unsigned long nr_to_scan,
1688 unsigned long *nr_saved_scan)
1692 *nr_saved_scan += nr_to_scan;
1693 nr = *nr_saved_scan;
1695 if (nr >= SWAP_CLUSTER_MAX)
1704 * Determine how aggressively the anon and file LRU lists should be
1705 * scanned. The relative value of each set of LRU lists is determined
1706 * by looking at the fraction of the pages scanned we did rotate back
1707 * onto the active list instead of evict.
1709 * nr[0] = anon pages to scan; nr[1] = file pages to scan
1711 static void get_scan_count(struct zone *zone, struct scan_control *sc,
1712 unsigned long *nr, int priority)
1714 unsigned long anon, file, free;
1715 unsigned long anon_prio, file_prio;
1716 unsigned long ap, fp;
1717 struct zone_reclaim_stat *reclaim_stat = get_reclaim_stat(zone, sc);
1718 u64 fraction[2], denominator;
1722 /* If we have no swap space, do not bother scanning anon pages. */
1723 if (!sc->may_swap || (nr_swap_pages <= 0)) {
1731 anon = zone_nr_lru_pages(zone, sc, LRU_ACTIVE_ANON) +
1732 zone_nr_lru_pages(zone, sc, LRU_INACTIVE_ANON);
1733 file = zone_nr_lru_pages(zone, sc, LRU_ACTIVE_FILE) +
1734 zone_nr_lru_pages(zone, sc, LRU_INACTIVE_FILE);
1736 if (scanning_global_lru(sc)) {
1737 free = zone_page_state(zone, NR_FREE_PAGES);
1738 /* If we have very few page cache pages,
1739 force-scan anon pages. */
1740 if (unlikely(file + free <= high_wmark_pages(zone))) {
1749 * With swappiness at 100, anonymous and file have the same priority.
1750 * This scanning priority is essentially the inverse of IO cost.
1752 anon_prio = sc->swappiness;
1753 file_prio = 200 - sc->swappiness;
1756 * OK, so we have swap space and a fair amount of page cache
1757 * pages. We use the recently rotated / recently scanned
1758 * ratios to determine how valuable each cache is.
1760 * Because workloads change over time (and to avoid overflow)
1761 * we keep these statistics as a floating average, which ends
1762 * up weighing recent references more than old ones.
1764 * anon in [0], file in [1]
1766 spin_lock_irq(&zone->lru_lock);
1767 if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
1768 reclaim_stat->recent_scanned[0] /= 2;
1769 reclaim_stat->recent_rotated[0] /= 2;
1772 if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
1773 reclaim_stat->recent_scanned[1] /= 2;
1774 reclaim_stat->recent_rotated[1] /= 2;
1778 * The amount of pressure on anon vs file pages is inversely
1779 * proportional to the fraction of recently scanned pages on
1780 * each list that were recently referenced and in active use.
1782 ap = (anon_prio + 1) * (reclaim_stat->recent_scanned[0] + 1);
1783 ap /= reclaim_stat->recent_rotated[0] + 1;
1785 fp = (file_prio + 1) * (reclaim_stat->recent_scanned[1] + 1);
1786 fp /= reclaim_stat->recent_rotated[1] + 1;
1787 spin_unlock_irq(&zone->lru_lock);
1791 denominator = ap + fp + 1;
1793 for_each_evictable_lru(l) {
1794 int file = is_file_lru(l);
1797 scan = zone_nr_lru_pages(zone, sc, l);
1798 if (priority || noswap) {
1800 scan = div64_u64(scan * fraction[file], denominator);
1802 nr[l] = nr_scan_try_batch(scan,
1803 &reclaim_stat->nr_saved_scan[l]);
1808 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
1810 static void shrink_zone(int priority, struct zone *zone,
1811 struct scan_control *sc)
1813 unsigned long nr[NR_LRU_LISTS];
1814 unsigned long nr_to_scan;
1816 unsigned long nr_reclaimed = sc->nr_reclaimed;
1817 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
1819 get_scan_count(zone, sc, nr, priority);
1821 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
1822 nr[LRU_INACTIVE_FILE]) {
1823 for_each_evictable_lru(l) {
1825 nr_to_scan = min_t(unsigned long,
1826 nr[l], SWAP_CLUSTER_MAX);
1827 nr[l] -= nr_to_scan;
1829 nr_reclaimed += shrink_list(l, nr_to_scan,
1830 zone, sc, priority);
1834 * On large memory systems, scan >> priority can become
1835 * really large. This is fine for the starting priority;
1836 * we want to put equal scanning pressure on each zone.
1837 * However, if the VM has a harder time of freeing pages,
1838 * with multiple processes reclaiming pages, the total
1839 * freeing target can get unreasonably large.
1841 if (nr_reclaimed >= nr_to_reclaim && priority < DEF_PRIORITY)
1845 sc->nr_reclaimed = nr_reclaimed;
1848 * Even if we did not try to evict anon pages at all, we want to
1849 * rebalance the anon lru active/inactive ratio.
1851 if (inactive_anon_is_low(zone, sc))
1852 shrink_active_list(SWAP_CLUSTER_MAX, zone, sc, priority, 0);
1854 throttle_vm_writeout(sc->gfp_mask);
1858 * This is the direct reclaim path, for page-allocating processes. We only
1859 * try to reclaim pages from zones which will satisfy the caller's allocation
1862 * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
1864 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
1866 * b) The target zone may be at high_wmark_pages(zone) but the lower zones
1867 * must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
1868 * zone defense algorithm.
1870 * If a zone is deemed to be full of pinned pages then just give it a light
1871 * scan then give up on it.
1873 static void shrink_zones(int priority, struct zonelist *zonelist,
1874 struct scan_control *sc)
1879 for_each_zone_zonelist_nodemask(zone, z, zonelist,
1880 gfp_zone(sc->gfp_mask), sc->nodemask) {
1881 if (!populated_zone(zone))
1884 * Take care memory controller reclaiming has small influence
1887 if (scanning_global_lru(sc)) {
1888 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1890 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1891 continue; /* Let kswapd poll it */
1894 shrink_zone(priority, zone, sc);
1898 static bool zone_reclaimable(struct zone *zone)
1900 return zone->pages_scanned < zone_reclaimable_pages(zone) * 6;
1904 * As hibernation is going on, kswapd is freezed so that it can't mark
1905 * the zone into all_unreclaimable. It can't handle OOM during hibernation.
1906 * So let's check zone's unreclaimable in direct reclaim as well as kswapd.
1908 static bool all_unreclaimable(struct zonelist *zonelist,
1909 struct scan_control *sc)
1913 bool all_unreclaimable = true;
1915 for_each_zone_zonelist_nodemask(zone, z, zonelist,
1916 gfp_zone(sc->gfp_mask), sc->nodemask) {
1917 if (!populated_zone(zone))
1919 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1921 if (zone_reclaimable(zone)) {
1922 all_unreclaimable = false;
1927 return all_unreclaimable;
1931 * This is the main entry point to direct page reclaim.
1933 * If a full scan of the inactive list fails to free enough memory then we
1934 * are "out of memory" and something needs to be killed.
1936 * If the caller is !__GFP_FS then the probability of a failure is reasonably
1937 * high - the zone may be full of dirty or under-writeback pages, which this
1938 * caller can't do much about. We kick the writeback threads and take explicit
1939 * naps in the hope that some of these pages can be written. But if the
1940 * allocating task holds filesystem locks which prevent writeout this might not
1941 * work, and the allocation attempt will fail.
1943 * returns: 0, if no pages reclaimed
1944 * else, the number of pages reclaimed
1946 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
1947 struct scan_control *sc)
1950 unsigned long total_scanned = 0;
1951 struct reclaim_state *reclaim_state = current->reclaim_state;
1954 unsigned long writeback_threshold;
1957 delayacct_freepages_start();
1959 if (scanning_global_lru(sc))
1960 count_vm_event(ALLOCSTALL);
1962 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1965 disable_swap_token();
1966 shrink_zones(priority, zonelist, sc);
1968 * Don't shrink slabs when reclaiming memory from
1969 * over limit cgroups
1971 if (scanning_global_lru(sc)) {
1972 unsigned long lru_pages = 0;
1973 for_each_zone_zonelist(zone, z, zonelist,
1974 gfp_zone(sc->gfp_mask)) {
1975 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1978 lru_pages += zone_reclaimable_pages(zone);
1981 shrink_slab(sc->nr_scanned, sc->gfp_mask, lru_pages);
1982 if (reclaim_state) {
1983 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
1984 reclaim_state->reclaimed_slab = 0;
1987 total_scanned += sc->nr_scanned;
1988 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
1992 * Try to write back as many pages as we just scanned. This
1993 * tends to cause slow streaming writers to write data to the
1994 * disk smoothly, at the dirtying rate, which is nice. But
1995 * that's undesirable in laptop mode, where we *want* lumpy
1996 * writeout. So in laptop mode, write out the whole world.
1998 writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
1999 if (total_scanned > writeback_threshold) {
2000 wakeup_flusher_threads(laptop_mode ? 0 : total_scanned);
2001 sc->may_writepage = 1;
2004 /* Take a nap, wait for some writeback to complete */
2005 if (!sc->hibernation_mode && sc->nr_scanned &&
2006 priority < DEF_PRIORITY - 2) {
2007 struct zone *preferred_zone;
2009 first_zones_zonelist(zonelist, gfp_zone(sc->gfp_mask),
2010 NULL, &preferred_zone);
2011 wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/10);
2016 delayacct_freepages_end();
2019 if (sc->nr_reclaimed)
2020 return sc->nr_reclaimed;
2022 /* top priority shrink_zones still had more to do? don't OOM, then */
2023 if (scanning_global_lru(sc) && !all_unreclaimable(zonelist, sc))
2029 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2030 gfp_t gfp_mask, nodemask_t *nodemask)
2032 unsigned long nr_reclaimed;
2033 struct scan_control sc = {
2034 .gfp_mask = gfp_mask,
2035 .may_writepage = !laptop_mode,
2036 .nr_to_reclaim = SWAP_CLUSTER_MAX,
2039 .swappiness = vm_swappiness,
2042 .nodemask = nodemask,
2045 trace_mm_vmscan_direct_reclaim_begin(order,
2049 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
2051 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
2053 return nr_reclaimed;
2056 #ifdef CONFIG_CGROUP_MEM_RES_CTLR
2058 unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *mem,
2059 gfp_t gfp_mask, bool noswap,
2060 unsigned int swappiness,
2063 struct scan_control sc = {
2064 .nr_to_reclaim = SWAP_CLUSTER_MAX,
2065 .may_writepage = !laptop_mode,
2067 .may_swap = !noswap,
2068 .swappiness = swappiness,
2072 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2073 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2075 trace_mm_vmscan_memcg_softlimit_reclaim_begin(0,
2080 * NOTE: Although we can get the priority field, using it
2081 * here is not a good idea, since it limits the pages we can scan.
2082 * if we don't reclaim here, the shrink_zone from balance_pgdat
2083 * will pick up pages from other mem cgroup's as well. We hack
2084 * the priority and make it zero.
2086 shrink_zone(0, zone, &sc);
2088 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
2090 return sc.nr_reclaimed;
2093 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *mem_cont,
2096 unsigned int swappiness)
2098 struct zonelist *zonelist;
2099 unsigned long nr_reclaimed;
2100 struct scan_control sc = {
2101 .may_writepage = !laptop_mode,
2103 .may_swap = !noswap,
2104 .nr_to_reclaim = SWAP_CLUSTER_MAX,
2105 .swappiness = swappiness,
2107 .mem_cgroup = mem_cont,
2108 .nodemask = NULL, /* we don't care the placement */
2111 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2112 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2113 zonelist = NODE_DATA(numa_node_id())->node_zonelists;
2115 trace_mm_vmscan_memcg_reclaim_begin(0,
2119 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
2121 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
2123 return nr_reclaimed;
2127 /* is kswapd sleeping prematurely? */
2128 static int sleeping_prematurely(pg_data_t *pgdat, int order, long remaining)
2132 /* If a direct reclaimer woke kswapd within HZ/10, it's premature */
2136 /* If after HZ/10, a zone is below the high mark, it's premature */
2137 for (i = 0; i < pgdat->nr_zones; i++) {
2138 struct zone *zone = pgdat->node_zones + i;
2140 if (!populated_zone(zone))
2143 if (zone->all_unreclaimable)
2146 if (!zone_watermark_ok_safe(zone, order, high_wmark_pages(zone),
2155 * For kswapd, balance_pgdat() will work across all this node's zones until
2156 * they are all at high_wmark_pages(zone).
2158 * Returns the number of pages which were actually freed.
2160 * There is special handling here for zones which are full of pinned pages.
2161 * This can happen if the pages are all mlocked, or if they are all used by
2162 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
2163 * What we do is to detect the case where all pages in the zone have been
2164 * scanned twice and there has been zero successful reclaim. Mark the zone as
2165 * dead and from now on, only perform a short scan. Basically we're polling
2166 * the zone for when the problem goes away.
2168 * kswapd scans the zones in the highmem->normal->dma direction. It skips
2169 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
2170 * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
2171 * lower zones regardless of the number of free pages in the lower zones. This
2172 * interoperates with the page allocator fallback scheme to ensure that aging
2173 * of pages is balanced across the zones.
2175 static unsigned long balance_pgdat(pg_data_t *pgdat, int order)
2180 unsigned long total_scanned;
2181 struct reclaim_state *reclaim_state = current->reclaim_state;
2182 struct scan_control sc = {
2183 .gfp_mask = GFP_KERNEL,
2187 * kswapd doesn't want to be bailed out while reclaim. because
2188 * we want to put equal scanning pressure on each zone.
2190 .nr_to_reclaim = ULONG_MAX,
2191 .swappiness = vm_swappiness,
2197 sc.nr_reclaimed = 0;
2198 sc.may_writepage = !laptop_mode;
2199 count_vm_event(PAGEOUTRUN);
2201 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
2202 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
2203 unsigned long lru_pages = 0;
2204 int has_under_min_watermark_zone = 0;
2206 /* The swap token gets in the way of swapout... */
2208 disable_swap_token();
2213 * Scan in the highmem->dma direction for the highest
2214 * zone which needs scanning
2216 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
2217 struct zone *zone = pgdat->node_zones + i;
2219 if (!populated_zone(zone))
2222 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
2226 * Do some background aging of the anon list, to give
2227 * pages a chance to be referenced before reclaiming.
2229 if (inactive_anon_is_low(zone, &sc))
2230 shrink_active_list(SWAP_CLUSTER_MAX, zone,
2233 if (!zone_watermark_ok_safe(zone, order,
2234 high_wmark_pages(zone), 0, 0)) {
2242 for (i = 0; i <= end_zone; i++) {
2243 struct zone *zone = pgdat->node_zones + i;
2245 lru_pages += zone_reclaimable_pages(zone);
2249 * Now scan the zone in the dma->highmem direction, stopping
2250 * at the last zone which needs scanning.
2252 * We do this because the page allocator works in the opposite
2253 * direction. This prevents the page allocator from allocating
2254 * pages behind kswapd's direction of progress, which would
2255 * cause too much scanning of the lower zones.
2257 for (i = 0; i <= end_zone; i++) {
2258 struct zone *zone = pgdat->node_zones + i;
2261 if (!populated_zone(zone))
2264 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
2270 * Call soft limit reclaim before calling shrink_zone.
2271 * For now we ignore the return value
2273 mem_cgroup_soft_limit_reclaim(zone, order, sc.gfp_mask);
2276 * We put equal pressure on every zone, unless one
2277 * zone has way too many pages free already.
2279 if (!zone_watermark_ok_safe(zone, order,
2280 8*high_wmark_pages(zone), end_zone, 0))
2281 shrink_zone(priority, zone, &sc);
2282 reclaim_state->reclaimed_slab = 0;
2283 nr_slab = shrink_slab(sc.nr_scanned, GFP_KERNEL,
2285 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
2286 total_scanned += sc.nr_scanned;
2287 if (zone->all_unreclaimable)
2289 if (nr_slab == 0 && !zone_reclaimable(zone))
2290 zone->all_unreclaimable = 1;
2292 * If we've done a decent amount of scanning and
2293 * the reclaim ratio is low, start doing writepage
2294 * even in laptop mode
2296 if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
2297 total_scanned > sc.nr_reclaimed + sc.nr_reclaimed / 2)
2298 sc.may_writepage = 1;
2300 if (!zone_watermark_ok_safe(zone, order,
2301 high_wmark_pages(zone), end_zone, 0)) {
2304 * We are still under min water mark. This
2305 * means that we have a GFP_ATOMIC allocation
2306 * failure risk. Hurry up!
2308 if (!zone_watermark_ok_safe(zone, order,
2309 min_wmark_pages(zone), end_zone, 0))
2310 has_under_min_watermark_zone = 1;
2313 * If a zone reaches its high watermark,
2314 * consider it to be no longer congested. It's
2315 * possible there are dirty pages backed by
2316 * congested BDIs but as pressure is relieved,
2317 * spectulatively avoid congestion waits
2319 zone_clear_flag(zone, ZONE_CONGESTED);
2324 break; /* kswapd: all done */
2326 * OK, kswapd is getting into trouble. Take a nap, then take
2327 * another pass across the zones.
2329 if (total_scanned && (priority < DEF_PRIORITY - 2)) {
2330 if (has_under_min_watermark_zone)
2331 count_vm_event(KSWAPD_SKIP_CONGESTION_WAIT);
2333 congestion_wait(BLK_RW_ASYNC, HZ/10);
2337 * We do this so kswapd doesn't build up large priorities for
2338 * example when it is freeing in parallel with allocators. It
2339 * matches the direct reclaim path behaviour in terms of impact
2340 * on zone->*_priority.
2342 if (sc.nr_reclaimed >= SWAP_CLUSTER_MAX)
2346 if (!all_zones_ok) {
2352 * Fragmentation may mean that the system cannot be
2353 * rebalanced for high-order allocations in all zones.
2354 * At this point, if nr_reclaimed < SWAP_CLUSTER_MAX,
2355 * it means the zones have been fully scanned and are still
2356 * not balanced. For high-order allocations, there is
2357 * little point trying all over again as kswapd may
2360 * Instead, recheck all watermarks at order-0 as they
2361 * are the most important. If watermarks are ok, kswapd will go
2362 * back to sleep. High-order users can still perform direct
2363 * reclaim if they wish.
2365 if (sc.nr_reclaimed < SWAP_CLUSTER_MAX)
2366 order = sc.order = 0;
2371 return sc.nr_reclaimed;
2375 * The background pageout daemon, started as a kernel thread
2376 * from the init process.
2378 * This basically trickles out pages so that we have _some_
2379 * free memory available even if there is no other activity
2380 * that frees anything up. This is needed for things like routing
2381 * etc, where we otherwise might have all activity going on in
2382 * asynchronous contexts that cannot page things out.
2384 * If there are applications that are active memory-allocators
2385 * (most normal use), this basically shouldn't matter.
2387 static int kswapd(void *p)
2389 unsigned long order;
2390 pg_data_t *pgdat = (pg_data_t*)p;
2391 struct task_struct *tsk = current;
2393 struct reclaim_state reclaim_state = {
2394 .reclaimed_slab = 0,
2396 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
2398 lockdep_set_current_reclaim_state(GFP_KERNEL);
2400 if (!cpumask_empty(cpumask))
2401 set_cpus_allowed_ptr(tsk, cpumask);
2402 current->reclaim_state = &reclaim_state;
2405 * Tell the memory management that we're a "memory allocator",
2406 * and that if we need more memory we should get access to it
2407 * regardless (see "__alloc_pages()"). "kswapd" should
2408 * never get caught in the normal page freeing logic.
2410 * (Kswapd normally doesn't need memory anyway, but sometimes
2411 * you need a small amount of memory in order to be able to
2412 * page out something else, and this flag essentially protects
2413 * us from recursively trying to free more memory as we're
2414 * trying to free the first piece of memory in the first place).
2416 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
2421 unsigned long new_order;
2424 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
2425 new_order = pgdat->kswapd_max_order;
2426 pgdat->kswapd_max_order = 0;
2427 if (order < new_order) {
2429 * Don't sleep if someone wants a larger 'order'
2434 if (!freezing(current) && !kthread_should_stop()) {
2437 /* Try to sleep for a short interval */
2438 if (!sleeping_prematurely(pgdat, order, remaining)) {
2439 remaining = schedule_timeout(HZ/10);
2440 finish_wait(&pgdat->kswapd_wait, &wait);
2441 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
2445 * After a short sleep, check if it was a
2446 * premature sleep. If not, then go fully
2447 * to sleep until explicitly woken up
2449 if (!sleeping_prematurely(pgdat, order, remaining)) {
2450 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
2451 restore_pgdat_percpu_threshold(pgdat);
2453 reduce_pgdat_percpu_threshold(pgdat);
2456 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
2458 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
2462 order = pgdat->kswapd_max_order;
2464 finish_wait(&pgdat->kswapd_wait, &wait);
2466 ret = try_to_freeze();
2467 if (kthread_should_stop())
2471 * We can speed up thawing tasks if we don't call balance_pgdat
2472 * after returning from the refrigerator
2475 trace_mm_vmscan_kswapd_wake(pgdat->node_id, order);
2476 balance_pgdat(pgdat, order);
2483 * A zone is low on free memory, so wake its kswapd task to service it.
2485 void wakeup_kswapd(struct zone *zone, int order)
2489 if (!populated_zone(zone))
2492 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2494 pgdat = zone->zone_pgdat;
2495 if (pgdat->kswapd_max_order < order)
2496 pgdat->kswapd_max_order = order;
2497 if (!waitqueue_active(&pgdat->kswapd_wait))
2499 if (zone_watermark_ok_safe(zone, order, low_wmark_pages(zone), 0, 0))
2502 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
2503 wake_up_interruptible(&pgdat->kswapd_wait);
2507 * The reclaimable count would be mostly accurate.
2508 * The less reclaimable pages may be
2509 * - mlocked pages, which will be moved to unevictable list when encountered
2510 * - mapped pages, which may require several travels to be reclaimed
2511 * - dirty pages, which is not "instantly" reclaimable
2513 unsigned long global_reclaimable_pages(void)
2517 nr = global_page_state(NR_ACTIVE_FILE) +
2518 global_page_state(NR_INACTIVE_FILE);
2520 if (nr_swap_pages > 0)
2521 nr += global_page_state(NR_ACTIVE_ANON) +
2522 global_page_state(NR_INACTIVE_ANON);
2527 unsigned long zone_reclaimable_pages(struct zone *zone)
2531 nr = zone_page_state(zone, NR_ACTIVE_FILE) +
2532 zone_page_state(zone, NR_INACTIVE_FILE);
2534 if (nr_swap_pages > 0)
2535 nr += zone_page_state(zone, NR_ACTIVE_ANON) +
2536 zone_page_state(zone, NR_INACTIVE_ANON);
2541 #ifdef CONFIG_HIBERNATION
2543 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
2546 * Rather than trying to age LRUs the aim is to preserve the overall
2547 * LRU order by reclaiming preferentially
2548 * inactive > active > active referenced > active mapped
2550 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
2552 struct reclaim_state reclaim_state;
2553 struct scan_control sc = {
2554 .gfp_mask = GFP_HIGHUSER_MOVABLE,
2558 .nr_to_reclaim = nr_to_reclaim,
2559 .hibernation_mode = 1,
2560 .swappiness = vm_swappiness,
2563 struct zonelist * zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
2564 struct task_struct *p = current;
2565 unsigned long nr_reclaimed;
2567 p->flags |= PF_MEMALLOC;
2568 lockdep_set_current_reclaim_state(sc.gfp_mask);
2569 reclaim_state.reclaimed_slab = 0;
2570 p->reclaim_state = &reclaim_state;
2572 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
2574 p->reclaim_state = NULL;
2575 lockdep_clear_current_reclaim_state();
2576 p->flags &= ~PF_MEMALLOC;
2578 return nr_reclaimed;
2580 #endif /* CONFIG_HIBERNATION */
2582 /* It's optimal to keep kswapds on the same CPUs as their memory, but
2583 not required for correctness. So if the last cpu in a node goes
2584 away, we get changed to run anywhere: as the first one comes back,
2585 restore their cpu bindings. */
2586 static int __devinit cpu_callback(struct notifier_block *nfb,
2587 unsigned long action, void *hcpu)
2591 if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
2592 for_each_node_state(nid, N_HIGH_MEMORY) {
2593 pg_data_t *pgdat = NODE_DATA(nid);
2594 const struct cpumask *mask;
2596 mask = cpumask_of_node(pgdat->node_id);
2598 if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
2599 /* One of our CPUs online: restore mask */
2600 set_cpus_allowed_ptr(pgdat->kswapd, mask);
2607 * This kswapd start function will be called by init and node-hot-add.
2608 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
2610 int kswapd_run(int nid)
2612 pg_data_t *pgdat = NODE_DATA(nid);
2618 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
2619 if (IS_ERR(pgdat->kswapd)) {
2620 /* failure at boot is fatal */
2621 BUG_ON(system_state == SYSTEM_BOOTING);
2622 printk("Failed to start kswapd on node %d\n",nid);
2629 * Called by memory hotplug when all memory in a node is offlined.
2631 void kswapd_stop(int nid)
2633 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
2636 kthread_stop(kswapd);
2639 static int __init kswapd_init(void)
2644 for_each_node_state(nid, N_HIGH_MEMORY)
2646 hotcpu_notifier(cpu_callback, 0);
2650 module_init(kswapd_init)
2656 * If non-zero call zone_reclaim when the number of free pages falls below
2659 int zone_reclaim_mode __read_mostly;
2661 #define RECLAIM_OFF 0
2662 #define RECLAIM_ZONE (1<<0) /* Run shrink_inactive_list on the zone */
2663 #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
2664 #define RECLAIM_SWAP (1<<2) /* Swap pages out during reclaim */
2667 * Priority for ZONE_RECLAIM. This determines the fraction of pages
2668 * of a node considered for each zone_reclaim. 4 scans 1/16th of
2671 #define ZONE_RECLAIM_PRIORITY 4
2674 * Percentage of pages in a zone that must be unmapped for zone_reclaim to
2677 int sysctl_min_unmapped_ratio = 1;
2680 * If the number of slab pages in a zone grows beyond this percentage then
2681 * slab reclaim needs to occur.
2683 int sysctl_min_slab_ratio = 5;
2685 static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
2687 unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
2688 unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
2689 zone_page_state(zone, NR_ACTIVE_FILE);
2692 * It's possible for there to be more file mapped pages than
2693 * accounted for by the pages on the file LRU lists because
2694 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
2696 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
2699 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
2700 static long zone_pagecache_reclaimable(struct zone *zone)
2702 long nr_pagecache_reclaimable;
2706 * If RECLAIM_SWAP is set, then all file pages are considered
2707 * potentially reclaimable. Otherwise, we have to worry about
2708 * pages like swapcache and zone_unmapped_file_pages() provides
2711 if (zone_reclaim_mode & RECLAIM_SWAP)
2712 nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
2714 nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
2716 /* If we can't clean pages, remove dirty pages from consideration */
2717 if (!(zone_reclaim_mode & RECLAIM_WRITE))
2718 delta += zone_page_state(zone, NR_FILE_DIRTY);
2720 /* Watch for any possible underflows due to delta */
2721 if (unlikely(delta > nr_pagecache_reclaimable))
2722 delta = nr_pagecache_reclaimable;
2724 return nr_pagecache_reclaimable - delta;
2728 * Try to free up some pages from this zone through reclaim.
2730 static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
2732 /* Minimum pages needed in order to stay on node */
2733 const unsigned long nr_pages = 1 << order;
2734 struct task_struct *p = current;
2735 struct reclaim_state reclaim_state;
2737 struct scan_control sc = {
2738 .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
2739 .may_unmap = !!(zone_reclaim_mode & RECLAIM_SWAP),
2741 .nr_to_reclaim = max_t(unsigned long, nr_pages,
2743 .gfp_mask = gfp_mask,
2744 .swappiness = vm_swappiness,
2747 unsigned long nr_slab_pages0, nr_slab_pages1;
2751 * We need to be able to allocate from the reserves for RECLAIM_SWAP
2752 * and we also need to be able to write out pages for RECLAIM_WRITE
2755 p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
2756 lockdep_set_current_reclaim_state(gfp_mask);
2757 reclaim_state.reclaimed_slab = 0;
2758 p->reclaim_state = &reclaim_state;
2760 if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
2762 * Free memory by calling shrink zone with increasing
2763 * priorities until we have enough memory freed.
2765 priority = ZONE_RECLAIM_PRIORITY;
2767 shrink_zone(priority, zone, &sc);
2769 } while (priority >= 0 && sc.nr_reclaimed < nr_pages);
2772 nr_slab_pages0 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
2773 if (nr_slab_pages0 > zone->min_slab_pages) {
2775 * shrink_slab() does not currently allow us to determine how
2776 * many pages were freed in this zone. So we take the current
2777 * number of slab pages and shake the slab until it is reduced
2778 * by the same nr_pages that we used for reclaiming unmapped
2781 * Note that shrink_slab will free memory on all zones and may
2785 unsigned long lru_pages = zone_reclaimable_pages(zone);
2787 /* No reclaimable slab or very low memory pressure */
2788 if (!shrink_slab(sc.nr_scanned, gfp_mask, lru_pages))
2791 /* Freed enough memory */
2792 nr_slab_pages1 = zone_page_state(zone,
2793 NR_SLAB_RECLAIMABLE);
2794 if (nr_slab_pages1 + nr_pages <= nr_slab_pages0)
2799 * Update nr_reclaimed by the number of slab pages we
2800 * reclaimed from this zone.
2802 nr_slab_pages1 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
2803 if (nr_slab_pages1 < nr_slab_pages0)
2804 sc.nr_reclaimed += nr_slab_pages0 - nr_slab_pages1;
2807 p->reclaim_state = NULL;
2808 current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
2809 lockdep_clear_current_reclaim_state();
2810 return sc.nr_reclaimed >= nr_pages;
2813 int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
2819 * Zone reclaim reclaims unmapped file backed pages and
2820 * slab pages if we are over the defined limits.
2822 * A small portion of unmapped file backed pages is needed for
2823 * file I/O otherwise pages read by file I/O will be immediately
2824 * thrown out if the zone is overallocated. So we do not reclaim
2825 * if less than a specified percentage of the zone is used by
2826 * unmapped file backed pages.
2828 if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
2829 zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
2830 return ZONE_RECLAIM_FULL;
2832 if (zone->all_unreclaimable)
2833 return ZONE_RECLAIM_FULL;
2836 * Do not scan if the allocation should not be delayed.
2838 if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
2839 return ZONE_RECLAIM_NOSCAN;
2842 * Only run zone reclaim on the local zone or on zones that do not
2843 * have associated processors. This will favor the local processor
2844 * over remote processors and spread off node memory allocations
2845 * as wide as possible.
2847 node_id = zone_to_nid(zone);
2848 if (node_state(node_id, N_CPU) && node_id != numa_node_id())
2849 return ZONE_RECLAIM_NOSCAN;
2851 if (zone_test_and_set_flag(zone, ZONE_RECLAIM_LOCKED))
2852 return ZONE_RECLAIM_NOSCAN;
2854 ret = __zone_reclaim(zone, gfp_mask, order);
2855 zone_clear_flag(zone, ZONE_RECLAIM_LOCKED);
2858 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
2865 * page_evictable - test whether a page is evictable
2866 * @page: the page to test
2867 * @vma: the VMA in which the page is or will be mapped, may be NULL
2869 * Test whether page is evictable--i.e., should be placed on active/inactive
2870 * lists vs unevictable list. The vma argument is !NULL when called from the
2871 * fault path to determine how to instantate a new page.
2873 * Reasons page might not be evictable:
2874 * (1) page's mapping marked unevictable
2875 * (2) page is part of an mlocked VMA
2878 int page_evictable(struct page *page, struct vm_area_struct *vma)
2881 if (mapping_unevictable(page_mapping(page)))
2884 if (PageMlocked(page) || (vma && is_mlocked_vma(vma, page)))
2891 * check_move_unevictable_page - check page for evictability and move to appropriate zone lru list
2892 * @page: page to check evictability and move to appropriate lru list
2893 * @zone: zone page is in
2895 * Checks a page for evictability and moves the page to the appropriate
2898 * Restrictions: zone->lru_lock must be held, page must be on LRU and must
2899 * have PageUnevictable set.
2901 static void check_move_unevictable_page(struct page *page, struct zone *zone)
2903 VM_BUG_ON(PageActive(page));
2906 ClearPageUnevictable(page);
2907 if (page_evictable(page, NULL)) {
2908 enum lru_list l = page_lru_base_type(page);
2910 __dec_zone_state(zone, NR_UNEVICTABLE);
2911 list_move(&page->lru, &zone->lru[l].list);
2912 mem_cgroup_move_lists(page, LRU_UNEVICTABLE, l);
2913 __inc_zone_state(zone, NR_INACTIVE_ANON + l);
2914 __count_vm_event(UNEVICTABLE_PGRESCUED);
2917 * rotate unevictable list
2919 SetPageUnevictable(page);
2920 list_move(&page->lru, &zone->lru[LRU_UNEVICTABLE].list);
2921 mem_cgroup_rotate_lru_list(page, LRU_UNEVICTABLE);
2922 if (page_evictable(page, NULL))
2928 * scan_mapping_unevictable_pages - scan an address space for evictable pages
2929 * @mapping: struct address_space to scan for evictable pages
2931 * Scan all pages in mapping. Check unevictable pages for
2932 * evictability and move them to the appropriate zone lru list.
2934 void scan_mapping_unevictable_pages(struct address_space *mapping)
2937 pgoff_t end = (i_size_read(mapping->host) + PAGE_CACHE_SIZE - 1) >>
2940 struct pagevec pvec;
2942 if (mapping->nrpages == 0)
2945 pagevec_init(&pvec, 0);
2946 while (next < end &&
2947 pagevec_lookup(&pvec, mapping, next, PAGEVEC_SIZE)) {
2953 for (i = 0; i < pagevec_count(&pvec); i++) {
2954 struct page *page = pvec.pages[i];
2955 pgoff_t page_index = page->index;
2956 struct zone *pagezone = page_zone(page);
2959 if (page_index > next)
2963 if (pagezone != zone) {
2965 spin_unlock_irq(&zone->lru_lock);
2967 spin_lock_irq(&zone->lru_lock);
2970 if (PageLRU(page) && PageUnevictable(page))
2971 check_move_unevictable_page(page, zone);
2974 spin_unlock_irq(&zone->lru_lock);
2975 pagevec_release(&pvec);
2977 count_vm_events(UNEVICTABLE_PGSCANNED, pg_scanned);
2983 * scan_zone_unevictable_pages - check unevictable list for evictable pages
2984 * @zone - zone of which to scan the unevictable list
2986 * Scan @zone's unevictable LRU lists to check for pages that have become
2987 * evictable. Move those that have to @zone's inactive list where they
2988 * become candidates for reclaim, unless shrink_inactive_zone() decides
2989 * to reactivate them. Pages that are still unevictable are rotated
2990 * back onto @zone's unevictable list.
2992 #define SCAN_UNEVICTABLE_BATCH_SIZE 16UL /* arbitrary lock hold batch size */
2993 static void scan_zone_unevictable_pages(struct zone *zone)
2995 struct list_head *l_unevictable = &zone->lru[LRU_UNEVICTABLE].list;
2997 unsigned long nr_to_scan = zone_page_state(zone, NR_UNEVICTABLE);
2999 while (nr_to_scan > 0) {
3000 unsigned long batch_size = min(nr_to_scan,
3001 SCAN_UNEVICTABLE_BATCH_SIZE);
3003 spin_lock_irq(&zone->lru_lock);
3004 for (scan = 0; scan < batch_size; scan++) {
3005 struct page *page = lru_to_page(l_unevictable);
3007 if (!trylock_page(page))
3010 prefetchw_prev_lru_page(page, l_unevictable, flags);
3012 if (likely(PageLRU(page) && PageUnevictable(page)))
3013 check_move_unevictable_page(page, zone);
3017 spin_unlock_irq(&zone->lru_lock);
3019 nr_to_scan -= batch_size;
3025 * scan_all_zones_unevictable_pages - scan all unevictable lists for evictable pages
3027 * A really big hammer: scan all zones' unevictable LRU lists to check for
3028 * pages that have become evictable. Move those back to the zones'
3029 * inactive list where they become candidates for reclaim.
3030 * This occurs when, e.g., we have unswappable pages on the unevictable lists,
3031 * and we add swap to the system. As such, it runs in the context of a task
3032 * that has possibly/probably made some previously unevictable pages
3035 static void scan_all_zones_unevictable_pages(void)
3039 for_each_zone(zone) {
3040 scan_zone_unevictable_pages(zone);
3045 * scan_unevictable_pages [vm] sysctl handler. On demand re-scan of
3046 * all nodes' unevictable lists for evictable pages
3048 unsigned long scan_unevictable_pages;
3050 int scan_unevictable_handler(struct ctl_table *table, int write,
3051 void __user *buffer,
3052 size_t *length, loff_t *ppos)
3054 proc_doulongvec_minmax(table, write, buffer, length, ppos);
3056 if (write && *(unsigned long *)table->data)
3057 scan_all_zones_unevictable_pages();
3059 scan_unevictable_pages = 0;
3065 * per node 'scan_unevictable_pages' attribute. On demand re-scan of
3066 * a specified node's per zone unevictable lists for evictable pages.
3069 static ssize_t read_scan_unevictable_node(struct sys_device *dev,
3070 struct sysdev_attribute *attr,
3073 return sprintf(buf, "0\n"); /* always zero; should fit... */
3076 static ssize_t write_scan_unevictable_node(struct sys_device *dev,
3077 struct sysdev_attribute *attr,
3078 const char *buf, size_t count)
3080 struct zone *node_zones = NODE_DATA(dev->id)->node_zones;
3083 unsigned long req = strict_strtoul(buf, 10, &res);
3086 return 1; /* zero is no-op */
3088 for (zone = node_zones; zone - node_zones < MAX_NR_ZONES; ++zone) {
3089 if (!populated_zone(zone))
3091 scan_zone_unevictable_pages(zone);
3097 static SYSDEV_ATTR(scan_unevictable_pages, S_IRUGO | S_IWUSR,
3098 read_scan_unevictable_node,
3099 write_scan_unevictable_node);
3101 int scan_unevictable_register_node(struct node *node)
3103 return sysdev_create_file(&node->sysdev, &attr_scan_unevictable_pages);
3106 void scan_unevictable_unregister_node(struct node *node)
3108 sysdev_remove_file(&node->sysdev, &attr_scan_unevictable_pages);