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>
52 /* Incremented by the number of inactive pages that were scanned */
53 unsigned long nr_scanned;
55 /* Number of pages freed so far during a call to shrink_zones() */
56 unsigned long nr_reclaimed;
58 /* How many pages shrink_list() should reclaim */
59 unsigned long nr_to_reclaim;
61 unsigned long hibernation_mode;
63 /* This context's GFP mask */
68 /* Can mapped pages be reclaimed? */
71 /* Can pages be swapped as part of reclaim? */
79 * Intend to reclaim enough contenious memory rather than to reclaim
80 * enough amount memory. I.e, it's the mode for high order allocation.
82 bool lumpy_reclaim_mode;
84 /* Which cgroup do we reclaim from */
85 struct mem_cgroup *mem_cgroup;
88 * Nodemask of nodes allowed by the caller. If NULL, all nodes
93 /* Pluggable isolate pages callback */
94 unsigned long (*isolate_pages)(unsigned long nr, struct list_head *dst,
95 unsigned long *scanned, int order, int mode,
96 struct zone *z, struct mem_cgroup *mem_cont,
97 int active, int file);
100 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
102 #ifdef ARCH_HAS_PREFETCH
103 #define prefetch_prev_lru_page(_page, _base, _field) \
105 if ((_page)->lru.prev != _base) { \
108 prev = lru_to_page(&(_page->lru)); \
109 prefetch(&prev->_field); \
113 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
116 #ifdef ARCH_HAS_PREFETCHW
117 #define prefetchw_prev_lru_page(_page, _base, _field) \
119 if ((_page)->lru.prev != _base) { \
122 prev = lru_to_page(&(_page->lru)); \
123 prefetchw(&prev->_field); \
127 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
131 * From 0 .. 100. Higher means more swappy.
133 int vm_swappiness = 60;
134 long vm_total_pages; /* The total number of pages which the VM controls */
136 static LIST_HEAD(shrinker_list);
137 static DECLARE_RWSEM(shrinker_rwsem);
139 #ifdef CONFIG_CGROUP_MEM_RES_CTLR
140 #define scanning_global_lru(sc) (!(sc)->mem_cgroup)
142 #define scanning_global_lru(sc) (1)
145 static struct zone_reclaim_stat *get_reclaim_stat(struct zone *zone,
146 struct scan_control *sc)
148 if (!scanning_global_lru(sc))
149 return mem_cgroup_get_reclaim_stat(sc->mem_cgroup, zone);
151 return &zone->reclaim_stat;
154 static unsigned long zone_nr_lru_pages(struct zone *zone,
155 struct scan_control *sc, enum lru_list lru)
157 if (!scanning_global_lru(sc))
158 return mem_cgroup_zone_nr_pages(sc->mem_cgroup, zone, lru);
160 return zone_page_state(zone, NR_LRU_BASE + lru);
165 * Add a shrinker callback to be called from the vm
167 void register_shrinker(struct shrinker *shrinker)
170 down_write(&shrinker_rwsem);
171 list_add_tail(&shrinker->list, &shrinker_list);
172 up_write(&shrinker_rwsem);
174 EXPORT_SYMBOL(register_shrinker);
179 void unregister_shrinker(struct shrinker *shrinker)
181 down_write(&shrinker_rwsem);
182 list_del(&shrinker->list);
183 up_write(&shrinker_rwsem);
185 EXPORT_SYMBOL(unregister_shrinker);
187 #define SHRINK_BATCH 128
189 * Call the shrink functions to age shrinkable caches
191 * Here we assume it costs one seek to replace a lru page and that it also
192 * takes a seek to recreate a cache object. With this in mind we age equal
193 * percentages of the lru and ageable caches. This should balance the seeks
194 * generated by these structures.
196 * If the vm encountered mapped pages on the LRU it increase the pressure on
197 * slab to avoid swapping.
199 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
201 * `lru_pages' represents the number of on-LRU pages in all the zones which
202 * are eligible for the caller's allocation attempt. It is used for balancing
203 * slab reclaim versus page reclaim.
205 * Returns the number of slab objects which we shrunk.
207 unsigned long shrink_slab(unsigned long scanned, gfp_t gfp_mask,
208 unsigned long lru_pages)
210 struct shrinker *shrinker;
211 unsigned long ret = 0;
214 scanned = SWAP_CLUSTER_MAX;
216 if (!down_read_trylock(&shrinker_rwsem))
217 return 1; /* Assume we'll be able to shrink next time */
219 list_for_each_entry(shrinker, &shrinker_list, list) {
220 unsigned long long delta;
221 unsigned long total_scan;
222 unsigned long max_pass = (*shrinker->shrink)(0, gfp_mask);
224 delta = (4 * scanned) / shrinker->seeks;
226 do_div(delta, lru_pages + 1);
227 shrinker->nr += delta;
228 if (shrinker->nr < 0) {
229 printk(KERN_ERR "shrink_slab: %pF negative objects to "
231 shrinker->shrink, shrinker->nr);
232 shrinker->nr = max_pass;
236 * Avoid risking looping forever due to too large nr value:
237 * never try to free more than twice the estimate number of
240 if (shrinker->nr > max_pass * 2)
241 shrinker->nr = max_pass * 2;
243 total_scan = shrinker->nr;
246 while (total_scan >= SHRINK_BATCH) {
247 long this_scan = SHRINK_BATCH;
251 nr_before = (*shrinker->shrink)(0, gfp_mask);
252 shrink_ret = (*shrinker->shrink)(this_scan, gfp_mask);
253 if (shrink_ret == -1)
255 if (shrink_ret < nr_before)
256 ret += nr_before - shrink_ret;
257 count_vm_events(SLABS_SCANNED, this_scan);
258 total_scan -= this_scan;
263 shrinker->nr += total_scan;
265 up_read(&shrinker_rwsem);
269 static inline int is_page_cache_freeable(struct page *page)
272 * A freeable page cache page is referenced only by the caller
273 * that isolated the page, the page cache radix tree and
274 * optional buffer heads at page->private.
276 return page_count(page) - page_has_private(page) == 2;
279 static int may_write_to_queue(struct backing_dev_info *bdi)
281 if (current->flags & PF_SWAPWRITE)
283 if (!bdi_write_congested(bdi))
285 if (bdi == current->backing_dev_info)
291 * We detected a synchronous write error writing a page out. Probably
292 * -ENOSPC. We need to propagate that into the address_space for a subsequent
293 * fsync(), msync() or close().
295 * The tricky part is that after writepage we cannot touch the mapping: nothing
296 * prevents it from being freed up. But we have a ref on the page and once
297 * that page is locked, the mapping is pinned.
299 * We're allowed to run sleeping lock_page() here because we know the caller has
302 static void handle_write_error(struct address_space *mapping,
303 struct page *page, int error)
306 if (page_mapping(page) == mapping)
307 mapping_set_error(mapping, error);
311 /* Request for sync pageout. */
317 /* possible outcome of pageout() */
319 /* failed to write page out, page is locked */
321 /* move page to the active list, page is locked */
323 /* page has been sent to the disk successfully, page is unlocked */
325 /* page is clean and locked */
330 * pageout is called by shrink_page_list() for each dirty page.
331 * Calls ->writepage().
333 static pageout_t pageout(struct page *page, struct address_space *mapping,
334 enum pageout_io sync_writeback)
337 * If the page is dirty, only perform writeback if that write
338 * will be non-blocking. To prevent this allocation from being
339 * stalled by pagecache activity. But note that there may be
340 * stalls if we need to run get_block(). We could test
341 * PagePrivate for that.
343 * If this process is currently in __generic_file_aio_write() against
344 * this page's queue, we can perform writeback even if that
347 * If the page is swapcache, write it back even if that would
348 * block, for some throttling. This happens by accident, because
349 * swap_backing_dev_info is bust: it doesn't reflect the
350 * congestion state of the swapdevs. Easy to fix, if needed.
352 if (!is_page_cache_freeable(page))
356 * Some data journaling orphaned pages can have
357 * page->mapping == NULL while being dirty with clean buffers.
359 if (page_has_private(page)) {
360 if (try_to_free_buffers(page)) {
361 ClearPageDirty(page);
362 printk("%s: orphaned page\n", __func__);
368 if (mapping->a_ops->writepage == NULL)
369 return PAGE_ACTIVATE;
370 if (!may_write_to_queue(mapping->backing_dev_info))
373 if (clear_page_dirty_for_io(page)) {
375 struct writeback_control wbc = {
376 .sync_mode = WB_SYNC_NONE,
377 .nr_to_write = SWAP_CLUSTER_MAX,
379 .range_end = LLONG_MAX,
384 SetPageReclaim(page);
385 res = mapping->a_ops->writepage(page, &wbc);
387 handle_write_error(mapping, page, res);
388 if (res == AOP_WRITEPAGE_ACTIVATE) {
389 ClearPageReclaim(page);
390 return PAGE_ACTIVATE;
394 * Wait on writeback if requested to. This happens when
395 * direct reclaiming a large contiguous area and the
396 * first attempt to free a range of pages fails.
398 if (PageWriteback(page) && sync_writeback == PAGEOUT_IO_SYNC)
399 wait_on_page_writeback(page);
401 if (!PageWriteback(page)) {
402 /* synchronous write or broken a_ops? */
403 ClearPageReclaim(page);
405 inc_zone_page_state(page, NR_VMSCAN_WRITE);
413 * Same as remove_mapping, but if the page is removed from the mapping, it
414 * gets returned with a refcount of 0.
416 static int __remove_mapping(struct address_space *mapping, struct page *page)
418 BUG_ON(!PageLocked(page));
419 BUG_ON(mapping != page_mapping(page));
421 spin_lock_irq(&mapping->tree_lock);
423 * The non racy check for a busy page.
425 * Must be careful with the order of the tests. When someone has
426 * a ref to the page, it may be possible that they dirty it then
427 * drop the reference. So if PageDirty is tested before page_count
428 * here, then the following race may occur:
430 * get_user_pages(&page);
431 * [user mapping goes away]
433 * !PageDirty(page) [good]
434 * SetPageDirty(page);
436 * !page_count(page) [good, discard it]
438 * [oops, our write_to data is lost]
440 * Reversing the order of the tests ensures such a situation cannot
441 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
442 * load is not satisfied before that of page->_count.
444 * Note that if SetPageDirty is always performed via set_page_dirty,
445 * and thus under tree_lock, then this ordering is not required.
447 if (!page_freeze_refs(page, 2))
449 /* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
450 if (unlikely(PageDirty(page))) {
451 page_unfreeze_refs(page, 2);
455 if (PageSwapCache(page)) {
456 swp_entry_t swap = { .val = page_private(page) };
457 __delete_from_swap_cache(page);
458 spin_unlock_irq(&mapping->tree_lock);
459 swapcache_free(swap, page);
461 __remove_from_page_cache(page);
462 spin_unlock_irq(&mapping->tree_lock);
463 mem_cgroup_uncharge_cache_page(page);
469 spin_unlock_irq(&mapping->tree_lock);
474 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
475 * someone else has a ref on the page, abort and return 0. If it was
476 * successfully detached, return 1. Assumes the caller has a single ref on
479 int remove_mapping(struct address_space *mapping, struct page *page)
481 if (__remove_mapping(mapping, page)) {
483 * Unfreezing the refcount with 1 rather than 2 effectively
484 * drops the pagecache ref for us without requiring another
487 page_unfreeze_refs(page, 1);
494 * putback_lru_page - put previously isolated page onto appropriate LRU list
495 * @page: page to be put back to appropriate lru list
497 * Add previously isolated @page to appropriate LRU list.
498 * Page may still be unevictable for other reasons.
500 * lru_lock must not be held, interrupts must be enabled.
502 void putback_lru_page(struct page *page)
505 int active = !!TestClearPageActive(page);
506 int was_unevictable = PageUnevictable(page);
508 VM_BUG_ON(PageLRU(page));
511 ClearPageUnevictable(page);
513 if (page_evictable(page, NULL)) {
515 * For evictable pages, we can use the cache.
516 * In event of a race, worst case is we end up with an
517 * unevictable page on [in]active list.
518 * We know how to handle that.
520 lru = active + page_lru_base_type(page);
521 lru_cache_add_lru(page, lru);
524 * Put unevictable pages directly on zone's unevictable
527 lru = LRU_UNEVICTABLE;
528 add_page_to_unevictable_list(page);
530 * When racing with an mlock clearing (page is
531 * unlocked), make sure that if the other thread does
532 * not observe our setting of PG_lru and fails
533 * isolation, we see PG_mlocked cleared below and move
534 * the page back to the evictable list.
536 * The other side is TestClearPageMlocked().
542 * page's status can change while we move it among lru. If an evictable
543 * page is on unevictable list, it never be freed. To avoid that,
544 * check after we added it to the list, again.
546 if (lru == LRU_UNEVICTABLE && page_evictable(page, NULL)) {
547 if (!isolate_lru_page(page)) {
551 /* This means someone else dropped this page from LRU
552 * So, it will be freed or putback to LRU again. There is
553 * nothing to do here.
557 if (was_unevictable && lru != LRU_UNEVICTABLE)
558 count_vm_event(UNEVICTABLE_PGRESCUED);
559 else if (!was_unevictable && lru == LRU_UNEVICTABLE)
560 count_vm_event(UNEVICTABLE_PGCULLED);
562 put_page(page); /* drop ref from isolate */
565 enum page_references {
567 PAGEREF_RECLAIM_CLEAN,
572 static enum page_references page_check_references(struct page *page,
573 struct scan_control *sc)
575 int referenced_ptes, referenced_page;
576 unsigned long vm_flags;
578 referenced_ptes = page_referenced(page, 1, sc->mem_cgroup, &vm_flags);
579 referenced_page = TestClearPageReferenced(page);
581 /* Lumpy reclaim - ignore references */
582 if (sc->lumpy_reclaim_mode)
583 return PAGEREF_RECLAIM;
586 * Mlock lost the isolation race with us. Let try_to_unmap()
587 * move the page to the unevictable list.
589 if (vm_flags & VM_LOCKED)
590 return PAGEREF_RECLAIM;
592 if (referenced_ptes) {
594 return PAGEREF_ACTIVATE;
596 * All mapped pages start out with page table
597 * references from the instantiating fault, so we need
598 * to look twice if a mapped file page is used more
601 * Mark it and spare it for another trip around the
602 * inactive list. Another page table reference will
603 * lead to its activation.
605 * Note: the mark is set for activated pages as well
606 * so that recently deactivated but used pages are
609 SetPageReferenced(page);
612 return PAGEREF_ACTIVATE;
617 /* Reclaim if clean, defer dirty pages to writeback */
619 return PAGEREF_RECLAIM_CLEAN;
621 return PAGEREF_RECLAIM;
625 * shrink_page_list() returns the number of reclaimed pages
627 static unsigned long shrink_page_list(struct list_head *page_list,
628 struct scan_control *sc,
629 enum pageout_io sync_writeback)
631 LIST_HEAD(ret_pages);
632 struct pagevec freed_pvec;
634 unsigned long nr_reclaimed = 0;
638 pagevec_init(&freed_pvec, 1);
639 while (!list_empty(page_list)) {
640 enum page_references references;
641 struct address_space *mapping;
647 page = lru_to_page(page_list);
648 list_del(&page->lru);
650 if (!trylock_page(page))
653 VM_BUG_ON(PageActive(page));
657 if (unlikely(!page_evictable(page, NULL)))
660 if (!sc->may_unmap && page_mapped(page))
663 /* Double the slab pressure for mapped and swapcache pages */
664 if (page_mapped(page) || PageSwapCache(page))
667 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
668 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
670 if (PageWriteback(page)) {
672 * Synchronous reclaim is performed in two passes,
673 * first an asynchronous pass over the list to
674 * start parallel writeback, and a second synchronous
675 * pass to wait for the IO to complete. Wait here
676 * for any page for which writeback has already
679 if (sync_writeback == PAGEOUT_IO_SYNC && may_enter_fs)
680 wait_on_page_writeback(page);
685 references = page_check_references(page, sc);
686 switch (references) {
687 case PAGEREF_ACTIVATE:
688 goto activate_locked;
691 case PAGEREF_RECLAIM:
692 case PAGEREF_RECLAIM_CLEAN:
693 ; /* try to reclaim the page below */
697 * Anonymous process memory has backing store?
698 * Try to allocate it some swap space here.
700 if (PageAnon(page) && !PageSwapCache(page)) {
701 if (!(sc->gfp_mask & __GFP_IO))
703 if (!add_to_swap(page))
704 goto activate_locked;
708 mapping = page_mapping(page);
711 * The page is mapped into the page tables of one or more
712 * processes. Try to unmap it here.
714 if (page_mapped(page) && mapping) {
715 switch (try_to_unmap(page, TTU_UNMAP)) {
717 goto activate_locked;
723 ; /* try to free the page below */
727 if (PageDirty(page)) {
728 if (references == PAGEREF_RECLAIM_CLEAN)
732 if (!sc->may_writepage)
735 /* Page is dirty, try to write it out here */
736 switch (pageout(page, mapping, sync_writeback)) {
740 goto activate_locked;
742 if (PageWriteback(page) || PageDirty(page))
745 * A synchronous write - probably a ramdisk. Go
746 * ahead and try to reclaim the page.
748 if (!trylock_page(page))
750 if (PageDirty(page) || PageWriteback(page))
752 mapping = page_mapping(page);
754 ; /* try to free the page below */
759 * If the page has buffers, try to free the buffer mappings
760 * associated with this page. If we succeed we try to free
763 * We do this even if the page is PageDirty().
764 * try_to_release_page() does not perform I/O, but it is
765 * possible for a page to have PageDirty set, but it is actually
766 * clean (all its buffers are clean). This happens if the
767 * buffers were written out directly, with submit_bh(). ext3
768 * will do this, as well as the blockdev mapping.
769 * try_to_release_page() will discover that cleanness and will
770 * drop the buffers and mark the page clean - it can be freed.
772 * Rarely, pages can have buffers and no ->mapping. These are
773 * the pages which were not successfully invalidated in
774 * truncate_complete_page(). We try to drop those buffers here
775 * and if that worked, and the page is no longer mapped into
776 * process address space (page_count == 1) it can be freed.
777 * Otherwise, leave the page on the LRU so it is swappable.
779 if (page_has_private(page)) {
780 if (!try_to_release_page(page, sc->gfp_mask))
781 goto activate_locked;
782 if (!mapping && page_count(page) == 1) {
784 if (put_page_testzero(page))
788 * rare race with speculative reference.
789 * the speculative reference will free
790 * this page shortly, so we may
791 * increment nr_reclaimed here (and
792 * leave it off the LRU).
800 if (!mapping || !__remove_mapping(mapping, page))
804 * At this point, we have no other references and there is
805 * no way to pick any more up (removed from LRU, removed
806 * from pagecache). Can use non-atomic bitops now (and
807 * we obviously don't have to worry about waking up a process
808 * waiting on the page lock, because there are no references.
810 __clear_page_locked(page);
813 if (!pagevec_add(&freed_pvec, page)) {
814 __pagevec_free(&freed_pvec);
815 pagevec_reinit(&freed_pvec);
820 if (PageSwapCache(page))
821 try_to_free_swap(page);
823 putback_lru_page(page);
827 /* Not a candidate for swapping, so reclaim swap space. */
828 if (PageSwapCache(page) && vm_swap_full())
829 try_to_free_swap(page);
830 VM_BUG_ON(PageActive(page));
836 list_add(&page->lru, &ret_pages);
837 VM_BUG_ON(PageLRU(page) || PageUnevictable(page));
839 list_splice(&ret_pages, page_list);
840 if (pagevec_count(&freed_pvec))
841 __pagevec_free(&freed_pvec);
842 count_vm_events(PGACTIVATE, pgactivate);
847 * Attempt to remove the specified page from its LRU. Only take this page
848 * if it is of the appropriate PageActive status. Pages which are being
849 * freed elsewhere are also ignored.
851 * page: page to consider
852 * mode: one of the LRU isolation modes defined above
854 * returns 0 on success, -ve errno on failure.
856 int __isolate_lru_page(struct page *page, int mode, int file)
860 /* Only take pages on the LRU. */
865 * When checking the active state, we need to be sure we are
866 * dealing with comparible boolean values. Take the logical not
869 if (mode != ISOLATE_BOTH && (!PageActive(page) != !mode))
872 if (mode != ISOLATE_BOTH && page_is_file_cache(page) != file)
876 * When this function is being called for lumpy reclaim, we
877 * initially look into all LRU pages, active, inactive and
878 * unevictable; only give shrink_page_list evictable pages.
880 if (PageUnevictable(page))
885 if (likely(get_page_unless_zero(page))) {
887 * Be careful not to clear PageLRU until after we're
888 * sure the page is not being freed elsewhere -- the
889 * page release code relies on it.
899 * zone->lru_lock is heavily contended. Some of the functions that
900 * shrink the lists perform better by taking out a batch of pages
901 * and working on them outside the LRU lock.
903 * For pagecache intensive workloads, this function is the hottest
904 * spot in the kernel (apart from copy_*_user functions).
906 * Appropriate locks must be held before calling this function.
908 * @nr_to_scan: The number of pages to look through on the list.
909 * @src: The LRU list to pull pages off.
910 * @dst: The temp list to put pages on to.
911 * @scanned: The number of pages that were scanned.
912 * @order: The caller's attempted allocation order
913 * @mode: One of the LRU isolation modes
914 * @file: True [1] if isolating file [!anon] pages
916 * returns how many pages were moved onto *@dst.
918 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
919 struct list_head *src, struct list_head *dst,
920 unsigned long *scanned, int order, int mode, int file)
922 unsigned long nr_taken = 0;
925 for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
928 unsigned long end_pfn;
929 unsigned long page_pfn;
932 page = lru_to_page(src);
933 prefetchw_prev_lru_page(page, src, flags);
935 VM_BUG_ON(!PageLRU(page));
937 switch (__isolate_lru_page(page, mode, file)) {
939 list_move(&page->lru, dst);
940 mem_cgroup_del_lru(page);
945 /* else it is being freed elsewhere */
946 list_move(&page->lru, src);
947 mem_cgroup_rotate_lru_list(page, page_lru(page));
958 * Attempt to take all pages in the order aligned region
959 * surrounding the tag page. Only take those pages of
960 * the same active state as that tag page. We may safely
961 * round the target page pfn down to the requested order
962 * as the mem_map is guarenteed valid out to MAX_ORDER,
963 * where that page is in a different zone we will detect
964 * it from its zone id and abort this block scan.
966 zone_id = page_zone_id(page);
967 page_pfn = page_to_pfn(page);
968 pfn = page_pfn & ~((1 << order) - 1);
969 end_pfn = pfn + (1 << order);
970 for (; pfn < end_pfn; pfn++) {
971 struct page *cursor_page;
973 /* The target page is in the block, ignore it. */
974 if (unlikely(pfn == page_pfn))
977 /* Avoid holes within the zone. */
978 if (unlikely(!pfn_valid_within(pfn)))
981 cursor_page = pfn_to_page(pfn);
983 /* Check that we have not crossed a zone boundary. */
984 if (unlikely(page_zone_id(cursor_page) != zone_id))
988 * If we don't have enough swap space, reclaiming of
989 * anon page which don't already have a swap slot is
992 if (nr_swap_pages <= 0 && PageAnon(cursor_page) &&
993 !PageSwapCache(cursor_page))
996 if (__isolate_lru_page(cursor_page, mode, file) == 0) {
997 list_move(&cursor_page->lru, dst);
998 mem_cgroup_del_lru(cursor_page);
1009 static unsigned long isolate_pages_global(unsigned long nr,
1010 struct list_head *dst,
1011 unsigned long *scanned, int order,
1012 int mode, struct zone *z,
1013 struct mem_cgroup *mem_cont,
1014 int active, int file)
1021 return isolate_lru_pages(nr, &z->lru[lru].list, dst, scanned, order,
1026 * clear_active_flags() is a helper for shrink_active_list(), clearing
1027 * any active bits from the pages in the list.
1029 static unsigned long clear_active_flags(struct list_head *page_list,
1030 unsigned int *count)
1036 list_for_each_entry(page, page_list, lru) {
1037 lru = page_lru_base_type(page);
1038 if (PageActive(page)) {
1040 ClearPageActive(page);
1050 * isolate_lru_page - tries to isolate a page from its LRU list
1051 * @page: page to isolate from its LRU list
1053 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
1054 * vmstat statistic corresponding to whatever LRU list the page was on.
1056 * Returns 0 if the page was removed from an LRU list.
1057 * Returns -EBUSY if the page was not on an LRU list.
1059 * The returned page will have PageLRU() cleared. If it was found on
1060 * the active list, it will have PageActive set. If it was found on
1061 * the unevictable list, it will have the PageUnevictable bit set. That flag
1062 * may need to be cleared by the caller before letting the page go.
1064 * The vmstat statistic corresponding to the list on which the page was
1065 * found will be decremented.
1068 * (1) Must be called with an elevated refcount on the page. This is a
1069 * fundamentnal difference from isolate_lru_pages (which is called
1070 * without a stable reference).
1071 * (2) the lru_lock must not be held.
1072 * (3) interrupts must be enabled.
1074 int isolate_lru_page(struct page *page)
1078 if (PageLRU(page)) {
1079 struct zone *zone = page_zone(page);
1081 spin_lock_irq(&zone->lru_lock);
1082 if (PageLRU(page) && get_page_unless_zero(page)) {
1083 int lru = page_lru(page);
1087 del_page_from_lru_list(zone, page, lru);
1089 spin_unlock_irq(&zone->lru_lock);
1095 * Are there way too many processes in the direct reclaim path already?
1097 static int too_many_isolated(struct zone *zone, int file,
1098 struct scan_control *sc)
1100 unsigned long inactive, isolated;
1102 if (current_is_kswapd())
1105 if (!scanning_global_lru(sc))
1109 inactive = zone_page_state(zone, NR_INACTIVE_FILE);
1110 isolated = zone_page_state(zone, NR_ISOLATED_FILE);
1112 inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1113 isolated = zone_page_state(zone, NR_ISOLATED_ANON);
1116 return isolated > inactive;
1120 * shrink_inactive_list() is a helper for shrink_zone(). It returns the number
1121 * of reclaimed pages
1123 static unsigned long shrink_inactive_list(unsigned long max_scan,
1124 struct zone *zone, struct scan_control *sc,
1125 int priority, int file)
1127 LIST_HEAD(page_list);
1128 struct pagevec pvec;
1129 unsigned long nr_scanned = 0;
1130 unsigned long nr_reclaimed = 0;
1131 struct zone_reclaim_stat *reclaim_stat = get_reclaim_stat(zone, sc);
1133 while (unlikely(too_many_isolated(zone, file, sc))) {
1134 congestion_wait(BLK_RW_ASYNC, HZ/10);
1136 /* We are about to die and free our memory. Return now. */
1137 if (fatal_signal_pending(current))
1138 return SWAP_CLUSTER_MAX;
1142 pagevec_init(&pvec, 1);
1145 spin_lock_irq(&zone->lru_lock);
1148 unsigned long nr_taken;
1149 unsigned long nr_scan;
1150 unsigned long nr_freed;
1151 unsigned long nr_active;
1152 unsigned int count[NR_LRU_LISTS] = { 0, };
1153 int mode = sc->lumpy_reclaim_mode ? ISOLATE_BOTH : ISOLATE_INACTIVE;
1154 unsigned long nr_anon;
1155 unsigned long nr_file;
1157 nr_taken = sc->isolate_pages(SWAP_CLUSTER_MAX,
1158 &page_list, &nr_scan, sc->order, mode,
1159 zone, sc->mem_cgroup, 0, file);
1161 if (scanning_global_lru(sc)) {
1162 zone->pages_scanned += nr_scan;
1163 if (current_is_kswapd())
1164 __count_zone_vm_events(PGSCAN_KSWAPD, zone,
1167 __count_zone_vm_events(PGSCAN_DIRECT, zone,
1174 nr_active = clear_active_flags(&page_list, count);
1175 __count_vm_events(PGDEACTIVATE, nr_active);
1177 __mod_zone_page_state(zone, NR_ACTIVE_FILE,
1178 -count[LRU_ACTIVE_FILE]);
1179 __mod_zone_page_state(zone, NR_INACTIVE_FILE,
1180 -count[LRU_INACTIVE_FILE]);
1181 __mod_zone_page_state(zone, NR_ACTIVE_ANON,
1182 -count[LRU_ACTIVE_ANON]);
1183 __mod_zone_page_state(zone, NR_INACTIVE_ANON,
1184 -count[LRU_INACTIVE_ANON]);
1186 nr_anon = count[LRU_ACTIVE_ANON] + count[LRU_INACTIVE_ANON];
1187 nr_file = count[LRU_ACTIVE_FILE] + count[LRU_INACTIVE_FILE];
1188 __mod_zone_page_state(zone, NR_ISOLATED_ANON, nr_anon);
1189 __mod_zone_page_state(zone, NR_ISOLATED_FILE, nr_file);
1191 reclaim_stat->recent_scanned[0] += nr_anon;
1192 reclaim_stat->recent_scanned[1] += nr_file;
1194 spin_unlock_irq(&zone->lru_lock);
1196 nr_scanned += nr_scan;
1197 nr_freed = shrink_page_list(&page_list, sc, PAGEOUT_IO_ASYNC);
1200 * If we are direct reclaiming for contiguous pages and we do
1201 * not reclaim everything in the list, try again and wait
1202 * for IO to complete. This will stall high-order allocations
1203 * but that should be acceptable to the caller
1205 if (nr_freed < nr_taken && !current_is_kswapd() &&
1206 sc->lumpy_reclaim_mode) {
1207 congestion_wait(BLK_RW_ASYNC, HZ/10);
1210 * The attempt at page out may have made some
1211 * of the pages active, mark them inactive again.
1213 nr_active = clear_active_flags(&page_list, count);
1214 count_vm_events(PGDEACTIVATE, nr_active);
1216 nr_freed += shrink_page_list(&page_list, sc,
1220 nr_reclaimed += nr_freed;
1222 local_irq_disable();
1223 if (current_is_kswapd())
1224 __count_vm_events(KSWAPD_STEAL, nr_freed);
1225 __count_zone_vm_events(PGSTEAL, zone, nr_freed);
1227 spin_lock(&zone->lru_lock);
1229 * Put back any unfreeable pages.
1231 while (!list_empty(&page_list)) {
1233 page = lru_to_page(&page_list);
1234 VM_BUG_ON(PageLRU(page));
1235 list_del(&page->lru);
1236 if (unlikely(!page_evictable(page, NULL))) {
1237 spin_unlock_irq(&zone->lru_lock);
1238 putback_lru_page(page);
1239 spin_lock_irq(&zone->lru_lock);
1243 lru = page_lru(page);
1244 add_page_to_lru_list(zone, page, lru);
1245 if (is_active_lru(lru)) {
1246 int file = is_file_lru(lru);
1247 reclaim_stat->recent_rotated[file]++;
1249 if (!pagevec_add(&pvec, page)) {
1250 spin_unlock_irq(&zone->lru_lock);
1251 __pagevec_release(&pvec);
1252 spin_lock_irq(&zone->lru_lock);
1255 __mod_zone_page_state(zone, NR_ISOLATED_ANON, -nr_anon);
1256 __mod_zone_page_state(zone, NR_ISOLATED_FILE, -nr_file);
1258 } while (nr_scanned < max_scan);
1261 spin_unlock_irq(&zone->lru_lock);
1262 pagevec_release(&pvec);
1263 return nr_reclaimed;
1267 * We are about to scan this zone at a certain priority level. If that priority
1268 * level is smaller (ie: more urgent) than the previous priority, then note
1269 * that priority level within the zone. This is done so that when the next
1270 * process comes in to scan this zone, it will immediately start out at this
1271 * priority level rather than having to build up its own scanning priority.
1272 * Here, this priority affects only the reclaim-mapped threshold.
1274 static inline void note_zone_scanning_priority(struct zone *zone, int priority)
1276 if (priority < zone->prev_priority)
1277 zone->prev_priority = priority;
1281 * This moves pages from the active list to the inactive list.
1283 * We move them the other way if the page is referenced by one or more
1284 * processes, from rmap.
1286 * If the pages are mostly unmapped, the processing is fast and it is
1287 * appropriate to hold zone->lru_lock across the whole operation. But if
1288 * the pages are mapped, the processing is slow (page_referenced()) so we
1289 * should drop zone->lru_lock around each page. It's impossible to balance
1290 * this, so instead we remove the pages from the LRU while processing them.
1291 * It is safe to rely on PG_active against the non-LRU pages in here because
1292 * nobody will play with that bit on a non-LRU page.
1294 * The downside is that we have to touch page->_count against each page.
1295 * But we had to alter page->flags anyway.
1298 static void move_active_pages_to_lru(struct zone *zone,
1299 struct list_head *list,
1302 unsigned long pgmoved = 0;
1303 struct pagevec pvec;
1306 pagevec_init(&pvec, 1);
1308 while (!list_empty(list)) {
1309 page = lru_to_page(list);
1311 VM_BUG_ON(PageLRU(page));
1314 list_move(&page->lru, &zone->lru[lru].list);
1315 mem_cgroup_add_lru_list(page, lru);
1318 if (!pagevec_add(&pvec, page) || list_empty(list)) {
1319 spin_unlock_irq(&zone->lru_lock);
1320 if (buffer_heads_over_limit)
1321 pagevec_strip(&pvec);
1322 __pagevec_release(&pvec);
1323 spin_lock_irq(&zone->lru_lock);
1326 __mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved);
1327 if (!is_active_lru(lru))
1328 __count_vm_events(PGDEACTIVATE, pgmoved);
1331 static void shrink_active_list(unsigned long nr_pages, struct zone *zone,
1332 struct scan_control *sc, int priority, int file)
1334 unsigned long nr_taken;
1335 unsigned long pgscanned;
1336 unsigned long vm_flags;
1337 LIST_HEAD(l_hold); /* The pages which were snipped off */
1338 LIST_HEAD(l_active);
1339 LIST_HEAD(l_inactive);
1341 struct zone_reclaim_stat *reclaim_stat = get_reclaim_stat(zone, sc);
1342 unsigned long nr_rotated = 0;
1345 spin_lock_irq(&zone->lru_lock);
1346 nr_taken = sc->isolate_pages(nr_pages, &l_hold, &pgscanned, sc->order,
1347 ISOLATE_ACTIVE, zone,
1348 sc->mem_cgroup, 1, file);
1350 * zone->pages_scanned is used for detect zone's oom
1351 * mem_cgroup remembers nr_scan by itself.
1353 if (scanning_global_lru(sc)) {
1354 zone->pages_scanned += pgscanned;
1356 reclaim_stat->recent_scanned[file] += nr_taken;
1358 __count_zone_vm_events(PGREFILL, zone, pgscanned);
1360 __mod_zone_page_state(zone, NR_ACTIVE_FILE, -nr_taken);
1362 __mod_zone_page_state(zone, NR_ACTIVE_ANON, -nr_taken);
1363 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
1364 spin_unlock_irq(&zone->lru_lock);
1366 while (!list_empty(&l_hold)) {
1368 page = lru_to_page(&l_hold);
1369 list_del(&page->lru);
1371 if (unlikely(!page_evictable(page, NULL))) {
1372 putback_lru_page(page);
1376 if (page_referenced(page, 0, sc->mem_cgroup, &vm_flags)) {
1379 * Identify referenced, file-backed active pages and
1380 * give them one more trip around the active list. So
1381 * that executable code get better chances to stay in
1382 * memory under moderate memory pressure. Anon pages
1383 * are not likely to be evicted by use-once streaming
1384 * IO, plus JVM can create lots of anon VM_EXEC pages,
1385 * so we ignore them here.
1387 if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
1388 list_add(&page->lru, &l_active);
1393 ClearPageActive(page); /* we are de-activating */
1394 list_add(&page->lru, &l_inactive);
1398 * Move pages back to the lru list.
1400 spin_lock_irq(&zone->lru_lock);
1402 * Count referenced pages from currently used mappings as rotated,
1403 * even though only some of them are actually re-activated. This
1404 * helps balance scan pressure between file and anonymous pages in
1407 reclaim_stat->recent_rotated[file] += nr_rotated;
1409 move_active_pages_to_lru(zone, &l_active,
1410 LRU_ACTIVE + file * LRU_FILE);
1411 move_active_pages_to_lru(zone, &l_inactive,
1412 LRU_BASE + file * LRU_FILE);
1413 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1414 spin_unlock_irq(&zone->lru_lock);
1417 static int inactive_anon_is_low_global(struct zone *zone)
1419 unsigned long active, inactive;
1421 active = zone_page_state(zone, NR_ACTIVE_ANON);
1422 inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1424 if (inactive * zone->inactive_ratio < active)
1431 * inactive_anon_is_low - check if anonymous pages need to be deactivated
1432 * @zone: zone to check
1433 * @sc: scan control of this context
1435 * Returns true if the zone does not have enough inactive anon pages,
1436 * meaning some active anon pages need to be deactivated.
1438 static int inactive_anon_is_low(struct zone *zone, struct scan_control *sc)
1442 if (scanning_global_lru(sc))
1443 low = inactive_anon_is_low_global(zone);
1445 low = mem_cgroup_inactive_anon_is_low(sc->mem_cgroup);
1449 static int inactive_file_is_low_global(struct zone *zone)
1451 unsigned long active, inactive;
1453 active = zone_page_state(zone, NR_ACTIVE_FILE);
1454 inactive = zone_page_state(zone, NR_INACTIVE_FILE);
1456 return (active > inactive);
1460 * inactive_file_is_low - check if file pages need to be deactivated
1461 * @zone: zone to check
1462 * @sc: scan control of this context
1464 * When the system is doing streaming IO, memory pressure here
1465 * ensures that active file pages get deactivated, until more
1466 * than half of the file pages are on the inactive list.
1468 * Once we get to that situation, protect the system's working
1469 * set from being evicted by disabling active file page aging.
1471 * This uses a different ratio than the anonymous pages, because
1472 * the page cache uses a use-once replacement algorithm.
1474 static int inactive_file_is_low(struct zone *zone, struct scan_control *sc)
1478 if (scanning_global_lru(sc))
1479 low = inactive_file_is_low_global(zone);
1481 low = mem_cgroup_inactive_file_is_low(sc->mem_cgroup);
1485 static int inactive_list_is_low(struct zone *zone, struct scan_control *sc,
1489 return inactive_file_is_low(zone, sc);
1491 return inactive_anon_is_low(zone, sc);
1494 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
1495 struct zone *zone, struct scan_control *sc, int priority)
1497 int file = is_file_lru(lru);
1499 if (is_active_lru(lru)) {
1500 if (inactive_list_is_low(zone, sc, file))
1501 shrink_active_list(nr_to_scan, zone, sc, priority, file);
1505 return shrink_inactive_list(nr_to_scan, zone, sc, priority, file);
1509 * Smallish @nr_to_scan's are deposited in @nr_saved_scan,
1510 * until we collected @swap_cluster_max pages to scan.
1512 static unsigned long nr_scan_try_batch(unsigned long nr_to_scan,
1513 unsigned long *nr_saved_scan)
1517 *nr_saved_scan += nr_to_scan;
1518 nr = *nr_saved_scan;
1520 if (nr >= SWAP_CLUSTER_MAX)
1529 * Determine how aggressively the anon and file LRU lists should be
1530 * scanned. The relative value of each set of LRU lists is determined
1531 * by looking at the fraction of the pages scanned we did rotate back
1532 * onto the active list instead of evict.
1534 * nr[0] = anon pages to scan; nr[1] = file pages to scan
1536 static void get_scan_count(struct zone *zone, struct scan_control *sc,
1537 unsigned long *nr, int priority)
1539 unsigned long anon, file, free;
1540 unsigned long anon_prio, file_prio;
1541 unsigned long ap, fp;
1542 struct zone_reclaim_stat *reclaim_stat = get_reclaim_stat(zone, sc);
1543 u64 fraction[2], denominator;
1547 /* If we have no swap space, do not bother scanning anon pages. */
1548 if (!sc->may_swap || (nr_swap_pages <= 0)) {
1556 anon = zone_nr_lru_pages(zone, sc, LRU_ACTIVE_ANON) +
1557 zone_nr_lru_pages(zone, sc, LRU_INACTIVE_ANON);
1558 file = zone_nr_lru_pages(zone, sc, LRU_ACTIVE_FILE) +
1559 zone_nr_lru_pages(zone, sc, LRU_INACTIVE_FILE);
1561 if (scanning_global_lru(sc)) {
1562 free = zone_page_state(zone, NR_FREE_PAGES);
1563 /* If we have very few page cache pages,
1564 force-scan anon pages. */
1565 if (unlikely(file + free <= high_wmark_pages(zone))) {
1574 * OK, so we have swap space and a fair amount of page cache
1575 * pages. We use the recently rotated / recently scanned
1576 * ratios to determine how valuable each cache is.
1578 * Because workloads change over time (and to avoid overflow)
1579 * we keep these statistics as a floating average, which ends
1580 * up weighing recent references more than old ones.
1582 * anon in [0], file in [1]
1584 if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
1585 spin_lock_irq(&zone->lru_lock);
1586 reclaim_stat->recent_scanned[0] /= 2;
1587 reclaim_stat->recent_rotated[0] /= 2;
1588 spin_unlock_irq(&zone->lru_lock);
1591 if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
1592 spin_lock_irq(&zone->lru_lock);
1593 reclaim_stat->recent_scanned[1] /= 2;
1594 reclaim_stat->recent_rotated[1] /= 2;
1595 spin_unlock_irq(&zone->lru_lock);
1599 * With swappiness at 100, anonymous and file have the same priority.
1600 * This scanning priority is essentially the inverse of IO cost.
1602 anon_prio = sc->swappiness;
1603 file_prio = 200 - sc->swappiness;
1606 * The amount of pressure on anon vs file pages is inversely
1607 * proportional to the fraction of recently scanned pages on
1608 * each list that were recently referenced and in active use.
1610 ap = (anon_prio + 1) * (reclaim_stat->recent_scanned[0] + 1);
1611 ap /= reclaim_stat->recent_rotated[0] + 1;
1613 fp = (file_prio + 1) * (reclaim_stat->recent_scanned[1] + 1);
1614 fp /= reclaim_stat->recent_rotated[1] + 1;
1618 denominator = ap + fp + 1;
1620 for_each_evictable_lru(l) {
1621 int file = is_file_lru(l);
1624 scan = zone_nr_lru_pages(zone, sc, l);
1625 if (priority || noswap) {
1627 scan = div64_u64(scan * fraction[file], denominator);
1629 nr[l] = nr_scan_try_batch(scan,
1630 &reclaim_stat->nr_saved_scan[l]);
1634 static void set_lumpy_reclaim_mode(int priority, struct scan_control *sc)
1637 * If we need a large contiguous chunk of memory, or have
1638 * trouble getting a small set of contiguous pages, we
1639 * will reclaim both active and inactive pages.
1641 if (sc->order > PAGE_ALLOC_COSTLY_ORDER)
1642 sc->lumpy_reclaim_mode = 1;
1643 else if (sc->order && priority < DEF_PRIORITY - 2)
1644 sc->lumpy_reclaim_mode = 1;
1646 sc->lumpy_reclaim_mode = 0;
1650 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
1652 static void shrink_zone(int priority, struct zone *zone,
1653 struct scan_control *sc)
1655 unsigned long nr[NR_LRU_LISTS];
1656 unsigned long nr_to_scan;
1658 unsigned long nr_reclaimed = sc->nr_reclaimed;
1659 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
1661 get_scan_count(zone, sc, nr, priority);
1663 set_lumpy_reclaim_mode(priority, sc);
1665 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
1666 nr[LRU_INACTIVE_FILE]) {
1667 for_each_evictable_lru(l) {
1669 nr_to_scan = min_t(unsigned long,
1670 nr[l], SWAP_CLUSTER_MAX);
1671 nr[l] -= nr_to_scan;
1673 nr_reclaimed += shrink_list(l, nr_to_scan,
1674 zone, sc, priority);
1678 * On large memory systems, scan >> priority can become
1679 * really large. This is fine for the starting priority;
1680 * we want to put equal scanning pressure on each zone.
1681 * However, if the VM has a harder time of freeing pages,
1682 * with multiple processes reclaiming pages, the total
1683 * freeing target can get unreasonably large.
1685 if (nr_reclaimed >= nr_to_reclaim && priority < DEF_PRIORITY)
1689 sc->nr_reclaimed = nr_reclaimed;
1692 * Even if we did not try to evict anon pages at all, we want to
1693 * rebalance the anon lru active/inactive ratio.
1695 if (inactive_anon_is_low(zone, sc) && nr_swap_pages > 0)
1696 shrink_active_list(SWAP_CLUSTER_MAX, zone, sc, priority, 0);
1698 throttle_vm_writeout(sc->gfp_mask);
1702 * This is the direct reclaim path, for page-allocating processes. We only
1703 * try to reclaim pages from zones which will satisfy the caller's allocation
1706 * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
1708 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
1710 * b) The target zone may be at high_wmark_pages(zone) but the lower zones
1711 * must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
1712 * zone defense algorithm.
1714 * If a zone is deemed to be full of pinned pages then just give it a light
1715 * scan then give up on it.
1717 static int shrink_zones(int priority, struct zonelist *zonelist,
1718 struct scan_control *sc)
1720 enum zone_type high_zoneidx = gfp_zone(sc->gfp_mask);
1725 for_each_zone_zonelist_nodemask(zone, z, zonelist, high_zoneidx,
1727 if (!populated_zone(zone))
1730 * Take care memory controller reclaiming has small influence
1733 if (scanning_global_lru(sc)) {
1734 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1736 note_zone_scanning_priority(zone, priority);
1738 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1739 continue; /* Let kswapd poll it */
1742 * Ignore cpuset limitation here. We just want to reduce
1743 * # of used pages by us regardless of memory shortage.
1745 mem_cgroup_note_reclaim_priority(sc->mem_cgroup,
1749 shrink_zone(priority, zone, sc);
1756 * This is the main entry point to direct page reclaim.
1758 * If a full scan of the inactive list fails to free enough memory then we
1759 * are "out of memory" and something needs to be killed.
1761 * If the caller is !__GFP_FS then the probability of a failure is reasonably
1762 * high - the zone may be full of dirty or under-writeback pages, which this
1763 * caller can't do much about. We kick the writeback threads and take explicit
1764 * naps in the hope that some of these pages can be written. But if the
1765 * allocating task holds filesystem locks which prevent writeout this might not
1766 * work, and the allocation attempt will fail.
1768 * returns: 0, if no pages reclaimed
1769 * else, the number of pages reclaimed
1771 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
1772 struct scan_control *sc)
1775 unsigned long ret = 0;
1776 unsigned long total_scanned = 0;
1777 struct reclaim_state *reclaim_state = current->reclaim_state;
1778 unsigned long lru_pages = 0;
1781 enum zone_type high_zoneidx = gfp_zone(sc->gfp_mask);
1782 unsigned long writeback_threshold;
1785 delayacct_freepages_start();
1787 if (scanning_global_lru(sc))
1788 count_vm_event(ALLOCSTALL);
1790 * mem_cgroup will not do shrink_slab.
1792 if (scanning_global_lru(sc)) {
1793 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
1795 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1798 lru_pages += zone_reclaimable_pages(zone);
1802 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1805 disable_swap_token();
1806 ret = shrink_zones(priority, zonelist, sc);
1808 * Don't shrink slabs when reclaiming memory from
1809 * over limit cgroups
1811 if (scanning_global_lru(sc)) {
1812 shrink_slab(sc->nr_scanned, sc->gfp_mask, lru_pages);
1813 if (reclaim_state) {
1814 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
1815 reclaim_state->reclaimed_slab = 0;
1818 total_scanned += sc->nr_scanned;
1819 if (sc->nr_reclaimed >= sc->nr_to_reclaim) {
1820 ret = sc->nr_reclaimed;
1825 * Try to write back as many pages as we just scanned. This
1826 * tends to cause slow streaming writers to write data to the
1827 * disk smoothly, at the dirtying rate, which is nice. But
1828 * that's undesirable in laptop mode, where we *want* lumpy
1829 * writeout. So in laptop mode, write out the whole world.
1831 writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
1832 if (total_scanned > writeback_threshold) {
1833 wakeup_flusher_threads(laptop_mode ? 0 : total_scanned);
1834 sc->may_writepage = 1;
1837 /* Take a nap, wait for some writeback to complete */
1838 if (!sc->hibernation_mode && sc->nr_scanned &&
1839 priority < DEF_PRIORITY - 2)
1840 congestion_wait(BLK_RW_ASYNC, HZ/10);
1842 /* top priority shrink_zones still had more to do? don't OOM, then */
1843 if (ret && scanning_global_lru(sc))
1844 ret = sc->nr_reclaimed;
1847 * Now that we've scanned all the zones at this priority level, note
1848 * that level within the zone so that the next thread which performs
1849 * scanning of this zone will immediately start out at this priority
1850 * level. This affects only the decision whether or not to bring
1851 * mapped pages onto the inactive list.
1856 if (scanning_global_lru(sc)) {
1857 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
1859 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1862 zone->prev_priority = priority;
1865 mem_cgroup_record_reclaim_priority(sc->mem_cgroup, priority);
1867 delayacct_freepages_end();
1873 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
1874 gfp_t gfp_mask, nodemask_t *nodemask)
1876 struct scan_control sc = {
1877 .gfp_mask = gfp_mask,
1878 .may_writepage = !laptop_mode,
1879 .nr_to_reclaim = SWAP_CLUSTER_MAX,
1882 .swappiness = vm_swappiness,
1885 .isolate_pages = isolate_pages_global,
1886 .nodemask = nodemask,
1889 return do_try_to_free_pages(zonelist, &sc);
1892 #ifdef CONFIG_CGROUP_MEM_RES_CTLR
1894 unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *mem,
1895 gfp_t gfp_mask, bool noswap,
1896 unsigned int swappiness,
1897 struct zone *zone, int nid)
1899 struct scan_control sc = {
1900 .may_writepage = !laptop_mode,
1902 .may_swap = !noswap,
1903 .swappiness = swappiness,
1906 .isolate_pages = mem_cgroup_isolate_pages,
1908 nodemask_t nm = nodemask_of_node(nid);
1910 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
1911 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
1913 sc.nr_reclaimed = 0;
1916 * NOTE: Although we can get the priority field, using it
1917 * here is not a good idea, since it limits the pages we can scan.
1918 * if we don't reclaim here, the shrink_zone from balance_pgdat
1919 * will pick up pages from other mem cgroup's as well. We hack
1920 * the priority and make it zero.
1922 shrink_zone(0, zone, &sc);
1923 return sc.nr_reclaimed;
1926 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *mem_cont,
1929 unsigned int swappiness)
1931 struct zonelist *zonelist;
1932 struct scan_control sc = {
1933 .may_writepage = !laptop_mode,
1935 .may_swap = !noswap,
1936 .nr_to_reclaim = SWAP_CLUSTER_MAX,
1937 .swappiness = swappiness,
1939 .mem_cgroup = mem_cont,
1940 .isolate_pages = mem_cgroup_isolate_pages,
1941 .nodemask = NULL, /* we don't care the placement */
1944 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
1945 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
1946 zonelist = NODE_DATA(numa_node_id())->node_zonelists;
1947 return do_try_to_free_pages(zonelist, &sc);
1951 /* is kswapd sleeping prematurely? */
1952 static int sleeping_prematurely(pg_data_t *pgdat, int order, long remaining)
1956 /* If a direct reclaimer woke kswapd within HZ/10, it's premature */
1960 /* If after HZ/10, a zone is below the high mark, it's premature */
1961 for (i = 0; i < pgdat->nr_zones; i++) {
1962 struct zone *zone = pgdat->node_zones + i;
1964 if (!populated_zone(zone))
1967 if (zone->all_unreclaimable)
1970 if (!zone_watermark_ok(zone, order, high_wmark_pages(zone),
1979 * For kswapd, balance_pgdat() will work across all this node's zones until
1980 * they are all at high_wmark_pages(zone).
1982 * Returns the number of pages which were actually freed.
1984 * There is special handling here for zones which are full of pinned pages.
1985 * This can happen if the pages are all mlocked, or if they are all used by
1986 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
1987 * What we do is to detect the case where all pages in the zone have been
1988 * scanned twice and there has been zero successful reclaim. Mark the zone as
1989 * dead and from now on, only perform a short scan. Basically we're polling
1990 * the zone for when the problem goes away.
1992 * kswapd scans the zones in the highmem->normal->dma direction. It skips
1993 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
1994 * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
1995 * lower zones regardless of the number of free pages in the lower zones. This
1996 * interoperates with the page allocator fallback scheme to ensure that aging
1997 * of pages is balanced across the zones.
1999 static unsigned long balance_pgdat(pg_data_t *pgdat, int order)
2004 unsigned long total_scanned;
2005 struct reclaim_state *reclaim_state = current->reclaim_state;
2006 struct scan_control sc = {
2007 .gfp_mask = GFP_KERNEL,
2011 * kswapd doesn't want to be bailed out while reclaim. because
2012 * we want to put equal scanning pressure on each zone.
2014 .nr_to_reclaim = ULONG_MAX,
2015 .swappiness = vm_swappiness,
2018 .isolate_pages = isolate_pages_global,
2021 * temp_priority is used to remember the scanning priority at which
2022 * this zone was successfully refilled to
2023 * free_pages == high_wmark_pages(zone).
2025 int temp_priority[MAX_NR_ZONES];
2029 sc.nr_reclaimed = 0;
2030 sc.may_writepage = !laptop_mode;
2031 count_vm_event(PAGEOUTRUN);
2033 for (i = 0; i < pgdat->nr_zones; i++)
2034 temp_priority[i] = DEF_PRIORITY;
2036 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
2037 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
2038 unsigned long lru_pages = 0;
2039 int has_under_min_watermark_zone = 0;
2041 /* The swap token gets in the way of swapout... */
2043 disable_swap_token();
2048 * Scan in the highmem->dma direction for the highest
2049 * zone which needs scanning
2051 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
2052 struct zone *zone = pgdat->node_zones + i;
2054 if (!populated_zone(zone))
2057 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
2061 * Do some background aging of the anon list, to give
2062 * pages a chance to be referenced before reclaiming.
2064 if (inactive_anon_is_low(zone, &sc))
2065 shrink_active_list(SWAP_CLUSTER_MAX, zone,
2068 if (!zone_watermark_ok(zone, order,
2069 high_wmark_pages(zone), 0, 0)) {
2077 for (i = 0; i <= end_zone; i++) {
2078 struct zone *zone = pgdat->node_zones + i;
2080 lru_pages += zone_reclaimable_pages(zone);
2084 * Now scan the zone in the dma->highmem direction, stopping
2085 * at the last zone which needs scanning.
2087 * We do this because the page allocator works in the opposite
2088 * direction. This prevents the page allocator from allocating
2089 * pages behind kswapd's direction of progress, which would
2090 * cause too much scanning of the lower zones.
2092 for (i = 0; i <= end_zone; i++) {
2093 struct zone *zone = pgdat->node_zones + i;
2097 if (!populated_zone(zone))
2100 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
2103 temp_priority[i] = priority;
2105 note_zone_scanning_priority(zone, priority);
2107 nid = pgdat->node_id;
2108 zid = zone_idx(zone);
2110 * Call soft limit reclaim before calling shrink_zone.
2111 * For now we ignore the return value
2113 mem_cgroup_soft_limit_reclaim(zone, order, sc.gfp_mask,
2116 * We put equal pressure on every zone, unless one
2117 * zone has way too many pages free already.
2119 if (!zone_watermark_ok(zone, order,
2120 8*high_wmark_pages(zone), end_zone, 0))
2121 shrink_zone(priority, zone, &sc);
2122 reclaim_state->reclaimed_slab = 0;
2123 nr_slab = shrink_slab(sc.nr_scanned, GFP_KERNEL,
2125 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
2126 total_scanned += sc.nr_scanned;
2127 if (zone->all_unreclaimable)
2130 zone->pages_scanned >= (zone_reclaimable_pages(zone) * 6))
2131 zone->all_unreclaimable = 1;
2133 * If we've done a decent amount of scanning and
2134 * the reclaim ratio is low, start doing writepage
2135 * even in laptop mode
2137 if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
2138 total_scanned > sc.nr_reclaimed + sc.nr_reclaimed / 2)
2139 sc.may_writepage = 1;
2141 if (!zone_watermark_ok(zone, order,
2142 high_wmark_pages(zone), end_zone, 0)) {
2145 * We are still under min water mark. This
2146 * means that we have a GFP_ATOMIC allocation
2147 * failure risk. Hurry up!
2149 if (!zone_watermark_ok(zone, order,
2150 min_wmark_pages(zone), end_zone, 0))
2151 has_under_min_watermark_zone = 1;
2156 break; /* kswapd: all done */
2158 * OK, kswapd is getting into trouble. Take a nap, then take
2159 * another pass across the zones.
2161 if (total_scanned && (priority < DEF_PRIORITY - 2)) {
2162 if (has_under_min_watermark_zone)
2163 count_vm_event(KSWAPD_SKIP_CONGESTION_WAIT);
2165 congestion_wait(BLK_RW_ASYNC, HZ/10);
2169 * We do this so kswapd doesn't build up large priorities for
2170 * example when it is freeing in parallel with allocators. It
2171 * matches the direct reclaim path behaviour in terms of impact
2172 * on zone->*_priority.
2174 if (sc.nr_reclaimed >= SWAP_CLUSTER_MAX)
2179 * Note within each zone the priority level at which this zone was
2180 * brought into a happy state. So that the next thread which scans this
2181 * zone will start out at that priority level.
2183 for (i = 0; i < pgdat->nr_zones; i++) {
2184 struct zone *zone = pgdat->node_zones + i;
2186 zone->prev_priority = temp_priority[i];
2188 if (!all_zones_ok) {
2194 * Fragmentation may mean that the system cannot be
2195 * rebalanced for high-order allocations in all zones.
2196 * At this point, if nr_reclaimed < SWAP_CLUSTER_MAX,
2197 * it means the zones have been fully scanned and are still
2198 * not balanced. For high-order allocations, there is
2199 * little point trying all over again as kswapd may
2202 * Instead, recheck all watermarks at order-0 as they
2203 * are the most important. If watermarks are ok, kswapd will go
2204 * back to sleep. High-order users can still perform direct
2205 * reclaim if they wish.
2207 if (sc.nr_reclaimed < SWAP_CLUSTER_MAX)
2208 order = sc.order = 0;
2213 return sc.nr_reclaimed;
2217 * The background pageout daemon, started as a kernel thread
2218 * from the init process.
2220 * This basically trickles out pages so that we have _some_
2221 * free memory available even if there is no other activity
2222 * that frees anything up. This is needed for things like routing
2223 * etc, where we otherwise might have all activity going on in
2224 * asynchronous contexts that cannot page things out.
2226 * If there are applications that are active memory-allocators
2227 * (most normal use), this basically shouldn't matter.
2229 static int kswapd(void *p)
2231 unsigned long order;
2232 pg_data_t *pgdat = (pg_data_t*)p;
2233 struct task_struct *tsk = current;
2235 struct reclaim_state reclaim_state = {
2236 .reclaimed_slab = 0,
2238 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
2240 lockdep_set_current_reclaim_state(GFP_KERNEL);
2242 if (!cpumask_empty(cpumask))
2243 set_cpus_allowed_ptr(tsk, cpumask);
2244 current->reclaim_state = &reclaim_state;
2247 * Tell the memory management that we're a "memory allocator",
2248 * and that if we need more memory we should get access to it
2249 * regardless (see "__alloc_pages()"). "kswapd" should
2250 * never get caught in the normal page freeing logic.
2252 * (Kswapd normally doesn't need memory anyway, but sometimes
2253 * you need a small amount of memory in order to be able to
2254 * page out something else, and this flag essentially protects
2255 * us from recursively trying to free more memory as we're
2256 * trying to free the first piece of memory in the first place).
2258 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
2263 unsigned long new_order;
2266 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
2267 new_order = pgdat->kswapd_max_order;
2268 pgdat->kswapd_max_order = 0;
2269 if (order < new_order) {
2271 * Don't sleep if someone wants a larger 'order'
2276 if (!freezing(current) && !kthread_should_stop()) {
2279 /* Try to sleep for a short interval */
2280 if (!sleeping_prematurely(pgdat, order, remaining)) {
2281 remaining = schedule_timeout(HZ/10);
2282 finish_wait(&pgdat->kswapd_wait, &wait);
2283 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
2287 * After a short sleep, check if it was a
2288 * premature sleep. If not, then go fully
2289 * to sleep until explicitly woken up
2291 if (!sleeping_prematurely(pgdat, order, remaining))
2295 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
2297 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
2301 order = pgdat->kswapd_max_order;
2303 finish_wait(&pgdat->kswapd_wait, &wait);
2305 ret = try_to_freeze();
2306 if (kthread_should_stop())
2310 * We can speed up thawing tasks if we don't call balance_pgdat
2311 * after returning from the refrigerator
2314 balance_pgdat(pgdat, order);
2320 * A zone is low on free memory, so wake its kswapd task to service it.
2322 void wakeup_kswapd(struct zone *zone, int order)
2326 if (!populated_zone(zone))
2329 pgdat = zone->zone_pgdat;
2330 if (zone_watermark_ok(zone, order, low_wmark_pages(zone), 0, 0))
2332 if (pgdat->kswapd_max_order < order)
2333 pgdat->kswapd_max_order = order;
2334 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2336 if (!waitqueue_active(&pgdat->kswapd_wait))
2338 wake_up_interruptible(&pgdat->kswapd_wait);
2342 * The reclaimable count would be mostly accurate.
2343 * The less reclaimable pages may be
2344 * - mlocked pages, which will be moved to unevictable list when encountered
2345 * - mapped pages, which may require several travels to be reclaimed
2346 * - dirty pages, which is not "instantly" reclaimable
2348 unsigned long global_reclaimable_pages(void)
2352 nr = global_page_state(NR_ACTIVE_FILE) +
2353 global_page_state(NR_INACTIVE_FILE);
2355 if (nr_swap_pages > 0)
2356 nr += global_page_state(NR_ACTIVE_ANON) +
2357 global_page_state(NR_INACTIVE_ANON);
2362 unsigned long zone_reclaimable_pages(struct zone *zone)
2366 nr = zone_page_state(zone, NR_ACTIVE_FILE) +
2367 zone_page_state(zone, NR_INACTIVE_FILE);
2369 if (nr_swap_pages > 0)
2370 nr += zone_page_state(zone, NR_ACTIVE_ANON) +
2371 zone_page_state(zone, NR_INACTIVE_ANON);
2376 #ifdef CONFIG_HIBERNATION
2378 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
2381 * Rather than trying to age LRUs the aim is to preserve the overall
2382 * LRU order by reclaiming preferentially
2383 * inactive > active > active referenced > active mapped
2385 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
2387 struct reclaim_state reclaim_state;
2388 struct scan_control sc = {
2389 .gfp_mask = GFP_HIGHUSER_MOVABLE,
2393 .nr_to_reclaim = nr_to_reclaim,
2394 .hibernation_mode = 1,
2395 .swappiness = vm_swappiness,
2397 .isolate_pages = isolate_pages_global,
2399 struct zonelist * zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
2400 struct task_struct *p = current;
2401 unsigned long nr_reclaimed;
2403 p->flags |= PF_MEMALLOC;
2404 lockdep_set_current_reclaim_state(sc.gfp_mask);
2405 reclaim_state.reclaimed_slab = 0;
2406 p->reclaim_state = &reclaim_state;
2408 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
2410 p->reclaim_state = NULL;
2411 lockdep_clear_current_reclaim_state();
2412 p->flags &= ~PF_MEMALLOC;
2414 return nr_reclaimed;
2416 #endif /* CONFIG_HIBERNATION */
2418 /* It's optimal to keep kswapds on the same CPUs as their memory, but
2419 not required for correctness. So if the last cpu in a node goes
2420 away, we get changed to run anywhere: as the first one comes back,
2421 restore their cpu bindings. */
2422 static int __devinit cpu_callback(struct notifier_block *nfb,
2423 unsigned long action, void *hcpu)
2427 if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
2428 for_each_node_state(nid, N_HIGH_MEMORY) {
2429 pg_data_t *pgdat = NODE_DATA(nid);
2430 const struct cpumask *mask;
2432 mask = cpumask_of_node(pgdat->node_id);
2434 if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
2435 /* One of our CPUs online: restore mask */
2436 set_cpus_allowed_ptr(pgdat->kswapd, mask);
2443 * This kswapd start function will be called by init and node-hot-add.
2444 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
2446 int kswapd_run(int nid)
2448 pg_data_t *pgdat = NODE_DATA(nid);
2454 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
2455 if (IS_ERR(pgdat->kswapd)) {
2456 /* failure at boot is fatal */
2457 BUG_ON(system_state == SYSTEM_BOOTING);
2458 printk("Failed to start kswapd on node %d\n",nid);
2465 * Called by memory hotplug when all memory in a node is offlined.
2467 void kswapd_stop(int nid)
2469 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
2472 kthread_stop(kswapd);
2475 static int __init kswapd_init(void)
2480 for_each_node_state(nid, N_HIGH_MEMORY)
2482 hotcpu_notifier(cpu_callback, 0);
2486 module_init(kswapd_init)
2492 * If non-zero call zone_reclaim when the number of free pages falls below
2495 int zone_reclaim_mode __read_mostly;
2497 #define RECLAIM_OFF 0
2498 #define RECLAIM_ZONE (1<<0) /* Run shrink_inactive_list on the zone */
2499 #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
2500 #define RECLAIM_SWAP (1<<2) /* Swap pages out during reclaim */
2503 * Priority for ZONE_RECLAIM. This determines the fraction of pages
2504 * of a node considered for each zone_reclaim. 4 scans 1/16th of
2507 #define ZONE_RECLAIM_PRIORITY 4
2510 * Percentage of pages in a zone that must be unmapped for zone_reclaim to
2513 int sysctl_min_unmapped_ratio = 1;
2516 * If the number of slab pages in a zone grows beyond this percentage then
2517 * slab reclaim needs to occur.
2519 int sysctl_min_slab_ratio = 5;
2521 static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
2523 unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
2524 unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
2525 zone_page_state(zone, NR_ACTIVE_FILE);
2528 * It's possible for there to be more file mapped pages than
2529 * accounted for by the pages on the file LRU lists because
2530 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
2532 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
2535 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
2536 static long zone_pagecache_reclaimable(struct zone *zone)
2538 long nr_pagecache_reclaimable;
2542 * If RECLAIM_SWAP is set, then all file pages are considered
2543 * potentially reclaimable. Otherwise, we have to worry about
2544 * pages like swapcache and zone_unmapped_file_pages() provides
2547 if (zone_reclaim_mode & RECLAIM_SWAP)
2548 nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
2550 nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
2552 /* If we can't clean pages, remove dirty pages from consideration */
2553 if (!(zone_reclaim_mode & RECLAIM_WRITE))
2554 delta += zone_page_state(zone, NR_FILE_DIRTY);
2556 /* Watch for any possible underflows due to delta */
2557 if (unlikely(delta > nr_pagecache_reclaimable))
2558 delta = nr_pagecache_reclaimable;
2560 return nr_pagecache_reclaimable - delta;
2564 * Try to free up some pages from this zone through reclaim.
2566 static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
2568 /* Minimum pages needed in order to stay on node */
2569 const unsigned long nr_pages = 1 << order;
2570 struct task_struct *p = current;
2571 struct reclaim_state reclaim_state;
2573 struct scan_control sc = {
2574 .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
2575 .may_unmap = !!(zone_reclaim_mode & RECLAIM_SWAP),
2577 .nr_to_reclaim = max_t(unsigned long, nr_pages,
2579 .gfp_mask = gfp_mask,
2580 .swappiness = vm_swappiness,
2582 .isolate_pages = isolate_pages_global,
2584 unsigned long slab_reclaimable;
2586 disable_swap_token();
2589 * We need to be able to allocate from the reserves for RECLAIM_SWAP
2590 * and we also need to be able to write out pages for RECLAIM_WRITE
2593 p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
2594 lockdep_set_current_reclaim_state(gfp_mask);
2595 reclaim_state.reclaimed_slab = 0;
2596 p->reclaim_state = &reclaim_state;
2598 if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
2600 * Free memory by calling shrink zone with increasing
2601 * priorities until we have enough memory freed.
2603 priority = ZONE_RECLAIM_PRIORITY;
2605 note_zone_scanning_priority(zone, priority);
2606 shrink_zone(priority, zone, &sc);
2608 } while (priority >= 0 && sc.nr_reclaimed < nr_pages);
2611 slab_reclaimable = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
2612 if (slab_reclaimable > zone->min_slab_pages) {
2614 * shrink_slab() does not currently allow us to determine how
2615 * many pages were freed in this zone. So we take the current
2616 * number of slab pages and shake the slab until it is reduced
2617 * by the same nr_pages that we used for reclaiming unmapped
2620 * Note that shrink_slab will free memory on all zones and may
2623 while (shrink_slab(sc.nr_scanned, gfp_mask, order) &&
2624 zone_page_state(zone, NR_SLAB_RECLAIMABLE) >
2625 slab_reclaimable - nr_pages)
2629 * Update nr_reclaimed by the number of slab pages we
2630 * reclaimed from this zone.
2632 sc.nr_reclaimed += slab_reclaimable -
2633 zone_page_state(zone, NR_SLAB_RECLAIMABLE);
2636 p->reclaim_state = NULL;
2637 current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
2638 lockdep_clear_current_reclaim_state();
2639 return sc.nr_reclaimed >= nr_pages;
2642 int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
2648 * Zone reclaim reclaims unmapped file backed pages and
2649 * slab pages if we are over the defined limits.
2651 * A small portion of unmapped file backed pages is needed for
2652 * file I/O otherwise pages read by file I/O will be immediately
2653 * thrown out if the zone is overallocated. So we do not reclaim
2654 * if less than a specified percentage of the zone is used by
2655 * unmapped file backed pages.
2657 if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
2658 zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
2659 return ZONE_RECLAIM_FULL;
2661 if (zone->all_unreclaimable)
2662 return ZONE_RECLAIM_FULL;
2665 * Do not scan if the allocation should not be delayed.
2667 if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
2668 return ZONE_RECLAIM_NOSCAN;
2671 * Only run zone reclaim on the local zone or on zones that do not
2672 * have associated processors. This will favor the local processor
2673 * over remote processors and spread off node memory allocations
2674 * as wide as possible.
2676 node_id = zone_to_nid(zone);
2677 if (node_state(node_id, N_CPU) && node_id != numa_node_id())
2678 return ZONE_RECLAIM_NOSCAN;
2680 if (zone_test_and_set_flag(zone, ZONE_RECLAIM_LOCKED))
2681 return ZONE_RECLAIM_NOSCAN;
2683 ret = __zone_reclaim(zone, gfp_mask, order);
2684 zone_clear_flag(zone, ZONE_RECLAIM_LOCKED);
2687 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
2694 * page_evictable - test whether a page is evictable
2695 * @page: the page to test
2696 * @vma: the VMA in which the page is or will be mapped, may be NULL
2698 * Test whether page is evictable--i.e., should be placed on active/inactive
2699 * lists vs unevictable list. The vma argument is !NULL when called from the
2700 * fault path to determine how to instantate a new page.
2702 * Reasons page might not be evictable:
2703 * (1) page's mapping marked unevictable
2704 * (2) page is part of an mlocked VMA
2707 int page_evictable(struct page *page, struct vm_area_struct *vma)
2710 if (mapping_unevictable(page_mapping(page)))
2713 if (PageMlocked(page) || (vma && is_mlocked_vma(vma, page)))
2720 * check_move_unevictable_page - check page for evictability and move to appropriate zone lru list
2721 * @page: page to check evictability and move to appropriate lru list
2722 * @zone: zone page is in
2724 * Checks a page for evictability and moves the page to the appropriate
2727 * Restrictions: zone->lru_lock must be held, page must be on LRU and must
2728 * have PageUnevictable set.
2730 static void check_move_unevictable_page(struct page *page, struct zone *zone)
2732 VM_BUG_ON(PageActive(page));
2735 ClearPageUnevictable(page);
2736 if (page_evictable(page, NULL)) {
2737 enum lru_list l = page_lru_base_type(page);
2739 __dec_zone_state(zone, NR_UNEVICTABLE);
2740 list_move(&page->lru, &zone->lru[l].list);
2741 mem_cgroup_move_lists(page, LRU_UNEVICTABLE, l);
2742 __inc_zone_state(zone, NR_INACTIVE_ANON + l);
2743 __count_vm_event(UNEVICTABLE_PGRESCUED);
2746 * rotate unevictable list
2748 SetPageUnevictable(page);
2749 list_move(&page->lru, &zone->lru[LRU_UNEVICTABLE].list);
2750 mem_cgroup_rotate_lru_list(page, LRU_UNEVICTABLE);
2751 if (page_evictable(page, NULL))
2757 * scan_mapping_unevictable_pages - scan an address space for evictable pages
2758 * @mapping: struct address_space to scan for evictable pages
2760 * Scan all pages in mapping. Check unevictable pages for
2761 * evictability and move them to the appropriate zone lru list.
2763 void scan_mapping_unevictable_pages(struct address_space *mapping)
2766 pgoff_t end = (i_size_read(mapping->host) + PAGE_CACHE_SIZE - 1) >>
2769 struct pagevec pvec;
2771 if (mapping->nrpages == 0)
2774 pagevec_init(&pvec, 0);
2775 while (next < end &&
2776 pagevec_lookup(&pvec, mapping, next, PAGEVEC_SIZE)) {
2782 for (i = 0; i < pagevec_count(&pvec); i++) {
2783 struct page *page = pvec.pages[i];
2784 pgoff_t page_index = page->index;
2785 struct zone *pagezone = page_zone(page);
2788 if (page_index > next)
2792 if (pagezone != zone) {
2794 spin_unlock_irq(&zone->lru_lock);
2796 spin_lock_irq(&zone->lru_lock);
2799 if (PageLRU(page) && PageUnevictable(page))
2800 check_move_unevictable_page(page, zone);
2803 spin_unlock_irq(&zone->lru_lock);
2804 pagevec_release(&pvec);
2806 count_vm_events(UNEVICTABLE_PGSCANNED, pg_scanned);
2812 * scan_zone_unevictable_pages - check unevictable list for evictable pages
2813 * @zone - zone of which to scan the unevictable list
2815 * Scan @zone's unevictable LRU lists to check for pages that have become
2816 * evictable. Move those that have to @zone's inactive list where they
2817 * become candidates for reclaim, unless shrink_inactive_zone() decides
2818 * to reactivate them. Pages that are still unevictable are rotated
2819 * back onto @zone's unevictable list.
2821 #define SCAN_UNEVICTABLE_BATCH_SIZE 16UL /* arbitrary lock hold batch size */
2822 static void scan_zone_unevictable_pages(struct zone *zone)
2824 struct list_head *l_unevictable = &zone->lru[LRU_UNEVICTABLE].list;
2826 unsigned long nr_to_scan = zone_page_state(zone, NR_UNEVICTABLE);
2828 while (nr_to_scan > 0) {
2829 unsigned long batch_size = min(nr_to_scan,
2830 SCAN_UNEVICTABLE_BATCH_SIZE);
2832 spin_lock_irq(&zone->lru_lock);
2833 for (scan = 0; scan < batch_size; scan++) {
2834 struct page *page = lru_to_page(l_unevictable);
2836 if (!trylock_page(page))
2839 prefetchw_prev_lru_page(page, l_unevictable, flags);
2841 if (likely(PageLRU(page) && PageUnevictable(page)))
2842 check_move_unevictable_page(page, zone);
2846 spin_unlock_irq(&zone->lru_lock);
2848 nr_to_scan -= batch_size;
2854 * scan_all_zones_unevictable_pages - scan all unevictable lists for evictable pages
2856 * A really big hammer: scan all zones' unevictable LRU lists to check for
2857 * pages that have become evictable. Move those back to the zones'
2858 * inactive list where they become candidates for reclaim.
2859 * This occurs when, e.g., we have unswappable pages on the unevictable lists,
2860 * and we add swap to the system. As such, it runs in the context of a task
2861 * that has possibly/probably made some previously unevictable pages
2864 static void scan_all_zones_unevictable_pages(void)
2868 for_each_zone(zone) {
2869 scan_zone_unevictable_pages(zone);
2874 * scan_unevictable_pages [vm] sysctl handler. On demand re-scan of
2875 * all nodes' unevictable lists for evictable pages
2877 unsigned long scan_unevictable_pages;
2879 int scan_unevictable_handler(struct ctl_table *table, int write,
2880 void __user *buffer,
2881 size_t *length, loff_t *ppos)
2883 proc_doulongvec_minmax(table, write, buffer, length, ppos);
2885 if (write && *(unsigned long *)table->data)
2886 scan_all_zones_unevictable_pages();
2888 scan_unevictable_pages = 0;
2893 * per node 'scan_unevictable_pages' attribute. On demand re-scan of
2894 * a specified node's per zone unevictable lists for evictable pages.
2897 static ssize_t read_scan_unevictable_node(struct sys_device *dev,
2898 struct sysdev_attribute *attr,
2901 return sprintf(buf, "0\n"); /* always zero; should fit... */
2904 static ssize_t write_scan_unevictable_node(struct sys_device *dev,
2905 struct sysdev_attribute *attr,
2906 const char *buf, size_t count)
2908 struct zone *node_zones = NODE_DATA(dev->id)->node_zones;
2911 unsigned long req = strict_strtoul(buf, 10, &res);
2914 return 1; /* zero is no-op */
2916 for (zone = node_zones; zone - node_zones < MAX_NR_ZONES; ++zone) {
2917 if (!populated_zone(zone))
2919 scan_zone_unevictable_pages(zone);
2925 static SYSDEV_ATTR(scan_unevictable_pages, S_IRUGO | S_IWUSR,
2926 read_scan_unevictable_node,
2927 write_scan_unevictable_node);
2929 int scan_unevictable_register_node(struct node *node)
2931 return sysdev_create_file(&node->sysdev, &attr_scan_unevictable_pages);
2934 void scan_unevictable_unregister_node(struct node *node)
2936 sysdev_remove_file(&node->sysdev, &attr_scan_unevictable_pages);