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/file.h>
23 #include <linux/writeback.h>
24 #include <linux/blkdev.h>
25 #include <linux/buffer_head.h> /* for try_to_release_page(),
26 buffer_heads_over_limit */
27 #include <linux/mm_inline.h>
28 #include <linux/pagevec.h>
29 #include <linux/backing-dev.h>
30 #include <linux/rmap.h>
31 #include <linux/topology.h>
32 #include <linux/cpu.h>
33 #include <linux/cpuset.h>
34 #include <linux/notifier.h>
35 #include <linux/rwsem.h>
36 #include <linux/delay.h>
38 #include <asm/tlbflush.h>
39 #include <asm/div64.h>
41 #include <linux/swapops.h>
46 /* Incremented by the number of inactive pages that were scanned */
47 unsigned long nr_scanned;
49 unsigned long nr_mapped; /* From page_state */
51 /* This context's GFP mask */
56 /* Can pages be swapped as part of reclaim? */
59 /* This context's SWAP_CLUSTER_MAX. If freeing memory for
60 * suspend, we effectively ignore SWAP_CLUSTER_MAX.
61 * In this context, it doesn't matter that we scan the
62 * whole list at once. */
69 * The list of shrinker callbacks used by to apply pressure to
74 struct list_head list;
75 int seeks; /* seeks to recreate an obj */
76 long nr; /* objs pending delete */
79 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
81 #ifdef ARCH_HAS_PREFETCH
82 #define prefetch_prev_lru_page(_page, _base, _field) \
84 if ((_page)->lru.prev != _base) { \
87 prev = lru_to_page(&(_page->lru)); \
88 prefetch(&prev->_field); \
92 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
95 #ifdef ARCH_HAS_PREFETCHW
96 #define prefetchw_prev_lru_page(_page, _base, _field) \
98 if ((_page)->lru.prev != _base) { \
101 prev = lru_to_page(&(_page->lru)); \
102 prefetchw(&prev->_field); \
106 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
110 * From 0 .. 100. Higher means more swappy.
112 int vm_swappiness = 60;
113 static long total_memory;
115 static LIST_HEAD(shrinker_list);
116 static DECLARE_RWSEM(shrinker_rwsem);
119 * Add a shrinker callback to be called from the vm
121 struct shrinker *set_shrinker(int seeks, shrinker_t theshrinker)
123 struct shrinker *shrinker;
125 shrinker = kmalloc(sizeof(*shrinker), GFP_KERNEL);
127 shrinker->shrinker = theshrinker;
128 shrinker->seeks = seeks;
130 down_write(&shrinker_rwsem);
131 list_add_tail(&shrinker->list, &shrinker_list);
132 up_write(&shrinker_rwsem);
136 EXPORT_SYMBOL(set_shrinker);
141 void remove_shrinker(struct shrinker *shrinker)
143 down_write(&shrinker_rwsem);
144 list_del(&shrinker->list);
145 up_write(&shrinker_rwsem);
148 EXPORT_SYMBOL(remove_shrinker);
150 #define SHRINK_BATCH 128
152 * Call the shrink functions to age shrinkable caches
154 * Here we assume it costs one seek to replace a lru page and that it also
155 * takes a seek to recreate a cache object. With this in mind we age equal
156 * percentages of the lru and ageable caches. This should balance the seeks
157 * generated by these structures.
159 * If the vm encounted mapped pages on the LRU it increase the pressure on
160 * slab to avoid swapping.
162 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
164 * `lru_pages' represents the number of on-LRU pages in all the zones which
165 * are eligible for the caller's allocation attempt. It is used for balancing
166 * slab reclaim versus page reclaim.
168 * Returns the number of slab objects which we shrunk.
170 unsigned long shrink_slab(unsigned long scanned, gfp_t gfp_mask,
171 unsigned long lru_pages)
173 struct shrinker *shrinker;
174 unsigned long ret = 0;
177 scanned = SWAP_CLUSTER_MAX;
179 if (!down_read_trylock(&shrinker_rwsem))
180 return 1; /* Assume we'll be able to shrink next time */
182 list_for_each_entry(shrinker, &shrinker_list, list) {
183 unsigned long long delta;
184 unsigned long total_scan;
185 unsigned long max_pass = (*shrinker->shrinker)(0, gfp_mask);
187 delta = (4 * scanned) / shrinker->seeks;
189 do_div(delta, lru_pages + 1);
190 shrinker->nr += delta;
191 if (shrinker->nr < 0) {
192 printk(KERN_ERR "%s: nr=%ld\n",
193 __FUNCTION__, shrinker->nr);
194 shrinker->nr = max_pass;
198 * Avoid risking looping forever due to too large nr value:
199 * never try to free more than twice the estimate number of
202 if (shrinker->nr > max_pass * 2)
203 shrinker->nr = max_pass * 2;
205 total_scan = shrinker->nr;
208 while (total_scan >= SHRINK_BATCH) {
209 long this_scan = SHRINK_BATCH;
213 nr_before = (*shrinker->shrinker)(0, gfp_mask);
214 shrink_ret = (*shrinker->shrinker)(this_scan, gfp_mask);
215 if (shrink_ret == -1)
217 if (shrink_ret < nr_before)
218 ret += nr_before - shrink_ret;
219 mod_page_state(slabs_scanned, this_scan);
220 total_scan -= this_scan;
225 shrinker->nr += total_scan;
227 up_read(&shrinker_rwsem);
231 /* Called without lock on whether page is mapped, so answer is unstable */
232 static inline int page_mapping_inuse(struct page *page)
234 struct address_space *mapping;
236 /* Page is in somebody's page tables. */
237 if (page_mapped(page))
240 /* Be more reluctant to reclaim swapcache than pagecache */
241 if (PageSwapCache(page))
244 mapping = page_mapping(page);
248 /* File is mmap'd by somebody? */
249 return mapping_mapped(mapping);
252 static inline int is_page_cache_freeable(struct page *page)
254 return page_count(page) - !!PagePrivate(page) == 2;
257 static int may_write_to_queue(struct backing_dev_info *bdi)
259 if (current->flags & PF_SWAPWRITE)
261 if (!bdi_write_congested(bdi))
263 if (bdi == current->backing_dev_info)
269 * We detected a synchronous write error writing a page out. Probably
270 * -ENOSPC. We need to propagate that into the address_space for a subsequent
271 * fsync(), msync() or close().
273 * The tricky part is that after writepage we cannot touch the mapping: nothing
274 * prevents it from being freed up. But we have a ref on the page and once
275 * that page is locked, the mapping is pinned.
277 * We're allowed to run sleeping lock_page() here because we know the caller has
280 static void handle_write_error(struct address_space *mapping,
281 struct page *page, int error)
284 if (page_mapping(page) == mapping) {
285 if (error == -ENOSPC)
286 set_bit(AS_ENOSPC, &mapping->flags);
288 set_bit(AS_EIO, &mapping->flags);
294 * pageout is called by shrink_page_list() for each dirty page.
295 * Calls ->writepage().
297 pageout_t pageout(struct page *page, struct address_space *mapping)
300 * If the page is dirty, only perform writeback if that write
301 * will be non-blocking. To prevent this allocation from being
302 * stalled by pagecache activity. But note that there may be
303 * stalls if we need to run get_block(). We could test
304 * PagePrivate for that.
306 * If this process is currently in generic_file_write() against
307 * this page's queue, we can perform writeback even if that
310 * If the page is swapcache, write it back even if that would
311 * block, for some throttling. This happens by accident, because
312 * swap_backing_dev_info is bust: it doesn't reflect the
313 * congestion state of the swapdevs. Easy to fix, if needed.
314 * See swapfile.c:page_queue_congested().
316 if (!is_page_cache_freeable(page))
320 * Some data journaling orphaned pages can have
321 * page->mapping == NULL while being dirty with clean buffers.
323 if (PagePrivate(page)) {
324 if (try_to_free_buffers(page)) {
325 ClearPageDirty(page);
326 printk("%s: orphaned page\n", __FUNCTION__);
332 if (mapping->a_ops->writepage == NULL)
333 return PAGE_ACTIVATE;
334 if (!may_write_to_queue(mapping->backing_dev_info))
337 if (clear_page_dirty_for_io(page)) {
339 struct writeback_control wbc = {
340 .sync_mode = WB_SYNC_NONE,
341 .nr_to_write = SWAP_CLUSTER_MAX,
346 SetPageReclaim(page);
347 res = mapping->a_ops->writepage(page, &wbc);
349 handle_write_error(mapping, page, res);
350 if (res == AOP_WRITEPAGE_ACTIVATE) {
351 ClearPageReclaim(page);
352 return PAGE_ACTIVATE;
354 if (!PageWriteback(page)) {
355 /* synchronous write or broken a_ops? */
356 ClearPageReclaim(page);
365 int remove_mapping(struct address_space *mapping, struct page *page)
368 return 0; /* truncate got there first */
370 write_lock_irq(&mapping->tree_lock);
373 * The non-racy check for busy page. It is critical to check
374 * PageDirty _after_ making sure that the page is freeable and
375 * not in use by anybody. (pagecache + us == 2)
377 if (unlikely(page_count(page) != 2))
380 if (unlikely(PageDirty(page)))
383 if (PageSwapCache(page)) {
384 swp_entry_t swap = { .val = page_private(page) };
385 __delete_from_swap_cache(page);
386 write_unlock_irq(&mapping->tree_lock);
388 __put_page(page); /* The pagecache ref */
392 __remove_from_page_cache(page);
393 write_unlock_irq(&mapping->tree_lock);
398 write_unlock_irq(&mapping->tree_lock);
403 * shrink_page_list() returns the number of reclaimed pages
405 static unsigned long shrink_page_list(struct list_head *page_list,
406 struct scan_control *sc)
408 LIST_HEAD(ret_pages);
409 struct pagevec freed_pvec;
411 unsigned long nr_reclaimed = 0;
415 pagevec_init(&freed_pvec, 1);
416 while (!list_empty(page_list)) {
417 struct address_space *mapping;
424 page = lru_to_page(page_list);
425 list_del(&page->lru);
427 if (TestSetPageLocked(page))
430 BUG_ON(PageActive(page));
434 if (!sc->may_swap && page_mapped(page))
437 /* Double the slab pressure for mapped and swapcache pages */
438 if (page_mapped(page) || PageSwapCache(page))
441 if (PageWriteback(page))
444 referenced = page_referenced(page, 1);
445 /* In active use or really unfreeable? Activate it. */
446 if (referenced && page_mapping_inuse(page))
447 goto activate_locked;
451 * Anonymous process memory has backing store?
452 * Try to allocate it some swap space here.
454 if (PageAnon(page) && !PageSwapCache(page))
455 if (!add_to_swap(page, GFP_ATOMIC))
456 goto activate_locked;
457 #endif /* CONFIG_SWAP */
459 mapping = page_mapping(page);
460 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
461 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
464 * The page is mapped into the page tables of one or more
465 * processes. Try to unmap it here.
467 if (page_mapped(page) && mapping) {
468 switch (try_to_unmap(page, 0)) {
470 goto activate_locked;
474 ; /* try to free the page below */
478 if (PageDirty(page)) {
483 if (!sc->may_writepage)
486 /* Page is dirty, try to write it out here */
487 switch(pageout(page, mapping)) {
491 goto activate_locked;
493 if (PageWriteback(page) || PageDirty(page))
496 * A synchronous write - probably a ramdisk. Go
497 * ahead and try to reclaim the page.
499 if (TestSetPageLocked(page))
501 if (PageDirty(page) || PageWriteback(page))
503 mapping = page_mapping(page);
505 ; /* try to free the page below */
510 * If the page has buffers, try to free the buffer mappings
511 * associated with this page. If we succeed we try to free
514 * We do this even if the page is PageDirty().
515 * try_to_release_page() does not perform I/O, but it is
516 * possible for a page to have PageDirty set, but it is actually
517 * clean (all its buffers are clean). This happens if the
518 * buffers were written out directly, with submit_bh(). ext3
519 * will do this, as well as the blockdev mapping.
520 * try_to_release_page() will discover that cleanness and will
521 * drop the buffers and mark the page clean - it can be freed.
523 * Rarely, pages can have buffers and no ->mapping. These are
524 * the pages which were not successfully invalidated in
525 * truncate_complete_page(). We try to drop those buffers here
526 * and if that worked, and the page is no longer mapped into
527 * process address space (page_count == 1) it can be freed.
528 * Otherwise, leave the page on the LRU so it is swappable.
530 if (PagePrivate(page)) {
531 if (!try_to_release_page(page, sc->gfp_mask))
532 goto activate_locked;
533 if (!mapping && page_count(page) == 1)
537 if (!remove_mapping(mapping, page))
543 if (!pagevec_add(&freed_pvec, page))
544 __pagevec_release_nonlru(&freed_pvec);
553 list_add(&page->lru, &ret_pages);
554 BUG_ON(PageLRU(page));
556 list_splice(&ret_pages, page_list);
557 if (pagevec_count(&freed_pvec))
558 __pagevec_release_nonlru(&freed_pvec);
559 mod_page_state(pgactivate, pgactivate);
564 * zone->lru_lock is heavily contended. Some of the functions that
565 * shrink the lists perform better by taking out a batch of pages
566 * and working on them outside the LRU lock.
568 * For pagecache intensive workloads, this function is the hottest
569 * spot in the kernel (apart from copy_*_user functions).
571 * Appropriate locks must be held before calling this function.
573 * @nr_to_scan: The number of pages to look through on the list.
574 * @src: The LRU list to pull pages off.
575 * @dst: The temp list to put pages on to.
576 * @scanned: The number of pages that were scanned.
578 * returns how many pages were moved onto *@dst.
580 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
581 struct list_head *src, struct list_head *dst,
582 unsigned long *scanned)
584 unsigned long nr_taken = 0;
588 for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
589 struct list_head *target;
590 page = lru_to_page(src);
591 prefetchw_prev_lru_page(page, src, flags);
593 BUG_ON(!PageLRU(page));
595 list_del(&page->lru);
597 if (likely(get_page_unless_zero(page))) {
599 * Be careful not to clear PageLRU until after we're
600 * sure the page is not being freed elsewhere -- the
601 * page release code relies on it.
606 } /* else it is being freed elsewhere */
608 list_add(&page->lru, target);
616 * shrink_inactive_list() is a helper for shrink_zone(). It returns the number
619 static unsigned long shrink_inactive_list(unsigned long max_scan,
620 struct zone *zone, struct scan_control *sc)
622 LIST_HEAD(page_list);
624 unsigned long nr_scanned = 0;
625 unsigned long nr_reclaimed = 0;
627 pagevec_init(&pvec, 1);
630 spin_lock_irq(&zone->lru_lock);
633 unsigned long nr_taken;
634 unsigned long nr_scan;
635 unsigned long nr_freed;
637 nr_taken = isolate_lru_pages(sc->swap_cluster_max,
638 &zone->inactive_list,
639 &page_list, &nr_scan);
640 zone->nr_inactive -= nr_taken;
641 zone->pages_scanned += nr_scan;
642 spin_unlock_irq(&zone->lru_lock);
644 nr_scanned += nr_scan;
645 nr_freed = shrink_page_list(&page_list, sc);
646 nr_reclaimed += nr_freed;
648 if (current_is_kswapd()) {
649 __mod_page_state_zone(zone, pgscan_kswapd, nr_scan);
650 __mod_page_state(kswapd_steal, nr_freed);
652 __mod_page_state_zone(zone, pgscan_direct, nr_scan);
653 __mod_page_state_zone(zone, pgsteal, nr_freed);
658 spin_lock(&zone->lru_lock);
660 * Put back any unfreeable pages.
662 while (!list_empty(&page_list)) {
663 page = lru_to_page(&page_list);
664 BUG_ON(PageLRU(page));
666 list_del(&page->lru);
667 if (PageActive(page))
668 add_page_to_active_list(zone, page);
670 add_page_to_inactive_list(zone, page);
671 if (!pagevec_add(&pvec, page)) {
672 spin_unlock_irq(&zone->lru_lock);
673 __pagevec_release(&pvec);
674 spin_lock_irq(&zone->lru_lock);
677 } while (nr_scanned < max_scan);
678 spin_unlock(&zone->lru_lock);
681 pagevec_release(&pvec);
686 * This moves pages from the active list to the inactive list.
688 * We move them the other way if the page is referenced by one or more
689 * processes, from rmap.
691 * If the pages are mostly unmapped, the processing is fast and it is
692 * appropriate to hold zone->lru_lock across the whole operation. But if
693 * the pages are mapped, the processing is slow (page_referenced()) so we
694 * should drop zone->lru_lock around each page. It's impossible to balance
695 * this, so instead we remove the pages from the LRU while processing them.
696 * It is safe to rely on PG_active against the non-LRU pages in here because
697 * nobody will play with that bit on a non-LRU page.
699 * The downside is that we have to touch page->_count against each page.
700 * But we had to alter page->flags anyway.
702 static void shrink_active_list(unsigned long nr_pages, struct zone *zone,
703 struct scan_control *sc)
705 unsigned long pgmoved;
706 int pgdeactivate = 0;
707 unsigned long pgscanned;
708 LIST_HEAD(l_hold); /* The pages which were snipped off */
709 LIST_HEAD(l_inactive); /* Pages to go onto the inactive_list */
710 LIST_HEAD(l_active); /* Pages to go onto the active_list */
713 int reclaim_mapped = 0;
721 * `distress' is a measure of how much trouble we're having
722 * reclaiming pages. 0 -> no problems. 100 -> great trouble.
724 distress = 100 >> zone->prev_priority;
727 * The point of this algorithm is to decide when to start
728 * reclaiming mapped memory instead of just pagecache. Work out
732 mapped_ratio = (sc->nr_mapped * 100) / total_memory;
735 * Now decide how much we really want to unmap some pages. The
736 * mapped ratio is downgraded - just because there's a lot of
737 * mapped memory doesn't necessarily mean that page reclaim
740 * The distress ratio is important - we don't want to start
743 * A 100% value of vm_swappiness overrides this algorithm
746 swap_tendency = mapped_ratio / 2 + distress + sc->swappiness;
749 * Now use this metric to decide whether to start moving mapped
750 * memory onto the inactive list.
752 if (swap_tendency >= 100)
757 spin_lock_irq(&zone->lru_lock);
758 pgmoved = isolate_lru_pages(nr_pages, &zone->active_list,
759 &l_hold, &pgscanned);
760 zone->pages_scanned += pgscanned;
761 zone->nr_active -= pgmoved;
762 spin_unlock_irq(&zone->lru_lock);
764 while (!list_empty(&l_hold)) {
766 page = lru_to_page(&l_hold);
767 list_del(&page->lru);
768 if (page_mapped(page)) {
769 if (!reclaim_mapped ||
770 (total_swap_pages == 0 && PageAnon(page)) ||
771 page_referenced(page, 0)) {
772 list_add(&page->lru, &l_active);
776 list_add(&page->lru, &l_inactive);
779 pagevec_init(&pvec, 1);
781 spin_lock_irq(&zone->lru_lock);
782 while (!list_empty(&l_inactive)) {
783 page = lru_to_page(&l_inactive);
784 prefetchw_prev_lru_page(page, &l_inactive, flags);
785 BUG_ON(PageLRU(page));
787 BUG_ON(!PageActive(page));
788 ClearPageActive(page);
790 list_move(&page->lru, &zone->inactive_list);
792 if (!pagevec_add(&pvec, page)) {
793 zone->nr_inactive += pgmoved;
794 spin_unlock_irq(&zone->lru_lock);
795 pgdeactivate += pgmoved;
797 if (buffer_heads_over_limit)
798 pagevec_strip(&pvec);
799 __pagevec_release(&pvec);
800 spin_lock_irq(&zone->lru_lock);
803 zone->nr_inactive += pgmoved;
804 pgdeactivate += pgmoved;
805 if (buffer_heads_over_limit) {
806 spin_unlock_irq(&zone->lru_lock);
807 pagevec_strip(&pvec);
808 spin_lock_irq(&zone->lru_lock);
812 while (!list_empty(&l_active)) {
813 page = lru_to_page(&l_active);
814 prefetchw_prev_lru_page(page, &l_active, flags);
815 BUG_ON(PageLRU(page));
817 BUG_ON(!PageActive(page));
818 list_move(&page->lru, &zone->active_list);
820 if (!pagevec_add(&pvec, page)) {
821 zone->nr_active += pgmoved;
823 spin_unlock_irq(&zone->lru_lock);
824 __pagevec_release(&pvec);
825 spin_lock_irq(&zone->lru_lock);
828 zone->nr_active += pgmoved;
829 spin_unlock(&zone->lru_lock);
831 __mod_page_state_zone(zone, pgrefill, pgscanned);
832 __mod_page_state(pgdeactivate, pgdeactivate);
835 pagevec_release(&pvec);
839 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
841 static unsigned long shrink_zone(int priority, struct zone *zone,
842 struct scan_control *sc)
844 unsigned long nr_active;
845 unsigned long nr_inactive;
846 unsigned long nr_to_scan;
847 unsigned long nr_reclaimed = 0;
849 atomic_inc(&zone->reclaim_in_progress);
852 * Add one to `nr_to_scan' just to make sure that the kernel will
853 * slowly sift through the active list.
855 zone->nr_scan_active += (zone->nr_active >> priority) + 1;
856 nr_active = zone->nr_scan_active;
857 if (nr_active >= sc->swap_cluster_max)
858 zone->nr_scan_active = 0;
862 zone->nr_scan_inactive += (zone->nr_inactive >> priority) + 1;
863 nr_inactive = zone->nr_scan_inactive;
864 if (nr_inactive >= sc->swap_cluster_max)
865 zone->nr_scan_inactive = 0;
869 while (nr_active || nr_inactive) {
871 nr_to_scan = min(nr_active,
872 (unsigned long)sc->swap_cluster_max);
873 nr_active -= nr_to_scan;
874 shrink_active_list(nr_to_scan, zone, sc);
878 nr_to_scan = min(nr_inactive,
879 (unsigned long)sc->swap_cluster_max);
880 nr_inactive -= nr_to_scan;
881 nr_reclaimed += shrink_inactive_list(nr_to_scan, zone,
886 throttle_vm_writeout();
888 atomic_dec(&zone->reclaim_in_progress);
893 * This is the direct reclaim path, for page-allocating processes. We only
894 * try to reclaim pages from zones which will satisfy the caller's allocation
897 * We reclaim from a zone even if that zone is over pages_high. Because:
898 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
900 * b) The zones may be over pages_high but they must go *over* pages_high to
901 * satisfy the `incremental min' zone defense algorithm.
903 * Returns the number of reclaimed pages.
905 * If a zone is deemed to be full of pinned pages then just give it a light
906 * scan then give up on it.
908 static unsigned long shrink_zones(int priority, struct zone **zones,
909 struct scan_control *sc)
911 unsigned long nr_reclaimed = 0;
914 for (i = 0; zones[i] != NULL; i++) {
915 struct zone *zone = zones[i];
917 if (!populated_zone(zone))
920 if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
923 zone->temp_priority = priority;
924 if (zone->prev_priority > priority)
925 zone->prev_priority = priority;
927 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
928 continue; /* Let kswapd poll it */
930 nr_reclaimed += shrink_zone(priority, zone, sc);
936 * This is the main entry point to direct page reclaim.
938 * If a full scan of the inactive list fails to free enough memory then we
939 * are "out of memory" and something needs to be killed.
941 * If the caller is !__GFP_FS then the probability of a failure is reasonably
942 * high - the zone may be full of dirty or under-writeback pages, which this
943 * caller can't do much about. We kick pdflush and take explicit naps in the
944 * hope that some of these pages can be written. But if the allocating task
945 * holds filesystem locks which prevent writeout this might not work, and the
946 * allocation attempt will fail.
948 unsigned long try_to_free_pages(struct zone **zones, gfp_t gfp_mask)
952 unsigned long total_scanned = 0;
953 unsigned long nr_reclaimed = 0;
954 struct reclaim_state *reclaim_state = current->reclaim_state;
955 unsigned long lru_pages = 0;
957 struct scan_control sc = {
958 .gfp_mask = gfp_mask,
959 .may_writepage = !laptop_mode,
960 .swap_cluster_max = SWAP_CLUSTER_MAX,
962 .swappiness = vm_swappiness,
965 inc_page_state(allocstall);
967 for (i = 0; zones[i] != NULL; i++) {
968 struct zone *zone = zones[i];
970 if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
973 zone->temp_priority = DEF_PRIORITY;
974 lru_pages += zone->nr_active + zone->nr_inactive;
977 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
978 sc.nr_mapped = read_page_state(nr_mapped);
981 disable_swap_token();
982 nr_reclaimed += shrink_zones(priority, zones, &sc);
983 shrink_slab(sc.nr_scanned, gfp_mask, lru_pages);
985 nr_reclaimed += reclaim_state->reclaimed_slab;
986 reclaim_state->reclaimed_slab = 0;
988 total_scanned += sc.nr_scanned;
989 if (nr_reclaimed >= sc.swap_cluster_max) {
995 * Try to write back as many pages as we just scanned. This
996 * tends to cause slow streaming writers to write data to the
997 * disk smoothly, at the dirtying rate, which is nice. But
998 * that's undesirable in laptop mode, where we *want* lumpy
999 * writeout. So in laptop mode, write out the whole world.
1001 if (total_scanned > sc.swap_cluster_max +
1002 sc.swap_cluster_max / 2) {
1003 wakeup_pdflush(laptop_mode ? 0 : total_scanned);
1004 sc.may_writepage = 1;
1007 /* Take a nap, wait for some writeback to complete */
1008 if (sc.nr_scanned && priority < DEF_PRIORITY - 2)
1009 blk_congestion_wait(WRITE, HZ/10);
1012 for (i = 0; zones[i] != 0; i++) {
1013 struct zone *zone = zones[i];
1015 if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
1018 zone->prev_priority = zone->temp_priority;
1024 * For kswapd, balance_pgdat() will work across all this node's zones until
1025 * they are all at pages_high.
1027 * Returns the number of pages which were actually freed.
1029 * There is special handling here for zones which are full of pinned pages.
1030 * This can happen if the pages are all mlocked, or if they are all used by
1031 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
1032 * What we do is to detect the case where all pages in the zone have been
1033 * scanned twice and there has been zero successful reclaim. Mark the zone as
1034 * dead and from now on, only perform a short scan. Basically we're polling
1035 * the zone for when the problem goes away.
1037 * kswapd scans the zones in the highmem->normal->dma direction. It skips
1038 * zones which have free_pages > pages_high, but once a zone is found to have
1039 * free_pages <= pages_high, we scan that zone and the lower zones regardless
1040 * of the number of free pages in the lower zones. This interoperates with
1041 * the page allocator fallback scheme to ensure that aging of pages is balanced
1044 static unsigned long balance_pgdat(pg_data_t *pgdat, int order)
1049 unsigned long total_scanned;
1050 unsigned long nr_reclaimed;
1051 struct reclaim_state *reclaim_state = current->reclaim_state;
1052 struct scan_control sc = {
1053 .gfp_mask = GFP_KERNEL,
1055 .swap_cluster_max = SWAP_CLUSTER_MAX,
1056 .swappiness = vm_swappiness,
1062 sc.may_writepage = !laptop_mode;
1063 sc.nr_mapped = read_page_state(nr_mapped);
1065 inc_page_state(pageoutrun);
1067 for (i = 0; i < pgdat->nr_zones; i++) {
1068 struct zone *zone = pgdat->node_zones + i;
1070 zone->temp_priority = DEF_PRIORITY;
1073 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1074 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
1075 unsigned long lru_pages = 0;
1077 /* The swap token gets in the way of swapout... */
1079 disable_swap_token();
1084 * Scan in the highmem->dma direction for the highest
1085 * zone which needs scanning
1087 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
1088 struct zone *zone = pgdat->node_zones + i;
1090 if (!populated_zone(zone))
1093 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1096 if (!zone_watermark_ok(zone, order, zone->pages_high,
1104 for (i = 0; i <= end_zone; i++) {
1105 struct zone *zone = pgdat->node_zones + i;
1107 lru_pages += zone->nr_active + zone->nr_inactive;
1111 * Now scan the zone in the dma->highmem direction, stopping
1112 * at the last zone which needs scanning.
1114 * We do this because the page allocator works in the opposite
1115 * direction. This prevents the page allocator from allocating
1116 * pages behind kswapd's direction of progress, which would
1117 * cause too much scanning of the lower zones.
1119 for (i = 0; i <= end_zone; i++) {
1120 struct zone *zone = pgdat->node_zones + i;
1123 if (!populated_zone(zone))
1126 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1129 if (!zone_watermark_ok(zone, order, zone->pages_high,
1132 zone->temp_priority = priority;
1133 if (zone->prev_priority > priority)
1134 zone->prev_priority = priority;
1136 nr_reclaimed += shrink_zone(priority, zone, &sc);
1137 reclaim_state->reclaimed_slab = 0;
1138 nr_slab = shrink_slab(sc.nr_scanned, GFP_KERNEL,
1140 nr_reclaimed += reclaim_state->reclaimed_slab;
1141 total_scanned += sc.nr_scanned;
1142 if (zone->all_unreclaimable)
1144 if (nr_slab == 0 && zone->pages_scanned >=
1145 (zone->nr_active + zone->nr_inactive) * 4)
1146 zone->all_unreclaimable = 1;
1148 * If we've done a decent amount of scanning and
1149 * the reclaim ratio is low, start doing writepage
1150 * even in laptop mode
1152 if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
1153 total_scanned > nr_reclaimed + nr_reclaimed / 2)
1154 sc.may_writepage = 1;
1157 break; /* kswapd: all done */
1159 * OK, kswapd is getting into trouble. Take a nap, then take
1160 * another pass across the zones.
1162 if (total_scanned && priority < DEF_PRIORITY - 2)
1163 blk_congestion_wait(WRITE, HZ/10);
1166 * We do this so kswapd doesn't build up large priorities for
1167 * example when it is freeing in parallel with allocators. It
1168 * matches the direct reclaim path behaviour in terms of impact
1169 * on zone->*_priority.
1171 if (nr_reclaimed >= SWAP_CLUSTER_MAX)
1175 for (i = 0; i < pgdat->nr_zones; i++) {
1176 struct zone *zone = pgdat->node_zones + i;
1178 zone->prev_priority = zone->temp_priority;
1180 if (!all_zones_ok) {
1185 return nr_reclaimed;
1189 * The background pageout daemon, started as a kernel thread
1190 * from the init process.
1192 * This basically trickles out pages so that we have _some_
1193 * free memory available even if there is no other activity
1194 * that frees anything up. This is needed for things like routing
1195 * etc, where we otherwise might have all activity going on in
1196 * asynchronous contexts that cannot page things out.
1198 * If there are applications that are active memory-allocators
1199 * (most normal use), this basically shouldn't matter.
1201 static int kswapd(void *p)
1203 unsigned long order;
1204 pg_data_t *pgdat = (pg_data_t*)p;
1205 struct task_struct *tsk = current;
1207 struct reclaim_state reclaim_state = {
1208 .reclaimed_slab = 0,
1212 daemonize("kswapd%d", pgdat->node_id);
1213 cpumask = node_to_cpumask(pgdat->node_id);
1214 if (!cpus_empty(cpumask))
1215 set_cpus_allowed(tsk, cpumask);
1216 current->reclaim_state = &reclaim_state;
1219 * Tell the memory management that we're a "memory allocator",
1220 * and that if we need more memory we should get access to it
1221 * regardless (see "__alloc_pages()"). "kswapd" should
1222 * never get caught in the normal page freeing logic.
1224 * (Kswapd normally doesn't need memory anyway, but sometimes
1225 * you need a small amount of memory in order to be able to
1226 * page out something else, and this flag essentially protects
1227 * us from recursively trying to free more memory as we're
1228 * trying to free the first piece of memory in the first place).
1230 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
1234 unsigned long new_order;
1238 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
1239 new_order = pgdat->kswapd_max_order;
1240 pgdat->kswapd_max_order = 0;
1241 if (order < new_order) {
1243 * Don't sleep if someone wants a larger 'order'
1249 order = pgdat->kswapd_max_order;
1251 finish_wait(&pgdat->kswapd_wait, &wait);
1253 balance_pgdat(pgdat, order);
1259 * A zone is low on free memory, so wake its kswapd task to service it.
1261 void wakeup_kswapd(struct zone *zone, int order)
1265 if (!populated_zone(zone))
1268 pgdat = zone->zone_pgdat;
1269 if (zone_watermark_ok(zone, order, zone->pages_low, 0, 0))
1271 if (pgdat->kswapd_max_order < order)
1272 pgdat->kswapd_max_order = order;
1273 if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
1275 if (!waitqueue_active(&pgdat->kswapd_wait))
1277 wake_up_interruptible(&pgdat->kswapd_wait);
1282 * Helper function for shrink_all_memory(). Tries to reclaim 'nr_pages' pages
1283 * from LRU lists system-wide, for given pass and priority, and returns the
1284 * number of reclaimed pages
1286 * For pass > 3 we also try to shrink the LRU lists that contain a few pages
1288 static unsigned long shrink_all_zones(unsigned long nr_pages, int pass,
1289 int prio, struct scan_control *sc)
1292 unsigned long nr_to_scan, ret = 0;
1294 for_each_zone(zone) {
1296 if (!populated_zone(zone))
1299 if (zone->all_unreclaimable && prio != DEF_PRIORITY)
1302 /* For pass = 0 we don't shrink the active list */
1304 zone->nr_scan_active += (zone->nr_active >> prio) + 1;
1305 if (zone->nr_scan_active >= nr_pages || pass > 3) {
1306 zone->nr_scan_active = 0;
1307 nr_to_scan = min(nr_pages, zone->nr_active);
1308 shrink_active_list(nr_to_scan, zone, sc);
1312 zone->nr_scan_inactive += (zone->nr_inactive >> prio) + 1;
1313 if (zone->nr_scan_inactive >= nr_pages || pass > 3) {
1314 zone->nr_scan_inactive = 0;
1315 nr_to_scan = min(nr_pages, zone->nr_inactive);
1316 ret += shrink_inactive_list(nr_to_scan, zone, sc);
1317 if (ret >= nr_pages)
1326 * Try to free `nr_pages' of memory, system-wide, and return the number of
1329 * Rather than trying to age LRUs the aim is to preserve the overall
1330 * LRU order by reclaiming preferentially
1331 * inactive > active > active referenced > active mapped
1333 unsigned long shrink_all_memory(unsigned long nr_pages)
1335 unsigned long lru_pages, nr_slab;
1336 unsigned long ret = 0;
1338 struct reclaim_state reclaim_state;
1340 struct scan_control sc = {
1341 .gfp_mask = GFP_KERNEL,
1343 .swap_cluster_max = nr_pages,
1345 .swappiness = vm_swappiness,
1348 current->reclaim_state = &reclaim_state;
1352 lru_pages += zone->nr_active + zone->nr_inactive;
1354 nr_slab = read_page_state(nr_slab);
1355 /* If slab caches are huge, it's better to hit them first */
1356 while (nr_slab >= lru_pages) {
1357 reclaim_state.reclaimed_slab = 0;
1358 shrink_slab(nr_pages, sc.gfp_mask, lru_pages);
1359 if (!reclaim_state.reclaimed_slab)
1362 ret += reclaim_state.reclaimed_slab;
1363 if (ret >= nr_pages)
1366 nr_slab -= reclaim_state.reclaimed_slab;
1370 * We try to shrink LRUs in 5 passes:
1371 * 0 = Reclaim from inactive_list only
1372 * 1 = Reclaim from active list but don't reclaim mapped
1373 * 2 = 2nd pass of type 1
1374 * 3 = Reclaim mapped (normal reclaim)
1375 * 4 = 2nd pass of type 3
1377 for (pass = 0; pass < 5; pass++) {
1380 /* Needed for shrinking slab caches later on */
1382 for_each_zone(zone) {
1383 lru_pages += zone->nr_active;
1384 lru_pages += zone->nr_inactive;
1387 /* Force reclaiming mapped pages in the passes #3 and #4 */
1390 sc.swappiness = 100;
1393 for (prio = DEF_PRIORITY; prio >= 0; prio--) {
1394 unsigned long nr_to_scan = nr_pages - ret;
1396 sc.nr_mapped = read_page_state(nr_mapped);
1399 ret += shrink_all_zones(nr_to_scan, prio, pass, &sc);
1400 if (ret >= nr_pages)
1403 reclaim_state.reclaimed_slab = 0;
1404 shrink_slab(sc.nr_scanned, sc.gfp_mask, lru_pages);
1405 ret += reclaim_state.reclaimed_slab;
1406 if (ret >= nr_pages)
1409 if (sc.nr_scanned && prio < DEF_PRIORITY - 2)
1410 blk_congestion_wait(WRITE, HZ / 10);
1417 * If ret = 0, we could not shrink LRUs, but there may be something
1422 reclaim_state.reclaimed_slab = 0;
1423 shrink_slab(nr_pages, sc.gfp_mask, lru_pages);
1424 ret += reclaim_state.reclaimed_slab;
1425 } while (ret < nr_pages && reclaim_state.reclaimed_slab > 0);
1428 current->reclaim_state = NULL;
1434 #ifdef CONFIG_HOTPLUG_CPU
1435 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1436 not required for correctness. So if the last cpu in a node goes
1437 away, we get changed to run anywhere: as the first one comes back,
1438 restore their cpu bindings. */
1439 static int cpu_callback(struct notifier_block *nfb,
1440 unsigned long action, void *hcpu)
1445 if (action == CPU_ONLINE) {
1446 for_each_online_pgdat(pgdat) {
1447 mask = node_to_cpumask(pgdat->node_id);
1448 if (any_online_cpu(mask) != NR_CPUS)
1449 /* One of our CPUs online: restore mask */
1450 set_cpus_allowed(pgdat->kswapd, mask);
1455 #endif /* CONFIG_HOTPLUG_CPU */
1457 static int __init kswapd_init(void)
1462 for_each_online_pgdat(pgdat) {
1465 pid = kernel_thread(kswapd, pgdat, CLONE_KERNEL);
1467 read_lock(&tasklist_lock);
1468 pgdat->kswapd = find_task_by_pid(pid);
1469 read_unlock(&tasklist_lock);
1471 total_memory = nr_free_pagecache_pages();
1472 hotcpu_notifier(cpu_callback, 0);
1476 module_init(kswapd_init)
1482 * If non-zero call zone_reclaim when the number of free pages falls below
1485 * In the future we may add flags to the mode. However, the page allocator
1486 * should only have to check that zone_reclaim_mode != 0 before calling
1489 int zone_reclaim_mode __read_mostly;
1491 #define RECLAIM_OFF 0
1492 #define RECLAIM_ZONE (1<<0) /* Run shrink_cache on the zone */
1493 #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
1494 #define RECLAIM_SWAP (1<<2) /* Swap pages out during reclaim */
1495 #define RECLAIM_SLAB (1<<3) /* Do a global slab shrink if the zone is out of memory */
1498 * Mininum time between zone reclaim scans
1500 int zone_reclaim_interval __read_mostly = 30*HZ;
1503 * Priority for ZONE_RECLAIM. This determines the fraction of pages
1504 * of a node considered for each zone_reclaim. 4 scans 1/16th of
1507 #define ZONE_RECLAIM_PRIORITY 4
1510 * Try to free up some pages from this zone through reclaim.
1512 static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
1514 /* Minimum pages needed in order to stay on node */
1515 const unsigned long nr_pages = 1 << order;
1516 struct task_struct *p = current;
1517 struct reclaim_state reclaim_state;
1519 unsigned long nr_reclaimed = 0;
1520 struct scan_control sc = {
1521 .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
1522 .may_swap = !!(zone_reclaim_mode & RECLAIM_SWAP),
1523 .nr_mapped = read_page_state(nr_mapped),
1524 .swap_cluster_max = max_t(unsigned long, nr_pages,
1526 .gfp_mask = gfp_mask,
1527 .swappiness = vm_swappiness,
1530 disable_swap_token();
1533 * We need to be able to allocate from the reserves for RECLAIM_SWAP
1534 * and we also need to be able to write out pages for RECLAIM_WRITE
1537 p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
1538 reclaim_state.reclaimed_slab = 0;
1539 p->reclaim_state = &reclaim_state;
1542 * Free memory by calling shrink zone with increasing priorities
1543 * until we have enough memory freed.
1545 priority = ZONE_RECLAIM_PRIORITY;
1547 nr_reclaimed += shrink_zone(priority, zone, &sc);
1549 } while (priority >= 0 && nr_reclaimed < nr_pages);
1551 if (nr_reclaimed < nr_pages && (zone_reclaim_mode & RECLAIM_SLAB)) {
1553 * shrink_slab() does not currently allow us to determine how
1554 * many pages were freed in this zone. So we just shake the slab
1555 * a bit and then go off node for this particular allocation
1556 * despite possibly having freed enough memory to allocate in
1557 * this zone. If we freed local memory then the next
1558 * allocations will be local again.
1560 * shrink_slab will free memory on all zones and may take
1563 shrink_slab(sc.nr_scanned, gfp_mask, order);
1566 p->reclaim_state = NULL;
1567 current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
1569 if (nr_reclaimed == 0) {
1571 * We were unable to reclaim enough pages to stay on node. We
1572 * now allow off node accesses for a certain time period before
1573 * trying again to reclaim pages from the local zone.
1575 zone->last_unsuccessful_zone_reclaim = jiffies;
1578 return nr_reclaimed >= nr_pages;
1581 int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
1587 * Do not reclaim if there was a recent unsuccessful attempt at zone
1588 * reclaim. In that case we let allocations go off node for the
1589 * zone_reclaim_interval. Otherwise we would scan for each off-node
1592 if (time_before(jiffies,
1593 zone->last_unsuccessful_zone_reclaim + zone_reclaim_interval))
1597 * Avoid concurrent zone reclaims, do not reclaim in a zone that does
1598 * not have reclaimable pages and if we should not delay the allocation
1601 if (!(gfp_mask & __GFP_WAIT) ||
1602 zone->all_unreclaimable ||
1603 atomic_read(&zone->reclaim_in_progress) > 0 ||
1604 (current->flags & PF_MEMALLOC))
1608 * Only run zone reclaim on the local zone or on zones that do not
1609 * have associated processors. This will favor the local processor
1610 * over remote processors and spread off node memory allocations
1611 * as wide as possible.
1613 node_id = zone->zone_pgdat->node_id;
1614 mask = node_to_cpumask(node_id);
1615 if (!cpus_empty(mask) && node_id != numa_node_id())
1617 return __zone_reclaim(zone, gfp_mask, order);