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>
40 #include <asm/tlbflush.h>
41 #include <asm/div64.h>
43 #include <linux/swapops.h>
48 /* Incremented by the number of inactive pages that were scanned */
49 unsigned long nr_scanned;
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. */
67 int all_unreclaimable;
71 * The list of shrinker callbacks used by to apply pressure to
76 struct list_head list;
77 int seeks; /* seeks to recreate an obj */
78 long nr; /* objs pending delete */
81 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
83 #ifdef ARCH_HAS_PREFETCH
84 #define prefetch_prev_lru_page(_page, _base, _field) \
86 if ((_page)->lru.prev != _base) { \
89 prev = lru_to_page(&(_page->lru)); \
90 prefetch(&prev->_field); \
94 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
97 #ifdef ARCH_HAS_PREFETCHW
98 #define prefetchw_prev_lru_page(_page, _base, _field) \
100 if ((_page)->lru.prev != _base) { \
103 prev = lru_to_page(&(_page->lru)); \
104 prefetchw(&prev->_field); \
108 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
112 * From 0 .. 100. Higher means more swappy.
114 int vm_swappiness = 60;
115 long vm_total_pages; /* The total number of pages which the VM controls */
117 static LIST_HEAD(shrinker_list);
118 static DECLARE_RWSEM(shrinker_rwsem);
121 * Add a shrinker callback to be called from the vm
123 struct shrinker *set_shrinker(int seeks, shrinker_t theshrinker)
125 struct shrinker *shrinker;
127 shrinker = kmalloc(sizeof(*shrinker), GFP_KERNEL);
129 shrinker->shrinker = theshrinker;
130 shrinker->seeks = seeks;
132 down_write(&shrinker_rwsem);
133 list_add_tail(&shrinker->list, &shrinker_list);
134 up_write(&shrinker_rwsem);
138 EXPORT_SYMBOL(set_shrinker);
143 void remove_shrinker(struct shrinker *shrinker)
145 down_write(&shrinker_rwsem);
146 list_del(&shrinker->list);
147 up_write(&shrinker_rwsem);
150 EXPORT_SYMBOL(remove_shrinker);
152 #define SHRINK_BATCH 128
154 * Call the shrink functions to age shrinkable caches
156 * Here we assume it costs one seek to replace a lru page and that it also
157 * takes a seek to recreate a cache object. With this in mind we age equal
158 * percentages of the lru and ageable caches. This should balance the seeks
159 * generated by these structures.
161 * If the vm encounted mapped pages on the LRU it increase the pressure on
162 * slab to avoid swapping.
164 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
166 * `lru_pages' represents the number of on-LRU pages in all the zones which
167 * are eligible for the caller's allocation attempt. It is used for balancing
168 * slab reclaim versus page reclaim.
170 * Returns the number of slab objects which we shrunk.
172 unsigned long shrink_slab(unsigned long scanned, gfp_t gfp_mask,
173 unsigned long lru_pages)
175 struct shrinker *shrinker;
176 unsigned long ret = 0;
179 scanned = SWAP_CLUSTER_MAX;
181 if (!down_read_trylock(&shrinker_rwsem))
182 return 1; /* Assume we'll be able to shrink next time */
184 list_for_each_entry(shrinker, &shrinker_list, list) {
185 unsigned long long delta;
186 unsigned long total_scan;
187 unsigned long max_pass = (*shrinker->shrinker)(0, gfp_mask);
189 delta = (4 * scanned) / shrinker->seeks;
191 do_div(delta, lru_pages + 1);
192 shrinker->nr += delta;
193 if (shrinker->nr < 0) {
194 printk(KERN_ERR "%s: nr=%ld\n",
195 __FUNCTION__, shrinker->nr);
196 shrinker->nr = max_pass;
200 * Avoid risking looping forever due to too large nr value:
201 * never try to free more than twice the estimate number of
204 if (shrinker->nr > max_pass * 2)
205 shrinker->nr = max_pass * 2;
207 total_scan = shrinker->nr;
210 while (total_scan >= SHRINK_BATCH) {
211 long this_scan = SHRINK_BATCH;
215 nr_before = (*shrinker->shrinker)(0, gfp_mask);
216 shrink_ret = (*shrinker->shrinker)(this_scan, gfp_mask);
217 if (shrink_ret == -1)
219 if (shrink_ret < nr_before)
220 ret += nr_before - shrink_ret;
221 count_vm_events(SLABS_SCANNED, this_scan);
222 total_scan -= this_scan;
227 shrinker->nr += total_scan;
229 up_read(&shrinker_rwsem);
233 /* Called without lock on whether page is mapped, so answer is unstable */
234 static inline int page_mapping_inuse(struct page *page)
236 struct address_space *mapping;
238 /* Page is in somebody's page tables. */
239 if (page_mapped(page))
242 /* Be more reluctant to reclaim swapcache than pagecache */
243 if (PageSwapCache(page))
246 mapping = page_mapping(page);
250 /* File is mmap'd by somebody? */
251 return mapping_mapped(mapping);
254 static inline int is_page_cache_freeable(struct page *page)
256 return page_count(page) - !!PagePrivate(page) == 2;
259 static int may_write_to_queue(struct backing_dev_info *bdi)
261 if (current->flags & PF_SWAPWRITE)
263 if (!bdi_write_congested(bdi))
265 if (bdi == current->backing_dev_info)
271 * We detected a synchronous write error writing a page out. Probably
272 * -ENOSPC. We need to propagate that into the address_space for a subsequent
273 * fsync(), msync() or close().
275 * The tricky part is that after writepage we cannot touch the mapping: nothing
276 * prevents it from being freed up. But we have a ref on the page and once
277 * that page is locked, the mapping is pinned.
279 * We're allowed to run sleeping lock_page() here because we know the caller has
282 static void handle_write_error(struct address_space *mapping,
283 struct page *page, int error)
286 if (page_mapping(page) == mapping) {
287 if (error == -ENOSPC)
288 set_bit(AS_ENOSPC, &mapping->flags);
290 set_bit(AS_EIO, &mapping->flags);
295 /* possible outcome of pageout() */
297 /* failed to write page out, page is locked */
299 /* move page to the active list, page is locked */
301 /* page has been sent to the disk successfully, page is unlocked */
303 /* page is clean and locked */
308 * pageout is called by shrink_page_list() for each dirty page.
309 * Calls ->writepage().
311 static pageout_t pageout(struct page *page, struct address_space *mapping)
314 * If the page is dirty, only perform writeback if that write
315 * will be non-blocking. To prevent this allocation from being
316 * stalled by pagecache activity. But note that there may be
317 * stalls if we need to run get_block(). We could test
318 * PagePrivate for that.
320 * If this process is currently in generic_file_write() against
321 * this page's queue, we can perform writeback even if that
324 * If the page is swapcache, write it back even if that would
325 * block, for some throttling. This happens by accident, because
326 * swap_backing_dev_info is bust: it doesn't reflect the
327 * congestion state of the swapdevs. Easy to fix, if needed.
328 * See swapfile.c:page_queue_congested().
330 if (!is_page_cache_freeable(page))
334 * Some data journaling orphaned pages can have
335 * page->mapping == NULL while being dirty with clean buffers.
337 if (PagePrivate(page)) {
338 if (try_to_free_buffers(page)) {
339 ClearPageDirty(page);
340 printk("%s: orphaned page\n", __FUNCTION__);
346 if (mapping->a_ops->writepage == NULL)
347 return PAGE_ACTIVATE;
348 if (!may_write_to_queue(mapping->backing_dev_info))
351 if (clear_page_dirty_for_io(page)) {
353 struct writeback_control wbc = {
354 .sync_mode = WB_SYNC_NONE,
355 .nr_to_write = SWAP_CLUSTER_MAX,
357 .range_end = LLONG_MAX,
362 SetPageReclaim(page);
363 res = mapping->a_ops->writepage(page, &wbc);
365 handle_write_error(mapping, page, res);
366 if (res == AOP_WRITEPAGE_ACTIVATE) {
367 ClearPageReclaim(page);
368 return PAGE_ACTIVATE;
370 if (!PageWriteback(page)) {
371 /* synchronous write or broken a_ops? */
372 ClearPageReclaim(page);
374 inc_zone_page_state(page, NR_VMSCAN_WRITE);
382 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
383 * someone else has a ref on the page, abort and return 0. If it was
384 * successfully detached, return 1. Assumes the caller has a single ref on
387 int remove_mapping(struct address_space *mapping, struct page *page)
389 BUG_ON(!PageLocked(page));
390 BUG_ON(mapping != page_mapping(page));
392 write_lock_irq(&mapping->tree_lock);
394 * The non racy check for a busy page.
396 * Must be careful with the order of the tests. When someone has
397 * a ref to the page, it may be possible that they dirty it then
398 * drop the reference. So if PageDirty is tested before page_count
399 * here, then the following race may occur:
401 * get_user_pages(&page);
402 * [user mapping goes away]
404 * !PageDirty(page) [good]
405 * SetPageDirty(page);
407 * !page_count(page) [good, discard it]
409 * [oops, our write_to data is lost]
411 * Reversing the order of the tests ensures such a situation cannot
412 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
413 * load is not satisfied before that of page->_count.
415 * Note that if SetPageDirty is always performed via set_page_dirty,
416 * and thus under tree_lock, then this ordering is not required.
418 if (unlikely(page_count(page) != 2))
421 if (unlikely(PageDirty(page)))
424 if (PageSwapCache(page)) {
425 swp_entry_t swap = { .val = page_private(page) };
426 __delete_from_swap_cache(page);
427 write_unlock_irq(&mapping->tree_lock);
429 __put_page(page); /* The pagecache ref */
433 __remove_from_page_cache(page);
434 write_unlock_irq(&mapping->tree_lock);
439 write_unlock_irq(&mapping->tree_lock);
444 * shrink_page_list() returns the number of reclaimed pages
446 static unsigned long shrink_page_list(struct list_head *page_list,
447 struct scan_control *sc)
449 LIST_HEAD(ret_pages);
450 struct pagevec freed_pvec;
452 unsigned long nr_reclaimed = 0;
456 pagevec_init(&freed_pvec, 1);
457 while (!list_empty(page_list)) {
458 struct address_space *mapping;
465 page = lru_to_page(page_list);
466 list_del(&page->lru);
468 if (TestSetPageLocked(page))
471 VM_BUG_ON(PageActive(page));
475 if (!sc->may_swap && page_mapped(page))
478 /* Double the slab pressure for mapped and swapcache pages */
479 if (page_mapped(page) || PageSwapCache(page))
482 if (PageWriteback(page))
485 referenced = page_referenced(page, 1);
486 /* In active use or really unfreeable? Activate it. */
487 if (referenced && page_mapping_inuse(page))
488 goto activate_locked;
492 * Anonymous process memory has backing store?
493 * Try to allocate it some swap space here.
495 if (PageAnon(page) && !PageSwapCache(page))
496 if (!add_to_swap(page, GFP_ATOMIC))
497 goto activate_locked;
498 #endif /* CONFIG_SWAP */
500 mapping = page_mapping(page);
501 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
502 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
505 * The page is mapped into the page tables of one or more
506 * processes. Try to unmap it here.
508 if (page_mapped(page) && mapping) {
509 switch (try_to_unmap(page, 0)) {
511 goto activate_locked;
515 ; /* try to free the page below */
519 if (PageDirty(page)) {
524 if (!sc->may_writepage)
527 /* Page is dirty, try to write it out here */
528 switch(pageout(page, mapping)) {
532 goto activate_locked;
534 if (PageWriteback(page) || PageDirty(page))
537 * A synchronous write - probably a ramdisk. Go
538 * ahead and try to reclaim the page.
540 if (TestSetPageLocked(page))
542 if (PageDirty(page) || PageWriteback(page))
544 mapping = page_mapping(page);
546 ; /* try to free the page below */
551 * If the page has buffers, try to free the buffer mappings
552 * associated with this page. If we succeed we try to free
555 * We do this even if the page is PageDirty().
556 * try_to_release_page() does not perform I/O, but it is
557 * possible for a page to have PageDirty set, but it is actually
558 * clean (all its buffers are clean). This happens if the
559 * buffers were written out directly, with submit_bh(). ext3
560 * will do this, as well as the blockdev mapping.
561 * try_to_release_page() will discover that cleanness and will
562 * drop the buffers and mark the page clean - it can be freed.
564 * Rarely, pages can have buffers and no ->mapping. These are
565 * the pages which were not successfully invalidated in
566 * truncate_complete_page(). We try to drop those buffers here
567 * and if that worked, and the page is no longer mapped into
568 * process address space (page_count == 1) it can be freed.
569 * Otherwise, leave the page on the LRU so it is swappable.
571 if (PagePrivate(page)) {
572 if (!try_to_release_page(page, sc->gfp_mask))
573 goto activate_locked;
574 if (!mapping && page_count(page) == 1)
578 if (!mapping || !remove_mapping(mapping, page))
584 if (!pagevec_add(&freed_pvec, page))
585 __pagevec_release_nonlru(&freed_pvec);
594 list_add(&page->lru, &ret_pages);
595 VM_BUG_ON(PageLRU(page));
597 list_splice(&ret_pages, page_list);
598 if (pagevec_count(&freed_pvec))
599 __pagevec_release_nonlru(&freed_pvec);
600 count_vm_events(PGACTIVATE, pgactivate);
605 * zone->lru_lock is heavily contended. Some of the functions that
606 * shrink the lists perform better by taking out a batch of pages
607 * and working on them outside the LRU lock.
609 * For pagecache intensive workloads, this function is the hottest
610 * spot in the kernel (apart from copy_*_user functions).
612 * Appropriate locks must be held before calling this function.
614 * @nr_to_scan: The number of pages to look through on the list.
615 * @src: The LRU list to pull pages off.
616 * @dst: The temp list to put pages on to.
617 * @scanned: The number of pages that were scanned.
619 * returns how many pages were moved onto *@dst.
621 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
622 struct list_head *src, struct list_head *dst,
623 unsigned long *scanned)
625 unsigned long nr_taken = 0;
629 for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
630 struct list_head *target;
631 page = lru_to_page(src);
632 prefetchw_prev_lru_page(page, src, flags);
634 VM_BUG_ON(!PageLRU(page));
636 list_del(&page->lru);
638 if (likely(get_page_unless_zero(page))) {
640 * Be careful not to clear PageLRU until after we're
641 * sure the page is not being freed elsewhere -- the
642 * page release code relies on it.
647 } /* else it is being freed elsewhere */
649 list_add(&page->lru, target);
657 * shrink_inactive_list() is a helper for shrink_zone(). It returns the number
660 static unsigned long shrink_inactive_list(unsigned long max_scan,
661 struct zone *zone, struct scan_control *sc)
663 LIST_HEAD(page_list);
665 unsigned long nr_scanned = 0;
666 unsigned long nr_reclaimed = 0;
668 pagevec_init(&pvec, 1);
671 spin_lock_irq(&zone->lru_lock);
674 unsigned long nr_taken;
675 unsigned long nr_scan;
676 unsigned long nr_freed;
678 nr_taken = isolate_lru_pages(sc->swap_cluster_max,
679 &zone->inactive_list,
680 &page_list, &nr_scan);
681 zone->nr_inactive -= nr_taken;
682 zone->pages_scanned += nr_scan;
683 spin_unlock_irq(&zone->lru_lock);
685 nr_scanned += nr_scan;
686 nr_freed = shrink_page_list(&page_list, sc);
687 nr_reclaimed += nr_freed;
689 if (current_is_kswapd()) {
690 __count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scan);
691 __count_vm_events(KSWAPD_STEAL, nr_freed);
693 __count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scan);
694 __count_vm_events(PGACTIVATE, nr_freed);
699 spin_lock(&zone->lru_lock);
701 * Put back any unfreeable pages.
703 while (!list_empty(&page_list)) {
704 page = lru_to_page(&page_list);
705 VM_BUG_ON(PageLRU(page));
707 list_del(&page->lru);
708 if (PageActive(page))
709 add_page_to_active_list(zone, page);
711 add_page_to_inactive_list(zone, page);
712 if (!pagevec_add(&pvec, page)) {
713 spin_unlock_irq(&zone->lru_lock);
714 __pagevec_release(&pvec);
715 spin_lock_irq(&zone->lru_lock);
718 } while (nr_scanned < max_scan);
719 spin_unlock(&zone->lru_lock);
722 pagevec_release(&pvec);
727 * We are about to scan this zone at a certain priority level. If that priority
728 * level is smaller (ie: more urgent) than the previous priority, then note
729 * that priority level within the zone. This is done so that when the next
730 * process comes in to scan this zone, it will immediately start out at this
731 * priority level rather than having to build up its own scanning priority.
732 * Here, this priority affects only the reclaim-mapped threshold.
734 static inline void note_zone_scanning_priority(struct zone *zone, int priority)
736 if (priority < zone->prev_priority)
737 zone->prev_priority = priority;
740 static inline int zone_is_near_oom(struct zone *zone)
742 return zone->pages_scanned >= (zone->nr_active + zone->nr_inactive)*3;
746 * This moves pages from the active list to the inactive list.
748 * We move them the other way if the page is referenced by one or more
749 * processes, from rmap.
751 * If the pages are mostly unmapped, the processing is fast and it is
752 * appropriate to hold zone->lru_lock across the whole operation. But if
753 * the pages are mapped, the processing is slow (page_referenced()) so we
754 * should drop zone->lru_lock around each page. It's impossible to balance
755 * this, so instead we remove the pages from the LRU while processing them.
756 * It is safe to rely on PG_active against the non-LRU pages in here because
757 * nobody will play with that bit on a non-LRU page.
759 * The downside is that we have to touch page->_count against each page.
760 * But we had to alter page->flags anyway.
762 static void shrink_active_list(unsigned long nr_pages, struct zone *zone,
763 struct scan_control *sc, int priority)
765 unsigned long pgmoved;
766 int pgdeactivate = 0;
767 unsigned long pgscanned;
768 LIST_HEAD(l_hold); /* The pages which were snipped off */
769 LIST_HEAD(l_inactive); /* Pages to go onto the inactive_list */
770 LIST_HEAD(l_active); /* Pages to go onto the active_list */
773 int reclaim_mapped = 0;
780 if (zone_is_near_oom(zone))
781 goto force_reclaim_mapped;
784 * `distress' is a measure of how much trouble we're having
785 * reclaiming pages. 0 -> no problems. 100 -> great trouble.
787 distress = 100 >> min(zone->prev_priority, priority);
790 * The point of this algorithm is to decide when to start
791 * reclaiming mapped memory instead of just pagecache. Work out
795 mapped_ratio = ((global_page_state(NR_FILE_MAPPED) +
796 global_page_state(NR_ANON_PAGES)) * 100) /
800 * Now decide how much we really want to unmap some pages. The
801 * mapped ratio is downgraded - just because there's a lot of
802 * mapped memory doesn't necessarily mean that page reclaim
805 * The distress ratio is important - we don't want to start
808 * A 100% value of vm_swappiness overrides this algorithm
811 swap_tendency = mapped_ratio / 2 + distress + sc->swappiness;
814 * Now use this metric to decide whether to start moving mapped
815 * memory onto the inactive list.
817 if (swap_tendency >= 100)
818 force_reclaim_mapped:
823 spin_lock_irq(&zone->lru_lock);
824 pgmoved = isolate_lru_pages(nr_pages, &zone->active_list,
825 &l_hold, &pgscanned);
826 zone->pages_scanned += pgscanned;
827 zone->nr_active -= pgmoved;
828 spin_unlock_irq(&zone->lru_lock);
830 while (!list_empty(&l_hold)) {
832 page = lru_to_page(&l_hold);
833 list_del(&page->lru);
834 if (page_mapped(page)) {
835 if (!reclaim_mapped ||
836 (total_swap_pages == 0 && PageAnon(page)) ||
837 page_referenced(page, 0)) {
838 list_add(&page->lru, &l_active);
842 list_add(&page->lru, &l_inactive);
845 pagevec_init(&pvec, 1);
847 spin_lock_irq(&zone->lru_lock);
848 while (!list_empty(&l_inactive)) {
849 page = lru_to_page(&l_inactive);
850 prefetchw_prev_lru_page(page, &l_inactive, flags);
851 VM_BUG_ON(PageLRU(page));
853 VM_BUG_ON(!PageActive(page));
854 ClearPageActive(page);
856 list_move(&page->lru, &zone->inactive_list);
858 if (!pagevec_add(&pvec, page)) {
859 zone->nr_inactive += pgmoved;
860 spin_unlock_irq(&zone->lru_lock);
861 pgdeactivate += pgmoved;
863 if (buffer_heads_over_limit)
864 pagevec_strip(&pvec);
865 __pagevec_release(&pvec);
866 spin_lock_irq(&zone->lru_lock);
869 zone->nr_inactive += pgmoved;
870 pgdeactivate += pgmoved;
871 if (buffer_heads_over_limit) {
872 spin_unlock_irq(&zone->lru_lock);
873 pagevec_strip(&pvec);
874 spin_lock_irq(&zone->lru_lock);
878 while (!list_empty(&l_active)) {
879 page = lru_to_page(&l_active);
880 prefetchw_prev_lru_page(page, &l_active, flags);
881 VM_BUG_ON(PageLRU(page));
883 VM_BUG_ON(!PageActive(page));
884 list_move(&page->lru, &zone->active_list);
886 if (!pagevec_add(&pvec, page)) {
887 zone->nr_active += pgmoved;
889 spin_unlock_irq(&zone->lru_lock);
890 __pagevec_release(&pvec);
891 spin_lock_irq(&zone->lru_lock);
894 zone->nr_active += pgmoved;
896 __count_zone_vm_events(PGREFILL, zone, pgscanned);
897 __count_vm_events(PGDEACTIVATE, pgdeactivate);
898 spin_unlock_irq(&zone->lru_lock);
900 pagevec_release(&pvec);
904 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
906 static unsigned long shrink_zone(int priority, struct zone *zone,
907 struct scan_control *sc)
909 unsigned long nr_active;
910 unsigned long nr_inactive;
911 unsigned long nr_to_scan;
912 unsigned long nr_reclaimed = 0;
914 atomic_inc(&zone->reclaim_in_progress);
917 * Add one to `nr_to_scan' just to make sure that the kernel will
918 * slowly sift through the active list.
920 zone->nr_scan_active += (zone->nr_active >> priority) + 1;
921 nr_active = zone->nr_scan_active;
922 if (nr_active >= sc->swap_cluster_max)
923 zone->nr_scan_active = 0;
927 zone->nr_scan_inactive += (zone->nr_inactive >> priority) + 1;
928 nr_inactive = zone->nr_scan_inactive;
929 if (nr_inactive >= sc->swap_cluster_max)
930 zone->nr_scan_inactive = 0;
934 while (nr_active || nr_inactive) {
936 nr_to_scan = min(nr_active,
937 (unsigned long)sc->swap_cluster_max);
938 nr_active -= nr_to_scan;
939 shrink_active_list(nr_to_scan, zone, sc, priority);
943 nr_to_scan = min(nr_inactive,
944 (unsigned long)sc->swap_cluster_max);
945 nr_inactive -= nr_to_scan;
946 nr_reclaimed += shrink_inactive_list(nr_to_scan, zone,
951 throttle_vm_writeout();
953 atomic_dec(&zone->reclaim_in_progress);
958 * This is the direct reclaim path, for page-allocating processes. We only
959 * try to reclaim pages from zones which will satisfy the caller's allocation
962 * We reclaim from a zone even if that zone is over pages_high. Because:
963 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
965 * b) The zones may be over pages_high but they must go *over* pages_high to
966 * satisfy the `incremental min' zone defense algorithm.
968 * Returns the number of reclaimed pages.
970 * If a zone is deemed to be full of pinned pages then just give it a light
971 * scan then give up on it.
973 static unsigned long shrink_zones(int priority, struct zone **zones,
974 struct scan_control *sc)
976 unsigned long nr_reclaimed = 0;
979 sc->all_unreclaimable = 1;
980 for (i = 0; zones[i] != NULL; i++) {
981 struct zone *zone = zones[i];
983 if (!populated_zone(zone))
986 if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
989 note_zone_scanning_priority(zone, priority);
991 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
992 continue; /* Let kswapd poll it */
994 sc->all_unreclaimable = 0;
996 nr_reclaimed += shrink_zone(priority, zone, sc);
1002 * This is the main entry point to direct page reclaim.
1004 * If a full scan of the inactive list fails to free enough memory then we
1005 * are "out of memory" and something needs to be killed.
1007 * If the caller is !__GFP_FS then the probability of a failure is reasonably
1008 * high - the zone may be full of dirty or under-writeback pages, which this
1009 * caller can't do much about. We kick pdflush and take explicit naps in the
1010 * hope that some of these pages can be written. But if the allocating task
1011 * holds filesystem locks which prevent writeout this might not work, and the
1012 * allocation attempt will fail.
1014 unsigned long try_to_free_pages(struct zone **zones, gfp_t gfp_mask)
1018 unsigned long total_scanned = 0;
1019 unsigned long nr_reclaimed = 0;
1020 struct reclaim_state *reclaim_state = current->reclaim_state;
1021 unsigned long lru_pages = 0;
1023 struct scan_control sc = {
1024 .gfp_mask = gfp_mask,
1025 .may_writepage = !laptop_mode,
1026 .swap_cluster_max = SWAP_CLUSTER_MAX,
1028 .swappiness = vm_swappiness,
1031 count_vm_event(ALLOCSTALL);
1033 for (i = 0; zones[i] != NULL; i++) {
1034 struct zone *zone = zones[i];
1036 if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
1039 lru_pages += zone->nr_active + zone->nr_inactive;
1042 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1045 disable_swap_token();
1046 nr_reclaimed += shrink_zones(priority, zones, &sc);
1047 shrink_slab(sc.nr_scanned, gfp_mask, lru_pages);
1048 if (reclaim_state) {
1049 nr_reclaimed += reclaim_state->reclaimed_slab;
1050 reclaim_state->reclaimed_slab = 0;
1052 total_scanned += sc.nr_scanned;
1053 if (nr_reclaimed >= sc.swap_cluster_max) {
1059 * Try to write back as many pages as we just scanned. This
1060 * tends to cause slow streaming writers to write data to the
1061 * disk smoothly, at the dirtying rate, which is nice. But
1062 * that's undesirable in laptop mode, where we *want* lumpy
1063 * writeout. So in laptop mode, write out the whole world.
1065 if (total_scanned > sc.swap_cluster_max +
1066 sc.swap_cluster_max / 2) {
1067 wakeup_pdflush(laptop_mode ? 0 : total_scanned);
1068 sc.may_writepage = 1;
1071 /* Take a nap, wait for some writeback to complete */
1072 if (sc.nr_scanned && priority < DEF_PRIORITY - 2)
1073 congestion_wait(WRITE, HZ/10);
1075 /* top priority shrink_caches still had more to do? don't OOM, then */
1076 if (!sc.all_unreclaimable)
1080 * Now that we've scanned all the zones at this priority level, note
1081 * that level within the zone so that the next thread which performs
1082 * scanning of this zone will immediately start out at this priority
1083 * level. This affects only the decision whether or not to bring
1084 * mapped pages onto the inactive list.
1088 for (i = 0; zones[i] != 0; i++) {
1089 struct zone *zone = zones[i];
1091 if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
1094 zone->prev_priority = priority;
1100 * For kswapd, balance_pgdat() will work across all this node's zones until
1101 * they are all at pages_high.
1103 * Returns the number of pages which were actually freed.
1105 * There is special handling here for zones which are full of pinned pages.
1106 * This can happen if the pages are all mlocked, or if they are all used by
1107 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
1108 * What we do is to detect the case where all pages in the zone have been
1109 * scanned twice and there has been zero successful reclaim. Mark the zone as
1110 * dead and from now on, only perform a short scan. Basically we're polling
1111 * the zone for when the problem goes away.
1113 * kswapd scans the zones in the highmem->normal->dma direction. It skips
1114 * zones which have free_pages > pages_high, but once a zone is found to have
1115 * free_pages <= pages_high, we scan that zone and the lower zones regardless
1116 * of the number of free pages in the lower zones. This interoperates with
1117 * the page allocator fallback scheme to ensure that aging of pages is balanced
1120 static unsigned long balance_pgdat(pg_data_t *pgdat, int order)
1125 unsigned long total_scanned;
1126 unsigned long nr_reclaimed;
1127 struct reclaim_state *reclaim_state = current->reclaim_state;
1128 struct scan_control sc = {
1129 .gfp_mask = GFP_KERNEL,
1131 .swap_cluster_max = SWAP_CLUSTER_MAX,
1132 .swappiness = vm_swappiness,
1135 * temp_priority is used to remember the scanning priority at which
1136 * this zone was successfully refilled to free_pages == pages_high.
1138 int temp_priority[MAX_NR_ZONES];
1143 sc.may_writepage = !laptop_mode;
1144 count_vm_event(PAGEOUTRUN);
1146 for (i = 0; i < pgdat->nr_zones; i++)
1147 temp_priority[i] = DEF_PRIORITY;
1149 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1150 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
1151 unsigned long lru_pages = 0;
1153 /* The swap token gets in the way of swapout... */
1155 disable_swap_token();
1160 * Scan in the highmem->dma direction for the highest
1161 * zone which needs scanning
1163 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
1164 struct zone *zone = pgdat->node_zones + i;
1166 if (!populated_zone(zone))
1169 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1172 if (!zone_watermark_ok(zone, order, zone->pages_high,
1181 for (i = 0; i <= end_zone; i++) {
1182 struct zone *zone = pgdat->node_zones + i;
1184 lru_pages += zone->nr_active + zone->nr_inactive;
1188 * Now scan the zone in the dma->highmem direction, stopping
1189 * at the last zone which needs scanning.
1191 * We do this because the page allocator works in the opposite
1192 * direction. This prevents the page allocator from allocating
1193 * pages behind kswapd's direction of progress, which would
1194 * cause too much scanning of the lower zones.
1196 for (i = 0; i <= end_zone; i++) {
1197 struct zone *zone = pgdat->node_zones + i;
1200 if (!populated_zone(zone))
1203 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1206 if (!zone_watermark_ok(zone, order, zone->pages_high,
1209 temp_priority[i] = priority;
1211 note_zone_scanning_priority(zone, priority);
1212 nr_reclaimed += shrink_zone(priority, zone, &sc);
1213 reclaim_state->reclaimed_slab = 0;
1214 nr_slab = shrink_slab(sc.nr_scanned, GFP_KERNEL,
1216 nr_reclaimed += reclaim_state->reclaimed_slab;
1217 total_scanned += sc.nr_scanned;
1218 if (zone->all_unreclaimable)
1220 if (nr_slab == 0 && zone->pages_scanned >=
1221 (zone->nr_active + zone->nr_inactive) * 6)
1222 zone->all_unreclaimable = 1;
1224 * If we've done a decent amount of scanning and
1225 * the reclaim ratio is low, start doing writepage
1226 * even in laptop mode
1228 if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
1229 total_scanned > nr_reclaimed + nr_reclaimed / 2)
1230 sc.may_writepage = 1;
1233 break; /* kswapd: all done */
1235 * OK, kswapd is getting into trouble. Take a nap, then take
1236 * another pass across the zones.
1238 if (total_scanned && priority < DEF_PRIORITY - 2)
1239 congestion_wait(WRITE, HZ/10);
1242 * We do this so kswapd doesn't build up large priorities for
1243 * example when it is freeing in parallel with allocators. It
1244 * matches the direct reclaim path behaviour in terms of impact
1245 * on zone->*_priority.
1247 if (nr_reclaimed >= SWAP_CLUSTER_MAX)
1252 * Note within each zone the priority level at which this zone was
1253 * brought into a happy state. So that the next thread which scans this
1254 * zone will start out at that priority level.
1256 for (i = 0; i < pgdat->nr_zones; i++) {
1257 struct zone *zone = pgdat->node_zones + i;
1259 zone->prev_priority = temp_priority[i];
1261 if (!all_zones_ok) {
1266 return nr_reclaimed;
1270 * The background pageout daemon, started as a kernel thread
1271 * from the init process.
1273 * This basically trickles out pages so that we have _some_
1274 * free memory available even if there is no other activity
1275 * that frees anything up. This is needed for things like routing
1276 * etc, where we otherwise might have all activity going on in
1277 * asynchronous contexts that cannot page things out.
1279 * If there are applications that are active memory-allocators
1280 * (most normal use), this basically shouldn't matter.
1282 static int kswapd(void *p)
1284 unsigned long order;
1285 pg_data_t *pgdat = (pg_data_t*)p;
1286 struct task_struct *tsk = current;
1288 struct reclaim_state reclaim_state = {
1289 .reclaimed_slab = 0,
1293 cpumask = node_to_cpumask(pgdat->node_id);
1294 if (!cpus_empty(cpumask))
1295 set_cpus_allowed(tsk, cpumask);
1296 current->reclaim_state = &reclaim_state;
1299 * Tell the memory management that we're a "memory allocator",
1300 * and that if we need more memory we should get access to it
1301 * regardless (see "__alloc_pages()"). "kswapd" should
1302 * never get caught in the normal page freeing logic.
1304 * (Kswapd normally doesn't need memory anyway, but sometimes
1305 * you need a small amount of memory in order to be able to
1306 * page out something else, and this flag essentially protects
1307 * us from recursively trying to free more memory as we're
1308 * trying to free the first piece of memory in the first place).
1310 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
1314 unsigned long new_order;
1318 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
1319 new_order = pgdat->kswapd_max_order;
1320 pgdat->kswapd_max_order = 0;
1321 if (order < new_order) {
1323 * Don't sleep if someone wants a larger 'order'
1329 order = pgdat->kswapd_max_order;
1331 finish_wait(&pgdat->kswapd_wait, &wait);
1333 balance_pgdat(pgdat, order);
1339 * A zone is low on free memory, so wake its kswapd task to service it.
1341 void wakeup_kswapd(struct zone *zone, int order)
1345 if (!populated_zone(zone))
1348 pgdat = zone->zone_pgdat;
1349 if (zone_watermark_ok(zone, order, zone->pages_low, 0, 0))
1351 if (pgdat->kswapd_max_order < order)
1352 pgdat->kswapd_max_order = order;
1353 if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
1355 if (!waitqueue_active(&pgdat->kswapd_wait))
1357 wake_up_interruptible(&pgdat->kswapd_wait);
1362 * Helper function for shrink_all_memory(). Tries to reclaim 'nr_pages' pages
1363 * from LRU lists system-wide, for given pass and priority, and returns the
1364 * number of reclaimed pages
1366 * For pass > 3 we also try to shrink the LRU lists that contain a few pages
1368 static unsigned long shrink_all_zones(unsigned long nr_pages, int pass,
1369 int prio, struct scan_control *sc)
1372 unsigned long nr_to_scan, ret = 0;
1374 for_each_zone(zone) {
1376 if (!populated_zone(zone))
1379 if (zone->all_unreclaimable && prio != DEF_PRIORITY)
1382 /* For pass = 0 we don't shrink the active list */
1384 zone->nr_scan_active += (zone->nr_active >> prio) + 1;
1385 if (zone->nr_scan_active >= nr_pages || pass > 3) {
1386 zone->nr_scan_active = 0;
1387 nr_to_scan = min(nr_pages, zone->nr_active);
1388 shrink_active_list(nr_to_scan, zone, sc, prio);
1392 zone->nr_scan_inactive += (zone->nr_inactive >> prio) + 1;
1393 if (zone->nr_scan_inactive >= nr_pages || pass > 3) {
1394 zone->nr_scan_inactive = 0;
1395 nr_to_scan = min(nr_pages, zone->nr_inactive);
1396 ret += shrink_inactive_list(nr_to_scan, zone, sc);
1397 if (ret >= nr_pages)
1406 * Try to free `nr_pages' of memory, system-wide, and return the number of
1409 * Rather than trying to age LRUs the aim is to preserve the overall
1410 * LRU order by reclaiming preferentially
1411 * inactive > active > active referenced > active mapped
1413 unsigned long shrink_all_memory(unsigned long nr_pages)
1415 unsigned long lru_pages, nr_slab;
1416 unsigned long ret = 0;
1418 struct reclaim_state reclaim_state;
1420 struct scan_control sc = {
1421 .gfp_mask = GFP_KERNEL,
1423 .swap_cluster_max = nr_pages,
1425 .swappiness = vm_swappiness,
1428 current->reclaim_state = &reclaim_state;
1432 lru_pages += zone->nr_active + zone->nr_inactive;
1434 nr_slab = global_page_state(NR_SLAB_RECLAIMABLE);
1435 /* If slab caches are huge, it's better to hit them first */
1436 while (nr_slab >= lru_pages) {
1437 reclaim_state.reclaimed_slab = 0;
1438 shrink_slab(nr_pages, sc.gfp_mask, lru_pages);
1439 if (!reclaim_state.reclaimed_slab)
1442 ret += reclaim_state.reclaimed_slab;
1443 if (ret >= nr_pages)
1446 nr_slab -= reclaim_state.reclaimed_slab;
1450 * We try to shrink LRUs in 5 passes:
1451 * 0 = Reclaim from inactive_list only
1452 * 1 = Reclaim from active list but don't reclaim mapped
1453 * 2 = 2nd pass of type 1
1454 * 3 = Reclaim mapped (normal reclaim)
1455 * 4 = 2nd pass of type 3
1457 for (pass = 0; pass < 5; pass++) {
1460 /* Needed for shrinking slab caches later on */
1462 for_each_zone(zone) {
1463 lru_pages += zone->nr_active;
1464 lru_pages += zone->nr_inactive;
1467 /* Force reclaiming mapped pages in the passes #3 and #4 */
1470 sc.swappiness = 100;
1473 for (prio = DEF_PRIORITY; prio >= 0; prio--) {
1474 unsigned long nr_to_scan = nr_pages - ret;
1477 ret += shrink_all_zones(nr_to_scan, prio, pass, &sc);
1478 if (ret >= nr_pages)
1481 reclaim_state.reclaimed_slab = 0;
1482 shrink_slab(sc.nr_scanned, sc.gfp_mask, lru_pages);
1483 ret += reclaim_state.reclaimed_slab;
1484 if (ret >= nr_pages)
1487 if (sc.nr_scanned && prio < DEF_PRIORITY - 2)
1488 congestion_wait(WRITE, HZ / 10);
1495 * If ret = 0, we could not shrink LRUs, but there may be something
1500 reclaim_state.reclaimed_slab = 0;
1501 shrink_slab(nr_pages, sc.gfp_mask, lru_pages);
1502 ret += reclaim_state.reclaimed_slab;
1503 } while (ret < nr_pages && reclaim_state.reclaimed_slab > 0);
1506 current->reclaim_state = NULL;
1512 #ifdef CONFIG_HOTPLUG_CPU
1513 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1514 not required for correctness. So if the last cpu in a node goes
1515 away, we get changed to run anywhere: as the first one comes back,
1516 restore their cpu bindings. */
1517 static int __devinit cpu_callback(struct notifier_block *nfb,
1518 unsigned long action, void *hcpu)
1523 if (action == CPU_ONLINE) {
1524 for_each_online_pgdat(pgdat) {
1525 mask = node_to_cpumask(pgdat->node_id);
1526 if (any_online_cpu(mask) != NR_CPUS)
1527 /* One of our CPUs online: restore mask */
1528 set_cpus_allowed(pgdat->kswapd, mask);
1533 #endif /* CONFIG_HOTPLUG_CPU */
1536 * This kswapd start function will be called by init and node-hot-add.
1537 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
1539 int kswapd_run(int nid)
1541 pg_data_t *pgdat = NODE_DATA(nid);
1547 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
1548 if (IS_ERR(pgdat->kswapd)) {
1549 /* failure at boot is fatal */
1550 BUG_ON(system_state == SYSTEM_BOOTING);
1551 printk("Failed to start kswapd on node %d\n",nid);
1557 static int __init kswapd_init(void)
1562 for_each_online_node(nid)
1564 hotcpu_notifier(cpu_callback, 0);
1568 module_init(kswapd_init)
1574 * If non-zero call zone_reclaim when the number of free pages falls below
1577 int zone_reclaim_mode __read_mostly;
1579 #define RECLAIM_OFF 0
1580 #define RECLAIM_ZONE (1<<0) /* Run shrink_cache on the zone */
1581 #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
1582 #define RECLAIM_SWAP (1<<2) /* Swap pages out during reclaim */
1585 * Priority for ZONE_RECLAIM. This determines the fraction of pages
1586 * of a node considered for each zone_reclaim. 4 scans 1/16th of
1589 #define ZONE_RECLAIM_PRIORITY 4
1592 * Percentage of pages in a zone that must be unmapped for zone_reclaim to
1595 int sysctl_min_unmapped_ratio = 1;
1598 * If the number of slab pages in a zone grows beyond this percentage then
1599 * slab reclaim needs to occur.
1601 int sysctl_min_slab_ratio = 5;
1604 * Try to free up some pages from this zone through reclaim.
1606 static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
1608 /* Minimum pages needed in order to stay on node */
1609 const unsigned long nr_pages = 1 << order;
1610 struct task_struct *p = current;
1611 struct reclaim_state reclaim_state;
1613 unsigned long nr_reclaimed = 0;
1614 struct scan_control sc = {
1615 .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
1616 .may_swap = !!(zone_reclaim_mode & RECLAIM_SWAP),
1617 .swap_cluster_max = max_t(unsigned long, nr_pages,
1619 .gfp_mask = gfp_mask,
1620 .swappiness = vm_swappiness,
1622 unsigned long slab_reclaimable;
1624 disable_swap_token();
1627 * We need to be able to allocate from the reserves for RECLAIM_SWAP
1628 * and we also need to be able to write out pages for RECLAIM_WRITE
1631 p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
1632 reclaim_state.reclaimed_slab = 0;
1633 p->reclaim_state = &reclaim_state;
1635 if (zone_page_state(zone, NR_FILE_PAGES) -
1636 zone_page_state(zone, NR_FILE_MAPPED) >
1637 zone->min_unmapped_pages) {
1639 * Free memory by calling shrink zone with increasing
1640 * priorities until we have enough memory freed.
1642 priority = ZONE_RECLAIM_PRIORITY;
1644 note_zone_scanning_priority(zone, priority);
1645 nr_reclaimed += shrink_zone(priority, zone, &sc);
1647 } while (priority >= 0 && nr_reclaimed < nr_pages);
1650 slab_reclaimable = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
1651 if (slab_reclaimable > zone->min_slab_pages) {
1653 * shrink_slab() does not currently allow us to determine how
1654 * many pages were freed in this zone. So we take the current
1655 * number of slab pages and shake the slab until it is reduced
1656 * by the same nr_pages that we used for reclaiming unmapped
1659 * Note that shrink_slab will free memory on all zones and may
1662 while (shrink_slab(sc.nr_scanned, gfp_mask, order) &&
1663 zone_page_state(zone, NR_SLAB_RECLAIMABLE) >
1664 slab_reclaimable - nr_pages)
1668 * Update nr_reclaimed by the number of slab pages we
1669 * reclaimed from this zone.
1671 nr_reclaimed += slab_reclaimable -
1672 zone_page_state(zone, NR_SLAB_RECLAIMABLE);
1675 p->reclaim_state = NULL;
1676 current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
1677 return nr_reclaimed >= nr_pages;
1680 int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
1686 * Zone reclaim reclaims unmapped file backed pages and
1687 * slab pages if we are over the defined limits.
1689 * A small portion of unmapped file backed pages is needed for
1690 * file I/O otherwise pages read by file I/O will be immediately
1691 * thrown out if the zone is overallocated. So we do not reclaim
1692 * if less than a specified percentage of the zone is used by
1693 * unmapped file backed pages.
1695 if (zone_page_state(zone, NR_FILE_PAGES) -
1696 zone_page_state(zone, NR_FILE_MAPPED) <= zone->min_unmapped_pages
1697 && zone_page_state(zone, NR_SLAB_RECLAIMABLE)
1698 <= zone->min_slab_pages)
1702 * Avoid concurrent zone reclaims, do not reclaim in a zone that does
1703 * not have reclaimable pages and if we should not delay the allocation
1706 if (!(gfp_mask & __GFP_WAIT) ||
1707 zone->all_unreclaimable ||
1708 atomic_read(&zone->reclaim_in_progress) > 0 ||
1709 (current->flags & PF_MEMALLOC))
1713 * Only run zone reclaim on the local zone or on zones that do not
1714 * have associated processors. This will favor the local processor
1715 * over remote processors and spread off node memory allocations
1716 * as wide as possible.
1718 node_id = zone_to_nid(zone);
1719 mask = node_to_cpumask(node_id);
1720 if (!cpus_empty(mask) && node_id != numa_node_id())
1722 return __zone_reclaim(zone, gfp_mask, order);