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/slab.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 /* This context's GFP mask */
66 /* Can mapped pages be reclaimed? */
69 /* Can pages be swapped as part of reclaim? */
72 /* This context's SWAP_CLUSTER_MAX. If freeing memory for
73 * suspend, we effectively ignore SWAP_CLUSTER_MAX.
74 * In this context, it doesn't matter that we scan the
75 * whole list at once. */
80 int all_unreclaimable;
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 /* Called without lock on whether page is mapped, so answer is unstable */
270 static inline int page_mapping_inuse(struct page *page)
272 struct address_space *mapping;
274 /* Page is in somebody's page tables. */
275 if (page_mapped(page))
278 /* Be more reluctant to reclaim swapcache than pagecache */
279 if (PageSwapCache(page))
282 mapping = page_mapping(page);
286 /* File is mmap'd by somebody? */
287 return mapping_mapped(mapping);
290 static inline int is_page_cache_freeable(struct page *page)
293 * A freeable page cache page is referenced only by the caller
294 * that isolated the page, the page cache radix tree and
295 * optional buffer heads at page->private.
297 return page_count(page) - page_has_private(page) == 2;
300 static int may_write_to_queue(struct backing_dev_info *bdi)
302 if (current->flags & PF_SWAPWRITE)
304 if (!bdi_write_congested(bdi))
306 if (bdi == current->backing_dev_info)
312 * We detected a synchronous write error writing a page out. Probably
313 * -ENOSPC. We need to propagate that into the address_space for a subsequent
314 * fsync(), msync() or close().
316 * The tricky part is that after writepage we cannot touch the mapping: nothing
317 * prevents it from being freed up. But we have a ref on the page and once
318 * that page is locked, the mapping is pinned.
320 * We're allowed to run sleeping lock_page() here because we know the caller has
323 static void handle_write_error(struct address_space *mapping,
324 struct page *page, int error)
327 if (page_mapping(page) == mapping)
328 mapping_set_error(mapping, error);
332 /* Request for sync pageout. */
338 /* possible outcome of pageout() */
340 /* failed to write page out, page is locked */
342 /* move page to the active list, page is locked */
344 /* page has been sent to the disk successfully, page is unlocked */
346 /* page is clean and locked */
351 * pageout is called by shrink_page_list() for each dirty page.
352 * Calls ->writepage().
354 static pageout_t pageout(struct page *page, struct address_space *mapping,
355 enum pageout_io sync_writeback)
358 * If the page is dirty, only perform writeback if that write
359 * will be non-blocking. To prevent this allocation from being
360 * stalled by pagecache activity. But note that there may be
361 * stalls if we need to run get_block(). We could test
362 * PagePrivate for that.
364 * If this process is currently in __generic_file_aio_write() against
365 * this page's queue, we can perform writeback even if that
368 * If the page is swapcache, write it back even if that would
369 * block, for some throttling. This happens by accident, because
370 * swap_backing_dev_info is bust: it doesn't reflect the
371 * congestion state of the swapdevs. Easy to fix, if needed.
373 if (!is_page_cache_freeable(page))
377 * Some data journaling orphaned pages can have
378 * page->mapping == NULL while being dirty with clean buffers.
380 if (page_has_private(page)) {
381 if (try_to_free_buffers(page)) {
382 ClearPageDirty(page);
383 printk("%s: orphaned page\n", __func__);
389 if (mapping->a_ops->writepage == NULL)
390 return PAGE_ACTIVATE;
391 if (!may_write_to_queue(mapping->backing_dev_info))
394 if (clear_page_dirty_for_io(page)) {
396 struct writeback_control wbc = {
397 .sync_mode = WB_SYNC_NONE,
398 .nr_to_write = SWAP_CLUSTER_MAX,
400 .range_end = LLONG_MAX,
405 SetPageReclaim(page);
406 res = mapping->a_ops->writepage(page, &wbc);
408 handle_write_error(mapping, page, res);
409 if (res == AOP_WRITEPAGE_ACTIVATE) {
410 ClearPageReclaim(page);
411 return PAGE_ACTIVATE;
415 * Wait on writeback if requested to. This happens when
416 * direct reclaiming a large contiguous area and the
417 * first attempt to free a range of pages fails.
419 if (PageWriteback(page) && sync_writeback == PAGEOUT_IO_SYNC)
420 wait_on_page_writeback(page);
422 if (!PageWriteback(page)) {
423 /* synchronous write or broken a_ops? */
424 ClearPageReclaim(page);
426 inc_zone_page_state(page, NR_VMSCAN_WRITE);
434 * Same as remove_mapping, but if the page is removed from the mapping, it
435 * gets returned with a refcount of 0.
437 static int __remove_mapping(struct address_space *mapping, struct page *page)
439 BUG_ON(!PageLocked(page));
440 BUG_ON(mapping != page_mapping(page));
442 spin_lock_irq(&mapping->tree_lock);
444 * The non racy check for a busy page.
446 * Must be careful with the order of the tests. When someone has
447 * a ref to the page, it may be possible that they dirty it then
448 * drop the reference. So if PageDirty is tested before page_count
449 * here, then the following race may occur:
451 * get_user_pages(&page);
452 * [user mapping goes away]
454 * !PageDirty(page) [good]
455 * SetPageDirty(page);
457 * !page_count(page) [good, discard it]
459 * [oops, our write_to data is lost]
461 * Reversing the order of the tests ensures such a situation cannot
462 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
463 * load is not satisfied before that of page->_count.
465 * Note that if SetPageDirty is always performed via set_page_dirty,
466 * and thus under tree_lock, then this ordering is not required.
468 if (!page_freeze_refs(page, 2))
470 /* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
471 if (unlikely(PageDirty(page))) {
472 page_unfreeze_refs(page, 2);
476 if (PageSwapCache(page)) {
477 swp_entry_t swap = { .val = page_private(page) };
478 __delete_from_swap_cache(page);
479 spin_unlock_irq(&mapping->tree_lock);
480 swapcache_free(swap, page);
482 __remove_from_page_cache(page);
483 spin_unlock_irq(&mapping->tree_lock);
484 mem_cgroup_uncharge_cache_page(page);
490 spin_unlock_irq(&mapping->tree_lock);
495 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
496 * someone else has a ref on the page, abort and return 0. If it was
497 * successfully detached, return 1. Assumes the caller has a single ref on
500 int remove_mapping(struct address_space *mapping, struct page *page)
502 if (__remove_mapping(mapping, page)) {
504 * Unfreezing the refcount with 1 rather than 2 effectively
505 * drops the pagecache ref for us without requiring another
508 page_unfreeze_refs(page, 1);
515 * putback_lru_page - put previously isolated page onto appropriate LRU list
516 * @page: page to be put back to appropriate lru list
518 * Add previously isolated @page to appropriate LRU list.
519 * Page may still be unevictable for other reasons.
521 * lru_lock must not be held, interrupts must be enabled.
523 void putback_lru_page(struct page *page)
526 int active = !!TestClearPageActive(page);
527 int was_unevictable = PageUnevictable(page);
529 VM_BUG_ON(PageLRU(page));
532 ClearPageUnevictable(page);
534 if (page_evictable(page, NULL)) {
536 * For evictable pages, we can use the cache.
537 * In event of a race, worst case is we end up with an
538 * unevictable page on [in]active list.
539 * We know how to handle that.
541 lru = active + page_lru_base_type(page);
542 lru_cache_add_lru(page, lru);
545 * Put unevictable pages directly on zone's unevictable
548 lru = LRU_UNEVICTABLE;
549 add_page_to_unevictable_list(page);
551 * When racing with an mlock clearing (page is
552 * unlocked), make sure that if the other thread does
553 * not observe our setting of PG_lru and fails
554 * isolation, we see PG_mlocked cleared below and move
555 * the page back to the evictable list.
557 * The other side is TestClearPageMlocked().
563 * page's status can change while we move it among lru. If an evictable
564 * page is on unevictable list, it never be freed. To avoid that,
565 * check after we added it to the list, again.
567 if (lru == LRU_UNEVICTABLE && page_evictable(page, NULL)) {
568 if (!isolate_lru_page(page)) {
572 /* This means someone else dropped this page from LRU
573 * So, it will be freed or putback to LRU again. There is
574 * nothing to do here.
578 if (was_unevictable && lru != LRU_UNEVICTABLE)
579 count_vm_event(UNEVICTABLE_PGRESCUED);
580 else if (!was_unevictable && lru == LRU_UNEVICTABLE)
581 count_vm_event(UNEVICTABLE_PGCULLED);
583 put_page(page); /* drop ref from isolate */
587 * shrink_page_list() returns the number of reclaimed pages
589 static unsigned long shrink_page_list(struct list_head *page_list,
590 struct scan_control *sc,
591 enum pageout_io sync_writeback)
593 LIST_HEAD(ret_pages);
594 struct pagevec freed_pvec;
596 unsigned long nr_reclaimed = 0;
597 unsigned long vm_flags;
601 pagevec_init(&freed_pvec, 1);
602 while (!list_empty(page_list)) {
603 struct address_space *mapping;
610 page = lru_to_page(page_list);
611 list_del(&page->lru);
613 if (!trylock_page(page))
616 VM_BUG_ON(PageActive(page));
620 if (unlikely(!page_evictable(page, NULL)))
623 if (!sc->may_unmap && page_mapped(page))
626 /* Double the slab pressure for mapped and swapcache pages */
627 if (page_mapped(page) || PageSwapCache(page))
630 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
631 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
633 if (PageWriteback(page)) {
635 * Synchronous reclaim is performed in two passes,
636 * first an asynchronous pass over the list to
637 * start parallel writeback, and a second synchronous
638 * pass to wait for the IO to complete. Wait here
639 * for any page for which writeback has already
642 if (sync_writeback == PAGEOUT_IO_SYNC && may_enter_fs)
643 wait_on_page_writeback(page);
648 referenced = page_referenced(page, 1,
649 sc->mem_cgroup, &vm_flags);
651 * In active use or really unfreeable? Activate it.
652 * If page which have PG_mlocked lost isoltation race,
653 * try_to_unmap moves it to unevictable list
655 if (sc->order <= PAGE_ALLOC_COSTLY_ORDER &&
656 referenced && page_mapping_inuse(page)
657 && !(vm_flags & VM_LOCKED))
658 goto activate_locked;
661 * Anonymous process memory has backing store?
662 * Try to allocate it some swap space here.
664 if (PageAnon(page) && !PageSwapCache(page)) {
665 if (!(sc->gfp_mask & __GFP_IO))
667 if (!add_to_swap(page))
668 goto activate_locked;
672 mapping = page_mapping(page);
675 * The page is mapped into the page tables of one or more
676 * processes. Try to unmap it here.
678 if (page_mapped(page) && mapping) {
679 switch (try_to_unmap(page, TTU_UNMAP)) {
681 goto activate_locked;
687 ; /* try to free the page below */
691 if (PageDirty(page)) {
692 if (sc->order <= PAGE_ALLOC_COSTLY_ORDER && referenced)
696 if (!sc->may_writepage)
699 /* Page is dirty, try to write it out here */
700 switch (pageout(page, mapping, sync_writeback)) {
704 goto activate_locked;
706 if (PageWriteback(page) || PageDirty(page))
709 * A synchronous write - probably a ramdisk. Go
710 * ahead and try to reclaim the page.
712 if (!trylock_page(page))
714 if (PageDirty(page) || PageWriteback(page))
716 mapping = page_mapping(page);
718 ; /* try to free the page below */
723 * If the page has buffers, try to free the buffer mappings
724 * associated with this page. If we succeed we try to free
727 * We do this even if the page is PageDirty().
728 * try_to_release_page() does not perform I/O, but it is
729 * possible for a page to have PageDirty set, but it is actually
730 * clean (all its buffers are clean). This happens if the
731 * buffers were written out directly, with submit_bh(). ext3
732 * will do this, as well as the blockdev mapping.
733 * try_to_release_page() will discover that cleanness and will
734 * drop the buffers and mark the page clean - it can be freed.
736 * Rarely, pages can have buffers and no ->mapping. These are
737 * the pages which were not successfully invalidated in
738 * truncate_complete_page(). We try to drop those buffers here
739 * and if that worked, and the page is no longer mapped into
740 * process address space (page_count == 1) it can be freed.
741 * Otherwise, leave the page on the LRU so it is swappable.
743 if (page_has_private(page)) {
744 if (!try_to_release_page(page, sc->gfp_mask))
745 goto activate_locked;
746 if (!mapping && page_count(page) == 1) {
748 if (put_page_testzero(page))
752 * rare race with speculative reference.
753 * the speculative reference will free
754 * this page shortly, so we may
755 * increment nr_reclaimed here (and
756 * leave it off the LRU).
764 if (!mapping || !__remove_mapping(mapping, page))
768 * At this point, we have no other references and there is
769 * no way to pick any more up (removed from LRU, removed
770 * from pagecache). Can use non-atomic bitops now (and
771 * we obviously don't have to worry about waking up a process
772 * waiting on the page lock, because there are no references.
774 __clear_page_locked(page);
777 if (!pagevec_add(&freed_pvec, page)) {
778 __pagevec_free(&freed_pvec);
779 pagevec_reinit(&freed_pvec);
784 if (PageSwapCache(page))
785 try_to_free_swap(page);
787 putback_lru_page(page);
791 /* Not a candidate for swapping, so reclaim swap space. */
792 if (PageSwapCache(page) && vm_swap_full())
793 try_to_free_swap(page);
794 VM_BUG_ON(PageActive(page));
800 list_add(&page->lru, &ret_pages);
801 VM_BUG_ON(PageLRU(page) || PageUnevictable(page));
803 list_splice(&ret_pages, page_list);
804 if (pagevec_count(&freed_pvec))
805 __pagevec_free(&freed_pvec);
806 count_vm_events(PGACTIVATE, pgactivate);
810 /* LRU Isolation modes. */
811 #define ISOLATE_INACTIVE 0 /* Isolate inactive pages. */
812 #define ISOLATE_ACTIVE 1 /* Isolate active pages. */
813 #define ISOLATE_BOTH 2 /* Isolate both active and inactive pages. */
816 * Attempt to remove the specified page from its LRU. Only take this page
817 * if it is of the appropriate PageActive status. Pages which are being
818 * freed elsewhere are also ignored.
820 * page: page to consider
821 * mode: one of the LRU isolation modes defined above
823 * returns 0 on success, -ve errno on failure.
825 int __isolate_lru_page(struct page *page, int mode, int file)
829 /* Only take pages on the LRU. */
834 * When checking the active state, we need to be sure we are
835 * dealing with comparible boolean values. Take the logical not
838 if (mode != ISOLATE_BOTH && (!PageActive(page) != !mode))
841 if (mode != ISOLATE_BOTH && page_is_file_cache(page) != file)
845 * When this function is being called for lumpy reclaim, we
846 * initially look into all LRU pages, active, inactive and
847 * unevictable; only give shrink_page_list evictable pages.
849 if (PageUnevictable(page))
854 if (likely(get_page_unless_zero(page))) {
856 * Be careful not to clear PageLRU until after we're
857 * sure the page is not being freed elsewhere -- the
858 * page release code relies on it.
868 * zone->lru_lock is heavily contended. Some of the functions that
869 * shrink the lists perform better by taking out a batch of pages
870 * and working on them outside the LRU lock.
872 * For pagecache intensive workloads, this function is the hottest
873 * spot in the kernel (apart from copy_*_user functions).
875 * Appropriate locks must be held before calling this function.
877 * @nr_to_scan: The number of pages to look through on the list.
878 * @src: The LRU list to pull pages off.
879 * @dst: The temp list to put pages on to.
880 * @scanned: The number of pages that were scanned.
881 * @order: The caller's attempted allocation order
882 * @mode: One of the LRU isolation modes
883 * @file: True [1] if isolating file [!anon] pages
885 * returns how many pages were moved onto *@dst.
887 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
888 struct list_head *src, struct list_head *dst,
889 unsigned long *scanned, int order, int mode, int file)
891 unsigned long nr_taken = 0;
894 for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
897 unsigned long end_pfn;
898 unsigned long page_pfn;
901 page = lru_to_page(src);
902 prefetchw_prev_lru_page(page, src, flags);
904 VM_BUG_ON(!PageLRU(page));
906 switch (__isolate_lru_page(page, mode, file)) {
908 list_move(&page->lru, dst);
909 mem_cgroup_del_lru(page);
914 /* else it is being freed elsewhere */
915 list_move(&page->lru, src);
916 mem_cgroup_rotate_lru_list(page, page_lru(page));
927 * Attempt to take all pages in the order aligned region
928 * surrounding the tag page. Only take those pages of
929 * the same active state as that tag page. We may safely
930 * round the target page pfn down to the requested order
931 * as the mem_map is guarenteed valid out to MAX_ORDER,
932 * where that page is in a different zone we will detect
933 * it from its zone id and abort this block scan.
935 zone_id = page_zone_id(page);
936 page_pfn = page_to_pfn(page);
937 pfn = page_pfn & ~((1 << order) - 1);
938 end_pfn = pfn + (1 << order);
939 for (; pfn < end_pfn; pfn++) {
940 struct page *cursor_page;
942 /* The target page is in the block, ignore it. */
943 if (unlikely(pfn == page_pfn))
946 /* Avoid holes within the zone. */
947 if (unlikely(!pfn_valid_within(pfn)))
950 cursor_page = pfn_to_page(pfn);
952 /* Check that we have not crossed a zone boundary. */
953 if (unlikely(page_zone_id(cursor_page) != zone_id))
957 * If we don't have enough swap space, reclaiming of
958 * anon page which don't already have a swap slot is
961 if (nr_swap_pages <= 0 && PageAnon(cursor_page) &&
962 !PageSwapCache(cursor_page))
965 if (__isolate_lru_page(cursor_page, mode, file) == 0) {
966 list_move(&cursor_page->lru, dst);
967 mem_cgroup_del_lru(cursor_page);
978 static unsigned long isolate_pages_global(unsigned long nr,
979 struct list_head *dst,
980 unsigned long *scanned, int order,
981 int mode, struct zone *z,
982 struct mem_cgroup *mem_cont,
983 int active, int file)
990 return isolate_lru_pages(nr, &z->lru[lru].list, dst, scanned, order,
995 * clear_active_flags() is a helper for shrink_active_list(), clearing
996 * any active bits from the pages in the list.
998 static unsigned long clear_active_flags(struct list_head *page_list,
1005 list_for_each_entry(page, page_list, lru) {
1006 lru = page_lru_base_type(page);
1007 if (PageActive(page)) {
1009 ClearPageActive(page);
1019 * isolate_lru_page - tries to isolate a page from its LRU list
1020 * @page: page to isolate from its LRU list
1022 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
1023 * vmstat statistic corresponding to whatever LRU list the page was on.
1025 * Returns 0 if the page was removed from an LRU list.
1026 * Returns -EBUSY if the page was not on an LRU list.
1028 * The returned page will have PageLRU() cleared. If it was found on
1029 * the active list, it will have PageActive set. If it was found on
1030 * the unevictable list, it will have the PageUnevictable bit set. That flag
1031 * may need to be cleared by the caller before letting the page go.
1033 * The vmstat statistic corresponding to the list on which the page was
1034 * found will be decremented.
1037 * (1) Must be called with an elevated refcount on the page. This is a
1038 * fundamentnal difference from isolate_lru_pages (which is called
1039 * without a stable reference).
1040 * (2) the lru_lock must not be held.
1041 * (3) interrupts must be enabled.
1043 int isolate_lru_page(struct page *page)
1047 if (PageLRU(page)) {
1048 struct zone *zone = page_zone(page);
1050 spin_lock_irq(&zone->lru_lock);
1051 if (PageLRU(page) && get_page_unless_zero(page)) {
1052 int lru = page_lru(page);
1056 del_page_from_lru_list(zone, page, lru);
1058 spin_unlock_irq(&zone->lru_lock);
1064 * Are there way too many processes in the direct reclaim path already?
1066 static int too_many_isolated(struct zone *zone, int file,
1067 struct scan_control *sc)
1069 unsigned long inactive, isolated;
1071 if (current_is_kswapd())
1074 if (!scanning_global_lru(sc))
1078 inactive = zone_page_state(zone, NR_INACTIVE_FILE);
1079 isolated = zone_page_state(zone, NR_ISOLATED_FILE);
1081 inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1082 isolated = zone_page_state(zone, NR_ISOLATED_ANON);
1085 return isolated > inactive;
1089 * shrink_inactive_list() is a helper for shrink_zone(). It returns the number
1090 * of reclaimed pages
1092 static unsigned long shrink_inactive_list(unsigned long max_scan,
1093 struct zone *zone, struct scan_control *sc,
1094 int priority, int file)
1096 LIST_HEAD(page_list);
1097 struct pagevec pvec;
1098 unsigned long nr_scanned = 0;
1099 unsigned long nr_reclaimed = 0;
1100 struct zone_reclaim_stat *reclaim_stat = get_reclaim_stat(zone, sc);
1101 int lumpy_reclaim = 0;
1103 while (unlikely(too_many_isolated(zone, file, sc))) {
1104 congestion_wait(BLK_RW_ASYNC, HZ/10);
1106 /* We are about to die and free our memory. Return now. */
1107 if (fatal_signal_pending(current))
1108 return SWAP_CLUSTER_MAX;
1112 * If we need a large contiguous chunk of memory, or have
1113 * trouble getting a small set of contiguous pages, we
1114 * will reclaim both active and inactive pages.
1116 * We use the same threshold as pageout congestion_wait below.
1118 if (sc->order > PAGE_ALLOC_COSTLY_ORDER)
1120 else if (sc->order && priority < DEF_PRIORITY - 2)
1123 pagevec_init(&pvec, 1);
1126 spin_lock_irq(&zone->lru_lock);
1129 unsigned long nr_taken;
1130 unsigned long nr_scan;
1131 unsigned long nr_freed;
1132 unsigned long nr_active;
1133 unsigned int count[NR_LRU_LISTS] = { 0, };
1134 int mode = lumpy_reclaim ? ISOLATE_BOTH : ISOLATE_INACTIVE;
1135 unsigned long nr_anon;
1136 unsigned long nr_file;
1138 nr_taken = sc->isolate_pages(sc->swap_cluster_max,
1139 &page_list, &nr_scan, sc->order, mode,
1140 zone, sc->mem_cgroup, 0, file);
1142 if (scanning_global_lru(sc)) {
1143 zone->pages_scanned += nr_scan;
1144 if (current_is_kswapd())
1145 __count_zone_vm_events(PGSCAN_KSWAPD, zone,
1148 __count_zone_vm_events(PGSCAN_DIRECT, zone,
1155 nr_active = clear_active_flags(&page_list, count);
1156 __count_vm_events(PGDEACTIVATE, nr_active);
1158 __mod_zone_page_state(zone, NR_ACTIVE_FILE,
1159 -count[LRU_ACTIVE_FILE]);
1160 __mod_zone_page_state(zone, NR_INACTIVE_FILE,
1161 -count[LRU_INACTIVE_FILE]);
1162 __mod_zone_page_state(zone, NR_ACTIVE_ANON,
1163 -count[LRU_ACTIVE_ANON]);
1164 __mod_zone_page_state(zone, NR_INACTIVE_ANON,
1165 -count[LRU_INACTIVE_ANON]);
1167 nr_anon = count[LRU_ACTIVE_ANON] + count[LRU_INACTIVE_ANON];
1168 nr_file = count[LRU_ACTIVE_FILE] + count[LRU_INACTIVE_FILE];
1169 __mod_zone_page_state(zone, NR_ISOLATED_ANON, nr_anon);
1170 __mod_zone_page_state(zone, NR_ISOLATED_FILE, nr_file);
1172 reclaim_stat->recent_scanned[0] += count[LRU_INACTIVE_ANON];
1173 reclaim_stat->recent_scanned[0] += count[LRU_ACTIVE_ANON];
1174 reclaim_stat->recent_scanned[1] += count[LRU_INACTIVE_FILE];
1175 reclaim_stat->recent_scanned[1] += count[LRU_ACTIVE_FILE];
1177 spin_unlock_irq(&zone->lru_lock);
1179 nr_scanned += nr_scan;
1180 nr_freed = shrink_page_list(&page_list, sc, PAGEOUT_IO_ASYNC);
1183 * If we are direct reclaiming for contiguous pages and we do
1184 * not reclaim everything in the list, try again and wait
1185 * for IO to complete. This will stall high-order allocations
1186 * but that should be acceptable to the caller
1188 if (nr_freed < nr_taken && !current_is_kswapd() &&
1190 congestion_wait(BLK_RW_ASYNC, HZ/10);
1193 * The attempt at page out may have made some
1194 * of the pages active, mark them inactive again.
1196 nr_active = clear_active_flags(&page_list, count);
1197 count_vm_events(PGDEACTIVATE, nr_active);
1199 nr_freed += shrink_page_list(&page_list, sc,
1203 nr_reclaimed += nr_freed;
1205 local_irq_disable();
1206 if (current_is_kswapd())
1207 __count_vm_events(KSWAPD_STEAL, nr_freed);
1208 __count_zone_vm_events(PGSTEAL, zone, nr_freed);
1210 spin_lock(&zone->lru_lock);
1212 * Put back any unfreeable pages.
1214 while (!list_empty(&page_list)) {
1216 page = lru_to_page(&page_list);
1217 VM_BUG_ON(PageLRU(page));
1218 list_del(&page->lru);
1219 if (unlikely(!page_evictable(page, NULL))) {
1220 spin_unlock_irq(&zone->lru_lock);
1221 putback_lru_page(page);
1222 spin_lock_irq(&zone->lru_lock);
1226 lru = page_lru(page);
1227 add_page_to_lru_list(zone, page, lru);
1228 if (is_active_lru(lru)) {
1229 int file = is_file_lru(lru);
1230 reclaim_stat->recent_rotated[file]++;
1232 if (!pagevec_add(&pvec, page)) {
1233 spin_unlock_irq(&zone->lru_lock);
1234 __pagevec_release(&pvec);
1235 spin_lock_irq(&zone->lru_lock);
1238 __mod_zone_page_state(zone, NR_ISOLATED_ANON, -nr_anon);
1239 __mod_zone_page_state(zone, NR_ISOLATED_FILE, -nr_file);
1241 } while (nr_scanned < max_scan);
1244 spin_unlock_irq(&zone->lru_lock);
1245 pagevec_release(&pvec);
1246 return nr_reclaimed;
1250 * We are about to scan this zone at a certain priority level. If that priority
1251 * level is smaller (ie: more urgent) than the previous priority, then note
1252 * that priority level within the zone. This is done so that when the next
1253 * process comes in to scan this zone, it will immediately start out at this
1254 * priority level rather than having to build up its own scanning priority.
1255 * Here, this priority affects only the reclaim-mapped threshold.
1257 static inline void note_zone_scanning_priority(struct zone *zone, int priority)
1259 if (priority < zone->prev_priority)
1260 zone->prev_priority = priority;
1264 * This moves pages from the active list to the inactive list.
1266 * We move them the other way if the page is referenced by one or more
1267 * processes, from rmap.
1269 * If the pages are mostly unmapped, the processing is fast and it is
1270 * appropriate to hold zone->lru_lock across the whole operation. But if
1271 * the pages are mapped, the processing is slow (page_referenced()) so we
1272 * should drop zone->lru_lock around each page. It's impossible to balance
1273 * this, so instead we remove the pages from the LRU while processing them.
1274 * It is safe to rely on PG_active against the non-LRU pages in here because
1275 * nobody will play with that bit on a non-LRU page.
1277 * The downside is that we have to touch page->_count against each page.
1278 * But we had to alter page->flags anyway.
1281 static void move_active_pages_to_lru(struct zone *zone,
1282 struct list_head *list,
1285 unsigned long pgmoved = 0;
1286 struct pagevec pvec;
1289 pagevec_init(&pvec, 1);
1291 while (!list_empty(list)) {
1292 page = lru_to_page(list);
1294 VM_BUG_ON(PageLRU(page));
1297 list_move(&page->lru, &zone->lru[lru].list);
1298 mem_cgroup_add_lru_list(page, lru);
1301 if (!pagevec_add(&pvec, page) || list_empty(list)) {
1302 spin_unlock_irq(&zone->lru_lock);
1303 if (buffer_heads_over_limit)
1304 pagevec_strip(&pvec);
1305 __pagevec_release(&pvec);
1306 spin_lock_irq(&zone->lru_lock);
1309 __mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved);
1310 if (!is_active_lru(lru))
1311 __count_vm_events(PGDEACTIVATE, pgmoved);
1314 static void shrink_active_list(unsigned long nr_pages, struct zone *zone,
1315 struct scan_control *sc, int priority, int file)
1317 unsigned long nr_taken;
1318 unsigned long pgscanned;
1319 unsigned long vm_flags;
1320 LIST_HEAD(l_hold); /* The pages which were snipped off */
1321 LIST_HEAD(l_active);
1322 LIST_HEAD(l_inactive);
1324 struct zone_reclaim_stat *reclaim_stat = get_reclaim_stat(zone, sc);
1325 unsigned long nr_rotated = 0;
1328 spin_lock_irq(&zone->lru_lock);
1329 nr_taken = sc->isolate_pages(nr_pages, &l_hold, &pgscanned, sc->order,
1330 ISOLATE_ACTIVE, zone,
1331 sc->mem_cgroup, 1, file);
1333 * zone->pages_scanned is used for detect zone's oom
1334 * mem_cgroup remembers nr_scan by itself.
1336 if (scanning_global_lru(sc)) {
1337 zone->pages_scanned += pgscanned;
1339 reclaim_stat->recent_scanned[file] += nr_taken;
1341 __count_zone_vm_events(PGREFILL, zone, pgscanned);
1343 __mod_zone_page_state(zone, NR_ACTIVE_FILE, -nr_taken);
1345 __mod_zone_page_state(zone, NR_ACTIVE_ANON, -nr_taken);
1346 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
1347 spin_unlock_irq(&zone->lru_lock);
1349 while (!list_empty(&l_hold)) {
1351 page = lru_to_page(&l_hold);
1352 list_del(&page->lru);
1354 if (unlikely(!page_evictable(page, NULL))) {
1355 putback_lru_page(page);
1359 /* page_referenced clears PageReferenced */
1360 if (page_mapping_inuse(page) &&
1361 page_referenced(page, 0, sc->mem_cgroup, &vm_flags)) {
1364 * Identify referenced, file-backed active pages and
1365 * give them one more trip around the active list. So
1366 * that executable code get better chances to stay in
1367 * memory under moderate memory pressure. Anon pages
1368 * are not likely to be evicted by use-once streaming
1369 * IO, plus JVM can create lots of anon VM_EXEC pages,
1370 * so we ignore them here.
1372 if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
1373 list_add(&page->lru, &l_active);
1378 ClearPageActive(page); /* we are de-activating */
1379 list_add(&page->lru, &l_inactive);
1383 * Move pages back to the lru list.
1385 spin_lock_irq(&zone->lru_lock);
1387 * Count referenced pages from currently used mappings as rotated,
1388 * even though only some of them are actually re-activated. This
1389 * helps balance scan pressure between file and anonymous pages in
1392 reclaim_stat->recent_rotated[file] += nr_rotated;
1394 move_active_pages_to_lru(zone, &l_active,
1395 LRU_ACTIVE + file * LRU_FILE);
1396 move_active_pages_to_lru(zone, &l_inactive,
1397 LRU_BASE + file * LRU_FILE);
1398 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1399 spin_unlock_irq(&zone->lru_lock);
1402 static int inactive_anon_is_low_global(struct zone *zone)
1404 unsigned long active, inactive;
1406 active = zone_page_state(zone, NR_ACTIVE_ANON);
1407 inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1409 if (inactive * zone->inactive_ratio < active)
1416 * inactive_anon_is_low - check if anonymous pages need to be deactivated
1417 * @zone: zone to check
1418 * @sc: scan control of this context
1420 * Returns true if the zone does not have enough inactive anon pages,
1421 * meaning some active anon pages need to be deactivated.
1423 static int inactive_anon_is_low(struct zone *zone, struct scan_control *sc)
1427 if (scanning_global_lru(sc))
1428 low = inactive_anon_is_low_global(zone);
1430 low = mem_cgroup_inactive_anon_is_low(sc->mem_cgroup);
1434 static int inactive_file_is_low_global(struct zone *zone)
1436 unsigned long active, inactive;
1438 active = zone_page_state(zone, NR_ACTIVE_FILE);
1439 inactive = zone_page_state(zone, NR_INACTIVE_FILE);
1441 return (active > inactive);
1445 * inactive_file_is_low - check if file pages need to be deactivated
1446 * @zone: zone to check
1447 * @sc: scan control of this context
1449 * When the system is doing streaming IO, memory pressure here
1450 * ensures that active file pages get deactivated, until more
1451 * than half of the file pages are on the inactive list.
1453 * Once we get to that situation, protect the system's working
1454 * set from being evicted by disabling active file page aging.
1456 * This uses a different ratio than the anonymous pages, because
1457 * the page cache uses a use-once replacement algorithm.
1459 static int inactive_file_is_low(struct zone *zone, struct scan_control *sc)
1463 if (scanning_global_lru(sc))
1464 low = inactive_file_is_low_global(zone);
1466 low = mem_cgroup_inactive_file_is_low(sc->mem_cgroup);
1470 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
1471 struct zone *zone, struct scan_control *sc, int priority)
1473 int file = is_file_lru(lru);
1475 if (lru == LRU_ACTIVE_FILE && inactive_file_is_low(zone, sc)) {
1476 shrink_active_list(nr_to_scan, zone, sc, priority, file);
1480 if (lru == LRU_ACTIVE_ANON && inactive_anon_is_low(zone, sc)) {
1481 shrink_active_list(nr_to_scan, zone, sc, priority, file);
1484 return shrink_inactive_list(nr_to_scan, zone, sc, priority, file);
1488 * Determine how aggressively the anon and file LRU lists should be
1489 * scanned. The relative value of each set of LRU lists is determined
1490 * by looking at the fraction of the pages scanned we did rotate back
1491 * onto the active list instead of evict.
1493 * percent[0] specifies how much pressure to put on ram/swap backed
1494 * memory, while percent[1] determines pressure on the file LRUs.
1496 static void get_scan_ratio(struct zone *zone, struct scan_control *sc,
1497 unsigned long *percent)
1499 unsigned long anon, file, free;
1500 unsigned long anon_prio, file_prio;
1501 unsigned long ap, fp;
1502 struct zone_reclaim_stat *reclaim_stat = get_reclaim_stat(zone, sc);
1504 anon = zone_nr_lru_pages(zone, sc, LRU_ACTIVE_ANON) +
1505 zone_nr_lru_pages(zone, sc, LRU_INACTIVE_ANON);
1506 file = zone_nr_lru_pages(zone, sc, LRU_ACTIVE_FILE) +
1507 zone_nr_lru_pages(zone, sc, LRU_INACTIVE_FILE);
1509 if (scanning_global_lru(sc)) {
1510 free = zone_page_state(zone, NR_FREE_PAGES);
1511 /* If we have very few page cache pages,
1512 force-scan anon pages. */
1513 if (unlikely(file + free <= high_wmark_pages(zone))) {
1521 * OK, so we have swap space and a fair amount of page cache
1522 * pages. We use the recently rotated / recently scanned
1523 * ratios to determine how valuable each cache is.
1525 * Because workloads change over time (and to avoid overflow)
1526 * we keep these statistics as a floating average, which ends
1527 * up weighing recent references more than old ones.
1529 * anon in [0], file in [1]
1531 if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
1532 spin_lock_irq(&zone->lru_lock);
1533 reclaim_stat->recent_scanned[0] /= 2;
1534 reclaim_stat->recent_rotated[0] /= 2;
1535 spin_unlock_irq(&zone->lru_lock);
1538 if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
1539 spin_lock_irq(&zone->lru_lock);
1540 reclaim_stat->recent_scanned[1] /= 2;
1541 reclaim_stat->recent_rotated[1] /= 2;
1542 spin_unlock_irq(&zone->lru_lock);
1546 * With swappiness at 100, anonymous and file have the same priority.
1547 * This scanning priority is essentially the inverse of IO cost.
1549 anon_prio = sc->swappiness;
1550 file_prio = 200 - sc->swappiness;
1553 * The amount of pressure on anon vs file pages is inversely
1554 * proportional to the fraction of recently scanned pages on
1555 * each list that were recently referenced and in active use.
1557 ap = (anon_prio + 1) * (reclaim_stat->recent_scanned[0] + 1);
1558 ap /= reclaim_stat->recent_rotated[0] + 1;
1560 fp = (file_prio + 1) * (reclaim_stat->recent_scanned[1] + 1);
1561 fp /= reclaim_stat->recent_rotated[1] + 1;
1563 /* Normalize to percentages */
1564 percent[0] = 100 * ap / (ap + fp + 1);
1565 percent[1] = 100 - percent[0];
1569 * Smallish @nr_to_scan's are deposited in @nr_saved_scan,
1570 * until we collected @swap_cluster_max pages to scan.
1572 static unsigned long nr_scan_try_batch(unsigned long nr_to_scan,
1573 unsigned long *nr_saved_scan,
1574 unsigned long swap_cluster_max)
1578 *nr_saved_scan += nr_to_scan;
1579 nr = *nr_saved_scan;
1581 if (nr >= swap_cluster_max)
1590 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
1592 static void shrink_zone(int priority, struct zone *zone,
1593 struct scan_control *sc)
1595 unsigned long nr[NR_LRU_LISTS];
1596 unsigned long nr_to_scan;
1597 unsigned long percent[2]; /* anon @ 0; file @ 1 */
1599 unsigned long nr_reclaimed = sc->nr_reclaimed;
1600 unsigned long swap_cluster_max = sc->swap_cluster_max;
1601 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
1602 struct zone_reclaim_stat *reclaim_stat = get_reclaim_stat(zone, sc);
1605 /* If we have no swap space, do not bother scanning anon pages. */
1606 if (!sc->may_swap || (nr_swap_pages <= 0)) {
1611 get_scan_ratio(zone, sc, percent);
1613 for_each_evictable_lru(l) {
1614 int file = is_file_lru(l);
1617 scan = zone_nr_lru_pages(zone, sc, l);
1618 if (priority || noswap) {
1620 scan = (scan * percent[file]) / 100;
1622 nr[l] = nr_scan_try_batch(scan,
1623 &reclaim_stat->nr_saved_scan[l],
1627 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
1628 nr[LRU_INACTIVE_FILE]) {
1629 for_each_evictable_lru(l) {
1631 nr_to_scan = min(nr[l], swap_cluster_max);
1632 nr[l] -= nr_to_scan;
1634 nr_reclaimed += shrink_list(l, nr_to_scan,
1635 zone, sc, priority);
1639 * On large memory systems, scan >> priority can become
1640 * really large. This is fine for the starting priority;
1641 * we want to put equal scanning pressure on each zone.
1642 * However, if the VM has a harder time of freeing pages,
1643 * with multiple processes reclaiming pages, the total
1644 * freeing target can get unreasonably large.
1646 if (nr_reclaimed > nr_to_reclaim && priority < DEF_PRIORITY)
1650 sc->nr_reclaimed = nr_reclaimed;
1653 * Even if we did not try to evict anon pages at all, we want to
1654 * rebalance the anon lru active/inactive ratio.
1656 if (inactive_anon_is_low(zone, sc) && nr_swap_pages > 0)
1657 shrink_active_list(SWAP_CLUSTER_MAX, zone, sc, priority, 0);
1659 throttle_vm_writeout(sc->gfp_mask);
1663 * This is the direct reclaim path, for page-allocating processes. We only
1664 * try to reclaim pages from zones which will satisfy the caller's allocation
1667 * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
1669 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
1671 * b) The target zone may be at high_wmark_pages(zone) but the lower zones
1672 * must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
1673 * zone defense algorithm.
1675 * If a zone is deemed to be full of pinned pages then just give it a light
1676 * scan then give up on it.
1678 static void shrink_zones(int priority, struct zonelist *zonelist,
1679 struct scan_control *sc)
1681 enum zone_type high_zoneidx = gfp_zone(sc->gfp_mask);
1685 sc->all_unreclaimable = 1;
1686 for_each_zone_zonelist_nodemask(zone, z, zonelist, high_zoneidx,
1688 if (!populated_zone(zone))
1691 * Take care memory controller reclaiming has small influence
1694 if (scanning_global_lru(sc)) {
1695 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1697 note_zone_scanning_priority(zone, priority);
1699 if (zone_is_all_unreclaimable(zone) &&
1700 priority != DEF_PRIORITY)
1701 continue; /* Let kswapd poll it */
1702 sc->all_unreclaimable = 0;
1705 * Ignore cpuset limitation here. We just want to reduce
1706 * # of used pages by us regardless of memory shortage.
1708 sc->all_unreclaimable = 0;
1709 mem_cgroup_note_reclaim_priority(sc->mem_cgroup,
1713 shrink_zone(priority, zone, sc);
1718 * This is the main entry point to direct page reclaim.
1720 * If a full scan of the inactive list fails to free enough memory then we
1721 * are "out of memory" and something needs to be killed.
1723 * If the caller is !__GFP_FS then the probability of a failure is reasonably
1724 * high - the zone may be full of dirty or under-writeback pages, which this
1725 * caller can't do much about. We kick the writeback threads and take explicit
1726 * naps in the hope that some of these pages can be written. But if the
1727 * allocating task holds filesystem locks which prevent writeout this might not
1728 * work, and the allocation attempt will fail.
1730 * returns: 0, if no pages reclaimed
1731 * else, the number of pages reclaimed
1733 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
1734 struct scan_control *sc)
1737 unsigned long ret = 0;
1738 unsigned long total_scanned = 0;
1739 struct reclaim_state *reclaim_state = current->reclaim_state;
1740 unsigned long lru_pages = 0;
1743 enum zone_type high_zoneidx = gfp_zone(sc->gfp_mask);
1744 unsigned long writeback_threshold;
1746 delayacct_freepages_start();
1748 if (scanning_global_lru(sc))
1749 count_vm_event(ALLOCSTALL);
1751 * mem_cgroup will not do shrink_slab.
1753 if (scanning_global_lru(sc)) {
1754 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
1756 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1759 lru_pages += zone_reclaimable_pages(zone);
1763 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1766 disable_swap_token();
1767 shrink_zones(priority, zonelist, sc);
1769 * Don't shrink slabs when reclaiming memory from
1770 * over limit cgroups
1772 if (scanning_global_lru(sc)) {
1773 shrink_slab(sc->nr_scanned, sc->gfp_mask, lru_pages);
1774 if (reclaim_state) {
1775 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
1776 reclaim_state->reclaimed_slab = 0;
1779 total_scanned += sc->nr_scanned;
1780 if (sc->nr_reclaimed >= sc->nr_to_reclaim) {
1781 ret = sc->nr_reclaimed;
1786 * Try to write back as many pages as we just scanned. This
1787 * tends to cause slow streaming writers to write data to the
1788 * disk smoothly, at the dirtying rate, which is nice. But
1789 * that's undesirable in laptop mode, where we *want* lumpy
1790 * writeout. So in laptop mode, write out the whole world.
1792 writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
1793 if (total_scanned > writeback_threshold) {
1794 wakeup_flusher_threads(laptop_mode ? 0 : total_scanned);
1795 sc->may_writepage = 1;
1798 /* Take a nap, wait for some writeback to complete */
1799 if (sc->nr_scanned && priority < DEF_PRIORITY - 2)
1800 congestion_wait(BLK_RW_ASYNC, HZ/10);
1802 /* top priority shrink_zones still had more to do? don't OOM, then */
1803 if (!sc->all_unreclaimable && scanning_global_lru(sc))
1804 ret = sc->nr_reclaimed;
1807 * Now that we've scanned all the zones at this priority level, note
1808 * that level within the zone so that the next thread which performs
1809 * scanning of this zone will immediately start out at this priority
1810 * level. This affects only the decision whether or not to bring
1811 * mapped pages onto the inactive list.
1816 if (scanning_global_lru(sc)) {
1817 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
1819 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1822 zone->prev_priority = priority;
1825 mem_cgroup_record_reclaim_priority(sc->mem_cgroup, priority);
1827 delayacct_freepages_end();
1832 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
1833 gfp_t gfp_mask, nodemask_t *nodemask)
1835 struct scan_control sc = {
1836 .gfp_mask = gfp_mask,
1837 .may_writepage = !laptop_mode,
1838 .swap_cluster_max = SWAP_CLUSTER_MAX,
1839 .nr_to_reclaim = SWAP_CLUSTER_MAX,
1842 .swappiness = vm_swappiness,
1845 .isolate_pages = isolate_pages_global,
1846 .nodemask = nodemask,
1849 return do_try_to_free_pages(zonelist, &sc);
1852 #ifdef CONFIG_CGROUP_MEM_RES_CTLR
1854 unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *mem,
1855 gfp_t gfp_mask, bool noswap,
1856 unsigned int swappiness,
1857 struct zone *zone, int nid)
1859 struct scan_control sc = {
1860 .may_writepage = !laptop_mode,
1862 .may_swap = !noswap,
1863 .swap_cluster_max = SWAP_CLUSTER_MAX,
1864 .swappiness = swappiness,
1867 .isolate_pages = mem_cgroup_isolate_pages,
1869 nodemask_t nm = nodemask_of_node(nid);
1871 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
1872 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
1874 sc.nr_reclaimed = 0;
1877 * NOTE: Although we can get the priority field, using it
1878 * here is not a good idea, since it limits the pages we can scan.
1879 * if we don't reclaim here, the shrink_zone from balance_pgdat
1880 * will pick up pages from other mem cgroup's as well. We hack
1881 * the priority and make it zero.
1883 shrink_zone(0, zone, &sc);
1884 return sc.nr_reclaimed;
1887 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *mem_cont,
1890 unsigned int swappiness)
1892 struct zonelist *zonelist;
1893 struct scan_control sc = {
1894 .may_writepage = !laptop_mode,
1896 .may_swap = !noswap,
1897 .swap_cluster_max = SWAP_CLUSTER_MAX,
1898 .nr_to_reclaim = SWAP_CLUSTER_MAX,
1899 .swappiness = swappiness,
1901 .mem_cgroup = mem_cont,
1902 .isolate_pages = mem_cgroup_isolate_pages,
1903 .nodemask = NULL, /* we don't care the placement */
1906 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
1907 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
1908 zonelist = NODE_DATA(numa_node_id())->node_zonelists;
1909 return do_try_to_free_pages(zonelist, &sc);
1913 /* is kswapd sleeping prematurely? */
1914 static int sleeping_prematurely(pg_data_t *pgdat, int order, long remaining)
1918 /* If a direct reclaimer woke kswapd within HZ/10, it's premature */
1922 /* If after HZ/10, a zone is below the high mark, it's premature */
1923 for (i = 0; i < pgdat->nr_zones; i++) {
1924 struct zone *zone = pgdat->node_zones + i;
1926 if (!populated_zone(zone))
1929 if (!zone_watermark_ok(zone, order, high_wmark_pages(zone),
1938 * For kswapd, balance_pgdat() will work across all this node's zones until
1939 * they are all at high_wmark_pages(zone).
1941 * Returns the number of pages which were actually freed.
1943 * There is special handling here for zones which are full of pinned pages.
1944 * This can happen if the pages are all mlocked, or if they are all used by
1945 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
1946 * What we do is to detect the case where all pages in the zone have been
1947 * scanned twice and there has been zero successful reclaim. Mark the zone as
1948 * dead and from now on, only perform a short scan. Basically we're polling
1949 * the zone for when the problem goes away.
1951 * kswapd scans the zones in the highmem->normal->dma direction. It skips
1952 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
1953 * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
1954 * lower zones regardless of the number of free pages in the lower zones. This
1955 * interoperates with the page allocator fallback scheme to ensure that aging
1956 * of pages is balanced across the zones.
1958 static unsigned long balance_pgdat(pg_data_t *pgdat, int order)
1963 unsigned long total_scanned;
1964 struct reclaim_state *reclaim_state = current->reclaim_state;
1965 struct scan_control sc = {
1966 .gfp_mask = GFP_KERNEL,
1969 .swap_cluster_max = SWAP_CLUSTER_MAX,
1971 * kswapd doesn't want to be bailed out while reclaim. because
1972 * we want to put equal scanning pressure on each zone.
1974 .nr_to_reclaim = ULONG_MAX,
1975 .swappiness = vm_swappiness,
1978 .isolate_pages = isolate_pages_global,
1981 * temp_priority is used to remember the scanning priority at which
1982 * this zone was successfully refilled to
1983 * free_pages == high_wmark_pages(zone).
1985 int temp_priority[MAX_NR_ZONES];
1989 sc.nr_reclaimed = 0;
1990 sc.may_writepage = !laptop_mode;
1991 count_vm_event(PAGEOUTRUN);
1993 for (i = 0; i < pgdat->nr_zones; i++)
1994 temp_priority[i] = DEF_PRIORITY;
1996 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1997 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
1998 unsigned long lru_pages = 0;
1999 int has_under_min_watermark_zone = 0;
2001 /* The swap token gets in the way of swapout... */
2003 disable_swap_token();
2008 * Scan in the highmem->dma direction for the highest
2009 * zone which needs scanning
2011 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
2012 struct zone *zone = pgdat->node_zones + i;
2014 if (!populated_zone(zone))
2017 if (zone_is_all_unreclaimable(zone) &&
2018 priority != DEF_PRIORITY)
2022 * Do some background aging of the anon list, to give
2023 * pages a chance to be referenced before reclaiming.
2025 if (inactive_anon_is_low(zone, &sc))
2026 shrink_active_list(SWAP_CLUSTER_MAX, zone,
2029 if (!zone_watermark_ok(zone, order,
2030 high_wmark_pages(zone), 0, 0)) {
2038 for (i = 0; i <= end_zone; i++) {
2039 struct zone *zone = pgdat->node_zones + i;
2041 lru_pages += zone_reclaimable_pages(zone);
2045 * Now scan the zone in the dma->highmem direction, stopping
2046 * at the last zone which needs scanning.
2048 * We do this because the page allocator works in the opposite
2049 * direction. This prevents the page allocator from allocating
2050 * pages behind kswapd's direction of progress, which would
2051 * cause too much scanning of the lower zones.
2053 for (i = 0; i <= end_zone; i++) {
2054 struct zone *zone = pgdat->node_zones + i;
2058 if (!populated_zone(zone))
2061 if (zone_is_all_unreclaimable(zone) &&
2062 priority != DEF_PRIORITY)
2065 if (!zone_watermark_ok(zone, order,
2066 high_wmark_pages(zone), end_zone, 0))
2068 temp_priority[i] = priority;
2070 note_zone_scanning_priority(zone, priority);
2072 nid = pgdat->node_id;
2073 zid = zone_idx(zone);
2075 * Call soft limit reclaim before calling shrink_zone.
2076 * For now we ignore the return value
2078 mem_cgroup_soft_limit_reclaim(zone, order, sc.gfp_mask,
2081 * We put equal pressure on every zone, unless one
2082 * zone has way too many pages free already.
2084 if (!zone_watermark_ok(zone, order,
2085 8*high_wmark_pages(zone), end_zone, 0))
2086 shrink_zone(priority, zone, &sc);
2087 reclaim_state->reclaimed_slab = 0;
2088 nr_slab = shrink_slab(sc.nr_scanned, GFP_KERNEL,
2090 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
2091 total_scanned += sc.nr_scanned;
2092 if (zone_is_all_unreclaimable(zone))
2094 if (nr_slab == 0 && zone->pages_scanned >=
2095 (zone_reclaimable_pages(zone) * 6))
2097 ZONE_ALL_UNRECLAIMABLE);
2099 * If we've done a decent amount of scanning and
2100 * the reclaim ratio is low, start doing writepage
2101 * even in laptop mode
2103 if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
2104 total_scanned > sc.nr_reclaimed + sc.nr_reclaimed / 2)
2105 sc.may_writepage = 1;
2108 * We are still under min water mark. it mean we have
2109 * GFP_ATOMIC allocation failure risk. Hurry up!
2111 if (!zone_watermark_ok(zone, order, min_wmark_pages(zone),
2113 has_under_min_watermark_zone = 1;
2117 break; /* kswapd: all done */
2119 * OK, kswapd is getting into trouble. Take a nap, then take
2120 * another pass across the zones.
2122 if (total_scanned && (priority < DEF_PRIORITY - 2)) {
2123 if (has_under_min_watermark_zone)
2124 count_vm_event(KSWAPD_SKIP_CONGESTION_WAIT);
2126 congestion_wait(BLK_RW_ASYNC, HZ/10);
2130 * We do this so kswapd doesn't build up large priorities for
2131 * example when it is freeing in parallel with allocators. It
2132 * matches the direct reclaim path behaviour in terms of impact
2133 * on zone->*_priority.
2135 if (sc.nr_reclaimed >= SWAP_CLUSTER_MAX)
2140 * Note within each zone the priority level at which this zone was
2141 * brought into a happy state. So that the next thread which scans this
2142 * zone will start out at that priority level.
2144 for (i = 0; i < pgdat->nr_zones; i++) {
2145 struct zone *zone = pgdat->node_zones + i;
2147 zone->prev_priority = temp_priority[i];
2149 if (!all_zones_ok) {
2155 * Fragmentation may mean that the system cannot be
2156 * rebalanced for high-order allocations in all zones.
2157 * At this point, if nr_reclaimed < SWAP_CLUSTER_MAX,
2158 * it means the zones have been fully scanned and are still
2159 * not balanced. For high-order allocations, there is
2160 * little point trying all over again as kswapd may
2163 * Instead, recheck all watermarks at order-0 as they
2164 * are the most important. If watermarks are ok, kswapd will go
2165 * back to sleep. High-order users can still perform direct
2166 * reclaim if they wish.
2168 if (sc.nr_reclaimed < SWAP_CLUSTER_MAX)
2169 order = sc.order = 0;
2174 return sc.nr_reclaimed;
2178 * The background pageout daemon, started as a kernel thread
2179 * from the init process.
2181 * This basically trickles out pages so that we have _some_
2182 * free memory available even if there is no other activity
2183 * that frees anything up. This is needed for things like routing
2184 * etc, where we otherwise might have all activity going on in
2185 * asynchronous contexts that cannot page things out.
2187 * If there are applications that are active memory-allocators
2188 * (most normal use), this basically shouldn't matter.
2190 static int kswapd(void *p)
2192 unsigned long order;
2193 pg_data_t *pgdat = (pg_data_t*)p;
2194 struct task_struct *tsk = current;
2196 struct reclaim_state reclaim_state = {
2197 .reclaimed_slab = 0,
2199 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
2201 lockdep_set_current_reclaim_state(GFP_KERNEL);
2203 if (!cpumask_empty(cpumask))
2204 set_cpus_allowed_ptr(tsk, cpumask);
2205 current->reclaim_state = &reclaim_state;
2208 * Tell the memory management that we're a "memory allocator",
2209 * and that if we need more memory we should get access to it
2210 * regardless (see "__alloc_pages()"). "kswapd" should
2211 * never get caught in the normal page freeing logic.
2213 * (Kswapd normally doesn't need memory anyway, but sometimes
2214 * you need a small amount of memory in order to be able to
2215 * page out something else, and this flag essentially protects
2216 * us from recursively trying to free more memory as we're
2217 * trying to free the first piece of memory in the first place).
2219 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
2224 unsigned long new_order;
2227 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
2228 new_order = pgdat->kswapd_max_order;
2229 pgdat->kswapd_max_order = 0;
2230 if (order < new_order) {
2232 * Don't sleep if someone wants a larger 'order'
2237 if (!freezing(current) && !kthread_should_stop()) {
2240 /* Try to sleep for a short interval */
2241 if (!sleeping_prematurely(pgdat, order, remaining)) {
2242 remaining = schedule_timeout(HZ/10);
2243 finish_wait(&pgdat->kswapd_wait, &wait);
2244 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
2248 * After a short sleep, check if it was a
2249 * premature sleep. If not, then go fully
2250 * to sleep until explicitly woken up
2252 if (!sleeping_prematurely(pgdat, order, remaining))
2256 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
2258 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
2262 order = pgdat->kswapd_max_order;
2264 finish_wait(&pgdat->kswapd_wait, &wait);
2266 ret = try_to_freeze();
2267 if (kthread_should_stop())
2271 * We can speed up thawing tasks if we don't call balance_pgdat
2272 * after returning from the refrigerator
2275 balance_pgdat(pgdat, order);
2281 * A zone is low on free memory, so wake its kswapd task to service it.
2283 void wakeup_kswapd(struct zone *zone, int order)
2287 if (!populated_zone(zone))
2290 pgdat = zone->zone_pgdat;
2291 if (zone_watermark_ok(zone, order, low_wmark_pages(zone), 0, 0))
2293 if (pgdat->kswapd_max_order < order)
2294 pgdat->kswapd_max_order = order;
2295 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2297 if (!waitqueue_active(&pgdat->kswapd_wait))
2299 wake_up_interruptible(&pgdat->kswapd_wait);
2303 * The reclaimable count would be mostly accurate.
2304 * The less reclaimable pages may be
2305 * - mlocked pages, which will be moved to unevictable list when encountered
2306 * - mapped pages, which may require several travels to be reclaimed
2307 * - dirty pages, which is not "instantly" reclaimable
2309 unsigned long global_reclaimable_pages(void)
2313 nr = global_page_state(NR_ACTIVE_FILE) +
2314 global_page_state(NR_INACTIVE_FILE);
2316 if (nr_swap_pages > 0)
2317 nr += global_page_state(NR_ACTIVE_ANON) +
2318 global_page_state(NR_INACTIVE_ANON);
2323 unsigned long zone_reclaimable_pages(struct zone *zone)
2327 nr = zone_page_state(zone, NR_ACTIVE_FILE) +
2328 zone_page_state(zone, NR_INACTIVE_FILE);
2330 if (nr_swap_pages > 0)
2331 nr += zone_page_state(zone, NR_ACTIVE_ANON) +
2332 zone_page_state(zone, NR_INACTIVE_ANON);
2337 #ifdef CONFIG_HIBERNATION
2339 * Helper function for shrink_all_memory(). Tries to reclaim 'nr_pages' pages
2340 * from LRU lists system-wide, for given pass and priority.
2342 * For pass > 3 we also try to shrink the LRU lists that contain a few pages
2344 static void shrink_all_zones(unsigned long nr_pages, int prio,
2345 int pass, struct scan_control *sc)
2348 unsigned long nr_reclaimed = 0;
2349 struct zone_reclaim_stat *reclaim_stat;
2351 for_each_populated_zone(zone) {
2354 if (zone_is_all_unreclaimable(zone) && prio != DEF_PRIORITY)
2357 for_each_evictable_lru(l) {
2358 enum zone_stat_item ls = NR_LRU_BASE + l;
2359 unsigned long lru_pages = zone_page_state(zone, ls);
2361 /* For pass = 0, we don't shrink the active list */
2362 if (pass == 0 && (l == LRU_ACTIVE_ANON ||
2363 l == LRU_ACTIVE_FILE))
2366 reclaim_stat = get_reclaim_stat(zone, sc);
2367 reclaim_stat->nr_saved_scan[l] +=
2368 (lru_pages >> prio) + 1;
2369 if (reclaim_stat->nr_saved_scan[l]
2370 >= nr_pages || pass > 3) {
2371 unsigned long nr_to_scan;
2373 reclaim_stat->nr_saved_scan[l] = 0;
2374 nr_to_scan = min(nr_pages, lru_pages);
2375 nr_reclaimed += shrink_list(l, nr_to_scan, zone,
2377 if (nr_reclaimed >= nr_pages) {
2378 sc->nr_reclaimed += nr_reclaimed;
2384 sc->nr_reclaimed += nr_reclaimed;
2388 * Try to free `nr_pages' of memory, system-wide, and return the number of
2391 * Rather than trying to age LRUs the aim is to preserve the overall
2392 * LRU order by reclaiming preferentially
2393 * inactive > active > active referenced > active mapped
2395 unsigned long shrink_all_memory(unsigned long nr_pages)
2397 unsigned long lru_pages, nr_slab;
2399 struct reclaim_state reclaim_state;
2400 struct scan_control sc = {
2401 .gfp_mask = GFP_KERNEL,
2404 .isolate_pages = isolate_pages_global,
2408 current->reclaim_state = &reclaim_state;
2410 lru_pages = global_reclaimable_pages();
2411 nr_slab = global_page_state(NR_SLAB_RECLAIMABLE);
2412 /* If slab caches are huge, it's better to hit them first */
2413 while (nr_slab >= lru_pages) {
2414 reclaim_state.reclaimed_slab = 0;
2415 shrink_slab(nr_pages, sc.gfp_mask, lru_pages);
2416 if (!reclaim_state.reclaimed_slab)
2419 sc.nr_reclaimed += reclaim_state.reclaimed_slab;
2420 if (sc.nr_reclaimed >= nr_pages)
2423 nr_slab -= reclaim_state.reclaimed_slab;
2427 * We try to shrink LRUs in 5 passes:
2428 * 0 = Reclaim from inactive_list only
2429 * 1 = Reclaim from active list but don't reclaim mapped
2430 * 2 = 2nd pass of type 1
2431 * 3 = Reclaim mapped (normal reclaim)
2432 * 4 = 2nd pass of type 3
2434 for (pass = 0; pass < 5; pass++) {
2437 /* Force reclaiming mapped pages in the passes #3 and #4 */
2441 for (prio = DEF_PRIORITY; prio >= 0; prio--) {
2442 unsigned long nr_to_scan = nr_pages - sc.nr_reclaimed;
2445 sc.swap_cluster_max = nr_to_scan;
2446 shrink_all_zones(nr_to_scan, prio, pass, &sc);
2447 if (sc.nr_reclaimed >= nr_pages)
2450 reclaim_state.reclaimed_slab = 0;
2451 shrink_slab(sc.nr_scanned, sc.gfp_mask,
2452 global_reclaimable_pages());
2453 sc.nr_reclaimed += reclaim_state.reclaimed_slab;
2454 if (sc.nr_reclaimed >= nr_pages)
2457 if (sc.nr_scanned && prio < DEF_PRIORITY - 2)
2458 congestion_wait(BLK_RW_ASYNC, HZ / 10);
2463 * If sc.nr_reclaimed = 0, we could not shrink LRUs, but there may be
2464 * something in slab caches
2466 if (!sc.nr_reclaimed) {
2468 reclaim_state.reclaimed_slab = 0;
2469 shrink_slab(nr_pages, sc.gfp_mask,
2470 global_reclaimable_pages());
2471 sc.nr_reclaimed += reclaim_state.reclaimed_slab;
2472 } while (sc.nr_reclaimed < nr_pages &&
2473 reclaim_state.reclaimed_slab > 0);
2478 current->reclaim_state = NULL;
2480 return sc.nr_reclaimed;
2482 #endif /* CONFIG_HIBERNATION */
2484 /* It's optimal to keep kswapds on the same CPUs as their memory, but
2485 not required for correctness. So if the last cpu in a node goes
2486 away, we get changed to run anywhere: as the first one comes back,
2487 restore their cpu bindings. */
2488 static int __devinit cpu_callback(struct notifier_block *nfb,
2489 unsigned long action, void *hcpu)
2493 if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
2494 for_each_node_state(nid, N_HIGH_MEMORY) {
2495 pg_data_t *pgdat = NODE_DATA(nid);
2496 const struct cpumask *mask;
2498 mask = cpumask_of_node(pgdat->node_id);
2500 if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
2501 /* One of our CPUs online: restore mask */
2502 set_cpus_allowed_ptr(pgdat->kswapd, mask);
2509 * This kswapd start function will be called by init and node-hot-add.
2510 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
2512 int kswapd_run(int nid)
2514 pg_data_t *pgdat = NODE_DATA(nid);
2520 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
2521 if (IS_ERR(pgdat->kswapd)) {
2522 /* failure at boot is fatal */
2523 BUG_ON(system_state == SYSTEM_BOOTING);
2524 printk("Failed to start kswapd on node %d\n",nid);
2531 * Called by memory hotplug when all memory in a node is offlined.
2533 void kswapd_stop(int nid)
2535 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
2538 kthread_stop(kswapd);
2541 static int __init kswapd_init(void)
2546 for_each_node_state(nid, N_HIGH_MEMORY)
2548 hotcpu_notifier(cpu_callback, 0);
2552 module_init(kswapd_init)
2558 * If non-zero call zone_reclaim when the number of free pages falls below
2561 int zone_reclaim_mode __read_mostly;
2563 #define RECLAIM_OFF 0
2564 #define RECLAIM_ZONE (1<<0) /* Run shrink_inactive_list on the zone */
2565 #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
2566 #define RECLAIM_SWAP (1<<2) /* Swap pages out during reclaim */
2569 * Priority for ZONE_RECLAIM. This determines the fraction of pages
2570 * of a node considered for each zone_reclaim. 4 scans 1/16th of
2573 #define ZONE_RECLAIM_PRIORITY 4
2576 * Percentage of pages in a zone that must be unmapped for zone_reclaim to
2579 int sysctl_min_unmapped_ratio = 1;
2582 * If the number of slab pages in a zone grows beyond this percentage then
2583 * slab reclaim needs to occur.
2585 int sysctl_min_slab_ratio = 5;
2587 static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
2589 unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
2590 unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
2591 zone_page_state(zone, NR_ACTIVE_FILE);
2594 * It's possible for there to be more file mapped pages than
2595 * accounted for by the pages on the file LRU lists because
2596 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
2598 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
2601 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
2602 static long zone_pagecache_reclaimable(struct zone *zone)
2604 long nr_pagecache_reclaimable;
2608 * If RECLAIM_SWAP is set, then all file pages are considered
2609 * potentially reclaimable. Otherwise, we have to worry about
2610 * pages like swapcache and zone_unmapped_file_pages() provides
2613 if (zone_reclaim_mode & RECLAIM_SWAP)
2614 nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
2616 nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
2618 /* If we can't clean pages, remove dirty pages from consideration */
2619 if (!(zone_reclaim_mode & RECLAIM_WRITE))
2620 delta += zone_page_state(zone, NR_FILE_DIRTY);
2622 /* Watch for any possible underflows due to delta */
2623 if (unlikely(delta > nr_pagecache_reclaimable))
2624 delta = nr_pagecache_reclaimable;
2626 return nr_pagecache_reclaimable - delta;
2630 * Try to free up some pages from this zone through reclaim.
2632 static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
2634 /* Minimum pages needed in order to stay on node */
2635 const unsigned long nr_pages = 1 << order;
2636 struct task_struct *p = current;
2637 struct reclaim_state reclaim_state;
2639 struct scan_control sc = {
2640 .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
2641 .may_unmap = !!(zone_reclaim_mode & RECLAIM_SWAP),
2643 .swap_cluster_max = max_t(unsigned long, nr_pages,
2645 .nr_to_reclaim = max_t(unsigned long, nr_pages,
2647 .gfp_mask = gfp_mask,
2648 .swappiness = vm_swappiness,
2650 .isolate_pages = isolate_pages_global,
2652 unsigned long slab_reclaimable;
2654 disable_swap_token();
2657 * We need to be able to allocate from the reserves for RECLAIM_SWAP
2658 * and we also need to be able to write out pages for RECLAIM_WRITE
2661 p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
2662 reclaim_state.reclaimed_slab = 0;
2663 p->reclaim_state = &reclaim_state;
2665 if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
2667 * Free memory by calling shrink zone with increasing
2668 * priorities until we have enough memory freed.
2670 priority = ZONE_RECLAIM_PRIORITY;
2672 note_zone_scanning_priority(zone, priority);
2673 shrink_zone(priority, zone, &sc);
2675 } while (priority >= 0 && sc.nr_reclaimed < nr_pages);
2678 slab_reclaimable = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
2679 if (slab_reclaimable > zone->min_slab_pages) {
2681 * shrink_slab() does not currently allow us to determine how
2682 * many pages were freed in this zone. So we take the current
2683 * number of slab pages and shake the slab until it is reduced
2684 * by the same nr_pages that we used for reclaiming unmapped
2687 * Note that shrink_slab will free memory on all zones and may
2690 while (shrink_slab(sc.nr_scanned, gfp_mask, order) &&
2691 zone_page_state(zone, NR_SLAB_RECLAIMABLE) >
2692 slab_reclaimable - nr_pages)
2696 * Update nr_reclaimed by the number of slab pages we
2697 * reclaimed from this zone.
2699 sc.nr_reclaimed += slab_reclaimable -
2700 zone_page_state(zone, NR_SLAB_RECLAIMABLE);
2703 p->reclaim_state = NULL;
2704 current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
2705 return sc.nr_reclaimed >= nr_pages;
2708 int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
2714 * Zone reclaim reclaims unmapped file backed pages and
2715 * slab pages if we are over the defined limits.
2717 * A small portion of unmapped file backed pages is needed for
2718 * file I/O otherwise pages read by file I/O will be immediately
2719 * thrown out if the zone is overallocated. So we do not reclaim
2720 * if less than a specified percentage of the zone is used by
2721 * unmapped file backed pages.
2723 if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
2724 zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
2725 return ZONE_RECLAIM_FULL;
2727 if (zone_is_all_unreclaimable(zone))
2728 return ZONE_RECLAIM_FULL;
2731 * Do not scan if the allocation should not be delayed.
2733 if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
2734 return ZONE_RECLAIM_NOSCAN;
2737 * Only run zone reclaim on the local zone or on zones that do not
2738 * have associated processors. This will favor the local processor
2739 * over remote processors and spread off node memory allocations
2740 * as wide as possible.
2742 node_id = zone_to_nid(zone);
2743 if (node_state(node_id, N_CPU) && node_id != numa_node_id())
2744 return ZONE_RECLAIM_NOSCAN;
2746 if (zone_test_and_set_flag(zone, ZONE_RECLAIM_LOCKED))
2747 return ZONE_RECLAIM_NOSCAN;
2749 ret = __zone_reclaim(zone, gfp_mask, order);
2750 zone_clear_flag(zone, ZONE_RECLAIM_LOCKED);
2753 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
2760 * page_evictable - test whether a page is evictable
2761 * @page: the page to test
2762 * @vma: the VMA in which the page is or will be mapped, may be NULL
2764 * Test whether page is evictable--i.e., should be placed on active/inactive
2765 * lists vs unevictable list. The vma argument is !NULL when called from the
2766 * fault path to determine how to instantate a new page.
2768 * Reasons page might not be evictable:
2769 * (1) page's mapping marked unevictable
2770 * (2) page is part of an mlocked VMA
2773 int page_evictable(struct page *page, struct vm_area_struct *vma)
2776 if (mapping_unevictable(page_mapping(page)))
2779 if (PageMlocked(page) || (vma && is_mlocked_vma(vma, page)))
2786 * check_move_unevictable_page - check page for evictability and move to appropriate zone lru list
2787 * @page: page to check evictability and move to appropriate lru list
2788 * @zone: zone page is in
2790 * Checks a page for evictability and moves the page to the appropriate
2793 * Restrictions: zone->lru_lock must be held, page must be on LRU and must
2794 * have PageUnevictable set.
2796 static void check_move_unevictable_page(struct page *page, struct zone *zone)
2798 VM_BUG_ON(PageActive(page));
2801 ClearPageUnevictable(page);
2802 if (page_evictable(page, NULL)) {
2803 enum lru_list l = page_lru_base_type(page);
2805 __dec_zone_state(zone, NR_UNEVICTABLE);
2806 list_move(&page->lru, &zone->lru[l].list);
2807 mem_cgroup_move_lists(page, LRU_UNEVICTABLE, l);
2808 __inc_zone_state(zone, NR_INACTIVE_ANON + l);
2809 __count_vm_event(UNEVICTABLE_PGRESCUED);
2812 * rotate unevictable list
2814 SetPageUnevictable(page);
2815 list_move(&page->lru, &zone->lru[LRU_UNEVICTABLE].list);
2816 mem_cgroup_rotate_lru_list(page, LRU_UNEVICTABLE);
2817 if (page_evictable(page, NULL))
2823 * scan_mapping_unevictable_pages - scan an address space for evictable pages
2824 * @mapping: struct address_space to scan for evictable pages
2826 * Scan all pages in mapping. Check unevictable pages for
2827 * evictability and move them to the appropriate zone lru list.
2829 void scan_mapping_unevictable_pages(struct address_space *mapping)
2832 pgoff_t end = (i_size_read(mapping->host) + PAGE_CACHE_SIZE - 1) >>
2835 struct pagevec pvec;
2837 if (mapping->nrpages == 0)
2840 pagevec_init(&pvec, 0);
2841 while (next < end &&
2842 pagevec_lookup(&pvec, mapping, next, PAGEVEC_SIZE)) {
2848 for (i = 0; i < pagevec_count(&pvec); i++) {
2849 struct page *page = pvec.pages[i];
2850 pgoff_t page_index = page->index;
2851 struct zone *pagezone = page_zone(page);
2854 if (page_index > next)
2858 if (pagezone != zone) {
2860 spin_unlock_irq(&zone->lru_lock);
2862 spin_lock_irq(&zone->lru_lock);
2865 if (PageLRU(page) && PageUnevictable(page))
2866 check_move_unevictable_page(page, zone);
2869 spin_unlock_irq(&zone->lru_lock);
2870 pagevec_release(&pvec);
2872 count_vm_events(UNEVICTABLE_PGSCANNED, pg_scanned);
2878 * scan_zone_unevictable_pages - check unevictable list for evictable pages
2879 * @zone - zone of which to scan the unevictable list
2881 * Scan @zone's unevictable LRU lists to check for pages that have become
2882 * evictable. Move those that have to @zone's inactive list where they
2883 * become candidates for reclaim, unless shrink_inactive_zone() decides
2884 * to reactivate them. Pages that are still unevictable are rotated
2885 * back onto @zone's unevictable list.
2887 #define SCAN_UNEVICTABLE_BATCH_SIZE 16UL /* arbitrary lock hold batch size */
2888 static void scan_zone_unevictable_pages(struct zone *zone)
2890 struct list_head *l_unevictable = &zone->lru[LRU_UNEVICTABLE].list;
2892 unsigned long nr_to_scan = zone_page_state(zone, NR_UNEVICTABLE);
2894 while (nr_to_scan > 0) {
2895 unsigned long batch_size = min(nr_to_scan,
2896 SCAN_UNEVICTABLE_BATCH_SIZE);
2898 spin_lock_irq(&zone->lru_lock);
2899 for (scan = 0; scan < batch_size; scan++) {
2900 struct page *page = lru_to_page(l_unevictable);
2902 if (!trylock_page(page))
2905 prefetchw_prev_lru_page(page, l_unevictable, flags);
2907 if (likely(PageLRU(page) && PageUnevictable(page)))
2908 check_move_unevictable_page(page, zone);
2912 spin_unlock_irq(&zone->lru_lock);
2914 nr_to_scan -= batch_size;
2920 * scan_all_zones_unevictable_pages - scan all unevictable lists for evictable pages
2922 * A really big hammer: scan all zones' unevictable LRU lists to check for
2923 * pages that have become evictable. Move those back to the zones'
2924 * inactive list where they become candidates for reclaim.
2925 * This occurs when, e.g., we have unswappable pages on the unevictable lists,
2926 * and we add swap to the system. As such, it runs in the context of a task
2927 * that has possibly/probably made some previously unevictable pages
2930 static void scan_all_zones_unevictable_pages(void)
2934 for_each_zone(zone) {
2935 scan_zone_unevictable_pages(zone);
2940 * scan_unevictable_pages [vm] sysctl handler. On demand re-scan of
2941 * all nodes' unevictable lists for evictable pages
2943 unsigned long scan_unevictable_pages;
2945 int scan_unevictable_handler(struct ctl_table *table, int write,
2946 void __user *buffer,
2947 size_t *length, loff_t *ppos)
2949 proc_doulongvec_minmax(table, write, buffer, length, ppos);
2951 if (write && *(unsigned long *)table->data)
2952 scan_all_zones_unevictable_pages();
2954 scan_unevictable_pages = 0;
2959 * per node 'scan_unevictable_pages' attribute. On demand re-scan of
2960 * a specified node's per zone unevictable lists for evictable pages.
2963 static ssize_t read_scan_unevictable_node(struct sys_device *dev,
2964 struct sysdev_attribute *attr,
2967 return sprintf(buf, "0\n"); /* always zero; should fit... */
2970 static ssize_t write_scan_unevictable_node(struct sys_device *dev,
2971 struct sysdev_attribute *attr,
2972 const char *buf, size_t count)
2974 struct zone *node_zones = NODE_DATA(dev->id)->node_zones;
2977 unsigned long req = strict_strtoul(buf, 10, &res);
2980 return 1; /* zero is no-op */
2982 for (zone = node_zones; zone - node_zones < MAX_NR_ZONES; ++zone) {
2983 if (!populated_zone(zone))
2985 scan_zone_unevictable_pages(zone);
2991 static SYSDEV_ATTR(scan_unevictable_pages, S_IRUGO | S_IWUSR,
2992 read_scan_unevictable_node,
2993 write_scan_unevictable_node);
2995 int scan_unevictable_register_node(struct node *node)
2997 return sysdev_create_file(&node->sysdev, &attr_scan_unevictable_pages);
3000 void scan_unevictable_unregister_node(struct node *node)
3002 sysdev_remove_file(&node->sysdev, &attr_scan_unevictable_pages);