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>
37 #include <linux/kthread.h>
39 #include <asm/tlbflush.h>
40 #include <asm/div64.h>
42 #include <linux/swapops.h>
47 /* Incremented by the number of inactive pages that were scanned */
48 unsigned long nr_scanned;
50 /* This context's GFP mask */
55 /* Can pages be swapped as part of reclaim? */
58 /* This context's SWAP_CLUSTER_MAX. If freeing memory for
59 * suspend, we effectively ignore SWAP_CLUSTER_MAX.
60 * In this context, it doesn't matter that we scan the
61 * whole list at once. */
66 int all_unreclaimable;
70 * The list of shrinker callbacks used by to apply pressure to
75 struct list_head list;
76 int seeks; /* seeks to recreate an obj */
77 long nr; /* objs pending delete */
80 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
82 #ifdef ARCH_HAS_PREFETCH
83 #define prefetch_prev_lru_page(_page, _base, _field) \
85 if ((_page)->lru.prev != _base) { \
88 prev = lru_to_page(&(_page->lru)); \
89 prefetch(&prev->_field); \
93 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
96 #ifdef ARCH_HAS_PREFETCHW
97 #define prefetchw_prev_lru_page(_page, _base, _field) \
99 if ((_page)->lru.prev != _base) { \
102 prev = lru_to_page(&(_page->lru)); \
103 prefetchw(&prev->_field); \
107 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
111 * From 0 .. 100. Higher means more swappy.
113 int vm_swappiness = 60;
114 long vm_total_pages; /* The total number of pages which the VM controls */
116 static LIST_HEAD(shrinker_list);
117 static DECLARE_RWSEM(shrinker_rwsem);
120 * Add a shrinker callback to be called from the vm
122 struct shrinker *set_shrinker(int seeks, shrinker_t theshrinker)
124 struct shrinker *shrinker;
126 shrinker = kmalloc(sizeof(*shrinker), GFP_KERNEL);
128 shrinker->shrinker = theshrinker;
129 shrinker->seeks = seeks;
131 down_write(&shrinker_rwsem);
132 list_add_tail(&shrinker->list, &shrinker_list);
133 up_write(&shrinker_rwsem);
137 EXPORT_SYMBOL(set_shrinker);
142 void remove_shrinker(struct shrinker *shrinker)
144 down_write(&shrinker_rwsem);
145 list_del(&shrinker->list);
146 up_write(&shrinker_rwsem);
149 EXPORT_SYMBOL(remove_shrinker);
151 #define SHRINK_BATCH 128
153 * Call the shrink functions to age shrinkable caches
155 * Here we assume it costs one seek to replace a lru page and that it also
156 * takes a seek to recreate a cache object. With this in mind we age equal
157 * percentages of the lru and ageable caches. This should balance the seeks
158 * generated by these structures.
160 * If the vm encounted mapped pages on the LRU it increase the pressure on
161 * slab to avoid swapping.
163 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
165 * `lru_pages' represents the number of on-LRU pages in all the zones which
166 * are eligible for the caller's allocation attempt. It is used for balancing
167 * slab reclaim versus page reclaim.
169 * Returns the number of slab objects which we shrunk.
171 unsigned long shrink_slab(unsigned long scanned, gfp_t gfp_mask,
172 unsigned long lru_pages)
174 struct shrinker *shrinker;
175 unsigned long ret = 0;
178 scanned = SWAP_CLUSTER_MAX;
180 if (!down_read_trylock(&shrinker_rwsem))
181 return 1; /* Assume we'll be able to shrink next time */
183 list_for_each_entry(shrinker, &shrinker_list, list) {
184 unsigned long long delta;
185 unsigned long total_scan;
186 unsigned long max_pass = (*shrinker->shrinker)(0, gfp_mask);
188 delta = (4 * scanned) / shrinker->seeks;
190 do_div(delta, lru_pages + 1);
191 shrinker->nr += delta;
192 if (shrinker->nr < 0) {
193 printk(KERN_ERR "%s: nr=%ld\n",
194 __FUNCTION__, shrinker->nr);
195 shrinker->nr = max_pass;
199 * Avoid risking looping forever due to too large nr value:
200 * never try to free more than twice the estimate number of
203 if (shrinker->nr > max_pass * 2)
204 shrinker->nr = max_pass * 2;
206 total_scan = shrinker->nr;
209 while (total_scan >= SHRINK_BATCH) {
210 long this_scan = SHRINK_BATCH;
214 nr_before = (*shrinker->shrinker)(0, gfp_mask);
215 shrink_ret = (*shrinker->shrinker)(this_scan, gfp_mask);
216 if (shrink_ret == -1)
218 if (shrink_ret < nr_before)
219 ret += nr_before - shrink_ret;
220 count_vm_events(SLABS_SCANNED, this_scan);
221 total_scan -= this_scan;
226 shrinker->nr += total_scan;
228 up_read(&shrinker_rwsem);
232 /* Called without lock on whether page is mapped, so answer is unstable */
233 static inline int page_mapping_inuse(struct page *page)
235 struct address_space *mapping;
237 /* Page is in somebody's page tables. */
238 if (page_mapped(page))
241 /* Be more reluctant to reclaim swapcache than pagecache */
242 if (PageSwapCache(page))
245 mapping = page_mapping(page);
249 /* File is mmap'd by somebody? */
250 return mapping_mapped(mapping);
253 static inline int is_page_cache_freeable(struct page *page)
255 return page_count(page) - !!PagePrivate(page) == 2;
258 static int may_write_to_queue(struct backing_dev_info *bdi)
260 if (current->flags & PF_SWAPWRITE)
262 if (!bdi_write_congested(bdi))
264 if (bdi == current->backing_dev_info)
270 * We detected a synchronous write error writing a page out. Probably
271 * -ENOSPC. We need to propagate that into the address_space for a subsequent
272 * fsync(), msync() or close().
274 * The tricky part is that after writepage we cannot touch the mapping: nothing
275 * prevents it from being freed up. But we have a ref on the page and once
276 * that page is locked, the mapping is pinned.
278 * We're allowed to run sleeping lock_page() here because we know the caller has
281 static void handle_write_error(struct address_space *mapping,
282 struct page *page, int error)
285 if (page_mapping(page) == mapping) {
286 if (error == -ENOSPC)
287 set_bit(AS_ENOSPC, &mapping->flags);
289 set_bit(AS_EIO, &mapping->flags);
294 /* possible outcome of pageout() */
296 /* failed to write page out, page is locked */
298 /* move page to the active list, page is locked */
300 /* page has been sent to the disk successfully, page is unlocked */
302 /* page is clean and locked */
307 * pageout is called by shrink_page_list() for each dirty page.
308 * Calls ->writepage().
310 static pageout_t pageout(struct page *page, struct address_space *mapping)
313 * If the page is dirty, only perform writeback if that write
314 * will be non-blocking. To prevent this allocation from being
315 * stalled by pagecache activity. But note that there may be
316 * stalls if we need to run get_block(). We could test
317 * PagePrivate for that.
319 * If this process is currently in generic_file_write() against
320 * this page's queue, we can perform writeback even if that
323 * If the page is swapcache, write it back even if that would
324 * block, for some throttling. This happens by accident, because
325 * swap_backing_dev_info is bust: it doesn't reflect the
326 * congestion state of the swapdevs. Easy to fix, if needed.
327 * See swapfile.c:page_queue_congested().
329 if (!is_page_cache_freeable(page))
333 * Some data journaling orphaned pages can have
334 * page->mapping == NULL while being dirty with clean buffers.
336 if (PagePrivate(page)) {
337 if (try_to_free_buffers(page)) {
338 ClearPageDirty(page);
339 printk("%s: orphaned page\n", __FUNCTION__);
345 if (mapping->a_ops->writepage == NULL)
346 return PAGE_ACTIVATE;
347 if (!may_write_to_queue(mapping->backing_dev_info))
350 if (clear_page_dirty_for_io(page)) {
352 struct writeback_control wbc = {
353 .sync_mode = WB_SYNC_NONE,
354 .nr_to_write = SWAP_CLUSTER_MAX,
356 .range_end = LLONG_MAX,
361 SetPageReclaim(page);
362 res = mapping->a_ops->writepage(page, &wbc);
364 handle_write_error(mapping, page, res);
365 if (res == AOP_WRITEPAGE_ACTIVATE) {
366 ClearPageReclaim(page);
367 return PAGE_ACTIVATE;
369 if (!PageWriteback(page)) {
370 /* synchronous write or broken a_ops? */
371 ClearPageReclaim(page);
380 int remove_mapping(struct address_space *mapping, struct page *page)
383 return 0; /* truncate got there first */
385 write_lock_irq(&mapping->tree_lock);
388 * The non-racy check for busy page. It is critical to check
389 * PageDirty _after_ making sure that the page is freeable and
390 * not in use by anybody. (pagecache + us == 2)
392 if (unlikely(page_count(page) != 2))
395 if (unlikely(PageDirty(page)))
398 if (PageSwapCache(page)) {
399 swp_entry_t swap = { .val = page_private(page) };
400 __delete_from_swap_cache(page);
401 write_unlock_irq(&mapping->tree_lock);
403 __put_page(page); /* The pagecache ref */
407 __remove_from_page_cache(page);
408 write_unlock_irq(&mapping->tree_lock);
413 write_unlock_irq(&mapping->tree_lock);
418 * shrink_page_list() returns the number of reclaimed pages
420 static unsigned long shrink_page_list(struct list_head *page_list,
421 struct scan_control *sc)
423 LIST_HEAD(ret_pages);
424 struct pagevec freed_pvec;
426 unsigned long nr_reclaimed = 0;
430 pagevec_init(&freed_pvec, 1);
431 while (!list_empty(page_list)) {
432 struct address_space *mapping;
439 page = lru_to_page(page_list);
440 list_del(&page->lru);
442 if (TestSetPageLocked(page))
445 BUG_ON(PageActive(page));
449 if (!sc->may_swap && page_mapped(page))
452 /* Double the slab pressure for mapped and swapcache pages */
453 if (page_mapped(page) || PageSwapCache(page))
456 if (PageWriteback(page))
459 referenced = page_referenced(page, 1);
460 /* In active use or really unfreeable? Activate it. */
461 if (referenced && page_mapping_inuse(page))
462 goto activate_locked;
466 * Anonymous process memory has backing store?
467 * Try to allocate it some swap space here.
469 if (PageAnon(page) && !PageSwapCache(page))
470 if (!add_to_swap(page, GFP_ATOMIC))
471 goto activate_locked;
472 #endif /* CONFIG_SWAP */
474 mapping = page_mapping(page);
475 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
476 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
479 * The page is mapped into the page tables of one or more
480 * processes. Try to unmap it here.
482 if (page_mapped(page) && mapping) {
483 switch (try_to_unmap(page, 0)) {
485 goto activate_locked;
489 ; /* try to free the page below */
493 if (PageDirty(page)) {
498 if (!sc->may_writepage)
501 /* Page is dirty, try to write it out here */
502 switch(pageout(page, mapping)) {
506 goto activate_locked;
508 if (PageWriteback(page) || PageDirty(page))
511 * A synchronous write - probably a ramdisk. Go
512 * ahead and try to reclaim the page.
514 if (TestSetPageLocked(page))
516 if (PageDirty(page) || PageWriteback(page))
518 mapping = page_mapping(page);
520 ; /* try to free the page below */
525 * If the page has buffers, try to free the buffer mappings
526 * associated with this page. If we succeed we try to free
529 * We do this even if the page is PageDirty().
530 * try_to_release_page() does not perform I/O, but it is
531 * possible for a page to have PageDirty set, but it is actually
532 * clean (all its buffers are clean). This happens if the
533 * buffers were written out directly, with submit_bh(). ext3
534 * will do this, as well as the blockdev mapping.
535 * try_to_release_page() will discover that cleanness and will
536 * drop the buffers and mark the page clean - it can be freed.
538 * Rarely, pages can have buffers and no ->mapping. These are
539 * the pages which were not successfully invalidated in
540 * truncate_complete_page(). We try to drop those buffers here
541 * and if that worked, and the page is no longer mapped into
542 * process address space (page_count == 1) it can be freed.
543 * Otherwise, leave the page on the LRU so it is swappable.
545 if (PagePrivate(page)) {
546 if (!try_to_release_page(page, sc->gfp_mask))
547 goto activate_locked;
548 if (!mapping && page_count(page) == 1)
552 if (!remove_mapping(mapping, page))
558 if (!pagevec_add(&freed_pvec, page))
559 __pagevec_release_nonlru(&freed_pvec);
568 list_add(&page->lru, &ret_pages);
569 BUG_ON(PageLRU(page));
571 list_splice(&ret_pages, page_list);
572 if (pagevec_count(&freed_pvec))
573 __pagevec_release_nonlru(&freed_pvec);
574 count_vm_events(PGACTIVATE, pgactivate);
579 * zone->lru_lock is heavily contended. Some of the functions that
580 * shrink the lists perform better by taking out a batch of pages
581 * and working on them outside the LRU lock.
583 * For pagecache intensive workloads, this function is the hottest
584 * spot in the kernel (apart from copy_*_user functions).
586 * Appropriate locks must be held before calling this function.
588 * @nr_to_scan: The number of pages to look through on the list.
589 * @src: The LRU list to pull pages off.
590 * @dst: The temp list to put pages on to.
591 * @scanned: The number of pages that were scanned.
593 * returns how many pages were moved onto *@dst.
595 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
596 struct list_head *src, struct list_head *dst,
597 unsigned long *scanned)
599 unsigned long nr_taken = 0;
603 for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
604 struct list_head *target;
605 page = lru_to_page(src);
606 prefetchw_prev_lru_page(page, src, flags);
608 BUG_ON(!PageLRU(page));
610 list_del(&page->lru);
612 if (likely(get_page_unless_zero(page))) {
614 * Be careful not to clear PageLRU until after we're
615 * sure the page is not being freed elsewhere -- the
616 * page release code relies on it.
621 } /* else it is being freed elsewhere */
623 list_add(&page->lru, target);
631 * shrink_inactive_list() is a helper for shrink_zone(). It returns the number
634 static unsigned long shrink_inactive_list(unsigned long max_scan,
635 struct zone *zone, struct scan_control *sc)
637 LIST_HEAD(page_list);
639 unsigned long nr_scanned = 0;
640 unsigned long nr_reclaimed = 0;
642 pagevec_init(&pvec, 1);
645 spin_lock_irq(&zone->lru_lock);
648 unsigned long nr_taken;
649 unsigned long nr_scan;
650 unsigned long nr_freed;
652 nr_taken = isolate_lru_pages(sc->swap_cluster_max,
653 &zone->inactive_list,
654 &page_list, &nr_scan);
655 zone->nr_inactive -= nr_taken;
656 zone->pages_scanned += nr_scan;
657 spin_unlock_irq(&zone->lru_lock);
659 nr_scanned += nr_scan;
660 nr_freed = shrink_page_list(&page_list, sc);
661 nr_reclaimed += nr_freed;
663 if (current_is_kswapd()) {
664 __count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scan);
665 __count_vm_events(KSWAPD_STEAL, nr_freed);
667 __count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scan);
668 __count_vm_events(PGACTIVATE, nr_freed);
673 spin_lock(&zone->lru_lock);
675 * Put back any unfreeable pages.
677 while (!list_empty(&page_list)) {
678 page = lru_to_page(&page_list);
679 BUG_ON(PageLRU(page));
681 list_del(&page->lru);
682 if (PageActive(page))
683 add_page_to_active_list(zone, page);
685 add_page_to_inactive_list(zone, page);
686 if (!pagevec_add(&pvec, page)) {
687 spin_unlock_irq(&zone->lru_lock);
688 __pagevec_release(&pvec);
689 spin_lock_irq(&zone->lru_lock);
692 } while (nr_scanned < max_scan);
693 spin_unlock(&zone->lru_lock);
696 pagevec_release(&pvec);
701 * We are about to scan this zone at a certain priority level. If that priority
702 * level is smaller (ie: more urgent) than the previous priority, then note
703 * that priority level within the zone. This is done so that when the next
704 * process comes in to scan this zone, it will immediately start out at this
705 * priority level rather than having to build up its own scanning priority.
706 * Here, this priority affects only the reclaim-mapped threshold.
708 static inline void note_zone_scanning_priority(struct zone *zone, int priority)
710 if (priority < zone->prev_priority)
711 zone->prev_priority = priority;
714 static inline int zone_is_near_oom(struct zone *zone)
716 return zone->pages_scanned >= (zone->nr_active + zone->nr_inactive)*3;
720 * This moves pages from the active list to the inactive list.
722 * We move them the other way if the page is referenced by one or more
723 * processes, from rmap.
725 * If the pages are mostly unmapped, the processing is fast and it is
726 * appropriate to hold zone->lru_lock across the whole operation. But if
727 * the pages are mapped, the processing is slow (page_referenced()) so we
728 * should drop zone->lru_lock around each page. It's impossible to balance
729 * this, so instead we remove the pages from the LRU while processing them.
730 * It is safe to rely on PG_active against the non-LRU pages in here because
731 * nobody will play with that bit on a non-LRU page.
733 * The downside is that we have to touch page->_count against each page.
734 * But we had to alter page->flags anyway.
736 static void shrink_active_list(unsigned long nr_pages, struct zone *zone,
737 struct scan_control *sc, int priority)
739 unsigned long pgmoved;
740 int pgdeactivate = 0;
741 unsigned long pgscanned;
742 LIST_HEAD(l_hold); /* The pages which were snipped off */
743 LIST_HEAD(l_inactive); /* Pages to go onto the inactive_list */
744 LIST_HEAD(l_active); /* Pages to go onto the active_list */
747 int reclaim_mapped = 0;
754 if (zone_is_near_oom(zone))
755 goto force_reclaim_mapped;
758 * `distress' is a measure of how much trouble we're having
759 * reclaiming pages. 0 -> no problems. 100 -> great trouble.
761 distress = 100 >> min(zone->prev_priority, priority);
764 * The point of this algorithm is to decide when to start
765 * reclaiming mapped memory instead of just pagecache. Work out
769 mapped_ratio = ((global_page_state(NR_FILE_MAPPED) +
770 global_page_state(NR_ANON_PAGES)) * 100) /
774 * Now decide how much we really want to unmap some pages. The
775 * mapped ratio is downgraded - just because there's a lot of
776 * mapped memory doesn't necessarily mean that page reclaim
779 * The distress ratio is important - we don't want to start
782 * A 100% value of vm_swappiness overrides this algorithm
785 swap_tendency = mapped_ratio / 2 + distress + sc->swappiness;
788 * Now use this metric to decide whether to start moving mapped
789 * memory onto the inactive list.
791 if (swap_tendency >= 100)
792 force_reclaim_mapped:
797 spin_lock_irq(&zone->lru_lock);
798 pgmoved = isolate_lru_pages(nr_pages, &zone->active_list,
799 &l_hold, &pgscanned);
800 zone->pages_scanned += pgscanned;
801 zone->nr_active -= pgmoved;
802 spin_unlock_irq(&zone->lru_lock);
804 while (!list_empty(&l_hold)) {
806 page = lru_to_page(&l_hold);
807 list_del(&page->lru);
808 if (page_mapped(page)) {
809 if (!reclaim_mapped ||
810 (total_swap_pages == 0 && PageAnon(page)) ||
811 page_referenced(page, 0)) {
812 list_add(&page->lru, &l_active);
816 list_add(&page->lru, &l_inactive);
819 pagevec_init(&pvec, 1);
821 spin_lock_irq(&zone->lru_lock);
822 while (!list_empty(&l_inactive)) {
823 page = lru_to_page(&l_inactive);
824 prefetchw_prev_lru_page(page, &l_inactive, flags);
825 BUG_ON(PageLRU(page));
827 BUG_ON(!PageActive(page));
828 ClearPageActive(page);
830 list_move(&page->lru, &zone->inactive_list);
832 if (!pagevec_add(&pvec, page)) {
833 zone->nr_inactive += pgmoved;
834 spin_unlock_irq(&zone->lru_lock);
835 pgdeactivate += pgmoved;
837 if (buffer_heads_over_limit)
838 pagevec_strip(&pvec);
839 __pagevec_release(&pvec);
840 spin_lock_irq(&zone->lru_lock);
843 zone->nr_inactive += pgmoved;
844 pgdeactivate += pgmoved;
845 if (buffer_heads_over_limit) {
846 spin_unlock_irq(&zone->lru_lock);
847 pagevec_strip(&pvec);
848 spin_lock_irq(&zone->lru_lock);
852 while (!list_empty(&l_active)) {
853 page = lru_to_page(&l_active);
854 prefetchw_prev_lru_page(page, &l_active, flags);
855 BUG_ON(PageLRU(page));
857 BUG_ON(!PageActive(page));
858 list_move(&page->lru, &zone->active_list);
860 if (!pagevec_add(&pvec, page)) {
861 zone->nr_active += pgmoved;
863 spin_unlock_irq(&zone->lru_lock);
864 __pagevec_release(&pvec);
865 spin_lock_irq(&zone->lru_lock);
868 zone->nr_active += pgmoved;
870 __count_zone_vm_events(PGREFILL, zone, pgscanned);
871 __count_vm_events(PGDEACTIVATE, pgdeactivate);
872 spin_unlock_irq(&zone->lru_lock);
874 pagevec_release(&pvec);
878 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
880 static unsigned long shrink_zone(int priority, struct zone *zone,
881 struct scan_control *sc)
883 unsigned long nr_active;
884 unsigned long nr_inactive;
885 unsigned long nr_to_scan;
886 unsigned long nr_reclaimed = 0;
888 atomic_inc(&zone->reclaim_in_progress);
891 * Add one to `nr_to_scan' just to make sure that the kernel will
892 * slowly sift through the active list.
894 zone->nr_scan_active += (zone->nr_active >> priority) + 1;
895 nr_active = zone->nr_scan_active;
896 if (nr_active >= sc->swap_cluster_max)
897 zone->nr_scan_active = 0;
901 zone->nr_scan_inactive += (zone->nr_inactive >> priority) + 1;
902 nr_inactive = zone->nr_scan_inactive;
903 if (nr_inactive >= sc->swap_cluster_max)
904 zone->nr_scan_inactive = 0;
908 while (nr_active || nr_inactive) {
910 nr_to_scan = min(nr_active,
911 (unsigned long)sc->swap_cluster_max);
912 nr_active -= nr_to_scan;
913 shrink_active_list(nr_to_scan, zone, sc, priority);
917 nr_to_scan = min(nr_inactive,
918 (unsigned long)sc->swap_cluster_max);
919 nr_inactive -= nr_to_scan;
920 nr_reclaimed += shrink_inactive_list(nr_to_scan, zone,
925 throttle_vm_writeout();
927 atomic_dec(&zone->reclaim_in_progress);
932 * This is the direct reclaim path, for page-allocating processes. We only
933 * try to reclaim pages from zones which will satisfy the caller's allocation
936 * We reclaim from a zone even if that zone is over pages_high. Because:
937 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
939 * b) The zones may be over pages_high but they must go *over* pages_high to
940 * satisfy the `incremental min' zone defense algorithm.
942 * Returns the number of reclaimed pages.
944 * If a zone is deemed to be full of pinned pages then just give it a light
945 * scan then give up on it.
947 static unsigned long shrink_zones(int priority, struct zone **zones,
948 struct scan_control *sc)
950 unsigned long nr_reclaimed = 0;
953 sc->all_unreclaimable = 1;
954 for (i = 0; zones[i] != NULL; i++) {
955 struct zone *zone = zones[i];
957 if (!populated_zone(zone))
960 if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
963 note_zone_scanning_priority(zone, priority);
965 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
966 continue; /* Let kswapd poll it */
968 sc->all_unreclaimable = 0;
970 nr_reclaimed += shrink_zone(priority, zone, sc);
976 * This is the main entry point to direct page reclaim.
978 * If a full scan of the inactive list fails to free enough memory then we
979 * are "out of memory" and something needs to be killed.
981 * If the caller is !__GFP_FS then the probability of a failure is reasonably
982 * high - the zone may be full of dirty or under-writeback pages, which this
983 * caller can't do much about. We kick pdflush and take explicit naps in the
984 * hope that some of these pages can be written. But if the allocating task
985 * holds filesystem locks which prevent writeout this might not work, and the
986 * allocation attempt will fail.
988 unsigned long try_to_free_pages(struct zone **zones, gfp_t gfp_mask)
992 unsigned long total_scanned = 0;
993 unsigned long nr_reclaimed = 0;
994 struct reclaim_state *reclaim_state = current->reclaim_state;
995 unsigned long lru_pages = 0;
997 struct scan_control sc = {
998 .gfp_mask = gfp_mask,
999 .may_writepage = !laptop_mode,
1000 .swap_cluster_max = SWAP_CLUSTER_MAX,
1002 .swappiness = vm_swappiness,
1005 count_vm_event(ALLOCSTALL);
1007 for (i = 0; zones[i] != NULL; i++) {
1008 struct zone *zone = zones[i];
1010 if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
1013 lru_pages += zone->nr_active + zone->nr_inactive;
1016 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1019 disable_swap_token();
1020 nr_reclaimed += shrink_zones(priority, zones, &sc);
1021 shrink_slab(sc.nr_scanned, gfp_mask, lru_pages);
1022 if (reclaim_state) {
1023 nr_reclaimed += reclaim_state->reclaimed_slab;
1024 reclaim_state->reclaimed_slab = 0;
1026 total_scanned += sc.nr_scanned;
1027 if (nr_reclaimed >= sc.swap_cluster_max) {
1033 * Try to write back as many pages as we just scanned. This
1034 * tends to cause slow streaming writers to write data to the
1035 * disk smoothly, at the dirtying rate, which is nice. But
1036 * that's undesirable in laptop mode, where we *want* lumpy
1037 * writeout. So in laptop mode, write out the whole world.
1039 if (total_scanned > sc.swap_cluster_max +
1040 sc.swap_cluster_max / 2) {
1041 wakeup_pdflush(laptop_mode ? 0 : total_scanned);
1042 sc.may_writepage = 1;
1045 /* Take a nap, wait for some writeback to complete */
1046 if (sc.nr_scanned && priority < DEF_PRIORITY - 2)
1047 blk_congestion_wait(WRITE, HZ/10);
1049 /* top priority shrink_caches still had more to do? don't OOM, then */
1050 if (!sc.all_unreclaimable || nr_reclaimed)
1055 * Now that we've scanned all the zones at this priority level, note
1056 * that level within the zone so that the next thread which performs
1057 * scanning of this zone will immediately start out at this priority
1058 * level. This affects only the decision whether or not to bring
1059 * mapped pages onto the inactive list.
1063 for (i = 0; zones[i] != 0; i++) {
1064 struct zone *zone = zones[i];
1066 if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
1069 zone->prev_priority = priority;
1075 * For kswapd, balance_pgdat() will work across all this node's zones until
1076 * they are all at pages_high.
1078 * Returns the number of pages which were actually freed.
1080 * There is special handling here for zones which are full of pinned pages.
1081 * This can happen if the pages are all mlocked, or if they are all used by
1082 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
1083 * What we do is to detect the case where all pages in the zone have been
1084 * scanned twice and there has been zero successful reclaim. Mark the zone as
1085 * dead and from now on, only perform a short scan. Basically we're polling
1086 * the zone for when the problem goes away.
1088 * kswapd scans the zones in the highmem->normal->dma direction. It skips
1089 * zones which have free_pages > pages_high, but once a zone is found to have
1090 * free_pages <= pages_high, we scan that zone and the lower zones regardless
1091 * of the number of free pages in the lower zones. This interoperates with
1092 * the page allocator fallback scheme to ensure that aging of pages is balanced
1095 static unsigned long balance_pgdat(pg_data_t *pgdat, int order)
1100 unsigned long total_scanned;
1101 unsigned long nr_reclaimed;
1102 struct reclaim_state *reclaim_state = current->reclaim_state;
1103 struct scan_control sc = {
1104 .gfp_mask = GFP_KERNEL,
1106 .swap_cluster_max = SWAP_CLUSTER_MAX,
1107 .swappiness = vm_swappiness,
1110 * temp_priority is used to remember the scanning priority at which
1111 * this zone was successfully refilled to free_pages == pages_high.
1113 int temp_priority[MAX_NR_ZONES];
1118 sc.may_writepage = !laptop_mode;
1119 count_vm_event(PAGEOUTRUN);
1121 for (i = 0; i < pgdat->nr_zones; i++)
1122 temp_priority[i] = DEF_PRIORITY;
1124 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1125 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
1126 unsigned long lru_pages = 0;
1128 /* The swap token gets in the way of swapout... */
1130 disable_swap_token();
1135 * Scan in the highmem->dma direction for the highest
1136 * zone which needs scanning
1138 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
1139 struct zone *zone = pgdat->node_zones + i;
1141 if (!populated_zone(zone))
1144 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1147 if (!zone_watermark_ok(zone, order, zone->pages_high,
1155 for (i = 0; i <= end_zone; i++) {
1156 struct zone *zone = pgdat->node_zones + i;
1158 lru_pages += zone->nr_active + zone->nr_inactive;
1162 * Now scan the zone in the dma->highmem direction, stopping
1163 * at the last zone which needs scanning.
1165 * We do this because the page allocator works in the opposite
1166 * direction. This prevents the page allocator from allocating
1167 * pages behind kswapd's direction of progress, which would
1168 * cause too much scanning of the lower zones.
1170 for (i = 0; i <= end_zone; i++) {
1171 struct zone *zone = pgdat->node_zones + i;
1174 if (!populated_zone(zone))
1177 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1180 if (!zone_watermark_ok(zone, order, zone->pages_high,
1183 temp_priority[i] = priority;
1185 note_zone_scanning_priority(zone, priority);
1186 nr_reclaimed += shrink_zone(priority, zone, &sc);
1187 reclaim_state->reclaimed_slab = 0;
1188 nr_slab = shrink_slab(sc.nr_scanned, GFP_KERNEL,
1190 nr_reclaimed += reclaim_state->reclaimed_slab;
1191 total_scanned += sc.nr_scanned;
1192 if (zone->all_unreclaimable)
1194 if (nr_slab == 0 && zone->pages_scanned >=
1195 (zone->nr_active + zone->nr_inactive) * 6)
1196 zone->all_unreclaimable = 1;
1198 * If we've done a decent amount of scanning and
1199 * the reclaim ratio is low, start doing writepage
1200 * even in laptop mode
1202 if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
1203 total_scanned > nr_reclaimed + nr_reclaimed / 2)
1204 sc.may_writepage = 1;
1207 break; /* kswapd: all done */
1209 * OK, kswapd is getting into trouble. Take a nap, then take
1210 * another pass across the zones.
1212 if (total_scanned && priority < DEF_PRIORITY - 2)
1213 blk_congestion_wait(WRITE, HZ/10);
1216 * We do this so kswapd doesn't build up large priorities for
1217 * example when it is freeing in parallel with allocators. It
1218 * matches the direct reclaim path behaviour in terms of impact
1219 * on zone->*_priority.
1221 if (nr_reclaimed >= SWAP_CLUSTER_MAX)
1226 * Note within each zone the priority level at which this zone was
1227 * brought into a happy state. So that the next thread which scans this
1228 * zone will start out at that priority level.
1230 for (i = 0; i < pgdat->nr_zones; i++) {
1231 struct zone *zone = pgdat->node_zones + i;
1233 zone->prev_priority = temp_priority[i];
1235 if (!all_zones_ok) {
1240 return nr_reclaimed;
1244 * The background pageout daemon, started as a kernel thread
1245 * from the init process.
1247 * This basically trickles out pages so that we have _some_
1248 * free memory available even if there is no other activity
1249 * that frees anything up. This is needed for things like routing
1250 * etc, where we otherwise might have all activity going on in
1251 * asynchronous contexts that cannot page things out.
1253 * If there are applications that are active memory-allocators
1254 * (most normal use), this basically shouldn't matter.
1256 static int kswapd(void *p)
1258 unsigned long order;
1259 pg_data_t *pgdat = (pg_data_t*)p;
1260 struct task_struct *tsk = current;
1262 struct reclaim_state reclaim_state = {
1263 .reclaimed_slab = 0,
1267 cpumask = node_to_cpumask(pgdat->node_id);
1268 if (!cpus_empty(cpumask))
1269 set_cpus_allowed(tsk, cpumask);
1270 current->reclaim_state = &reclaim_state;
1273 * Tell the memory management that we're a "memory allocator",
1274 * and that if we need more memory we should get access to it
1275 * regardless (see "__alloc_pages()"). "kswapd" should
1276 * never get caught in the normal page freeing logic.
1278 * (Kswapd normally doesn't need memory anyway, but sometimes
1279 * you need a small amount of memory in order to be able to
1280 * page out something else, and this flag essentially protects
1281 * us from recursively trying to free more memory as we're
1282 * trying to free the first piece of memory in the first place).
1284 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
1288 unsigned long new_order;
1292 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
1293 new_order = pgdat->kswapd_max_order;
1294 pgdat->kswapd_max_order = 0;
1295 if (order < new_order) {
1297 * Don't sleep if someone wants a larger 'order'
1303 order = pgdat->kswapd_max_order;
1305 finish_wait(&pgdat->kswapd_wait, &wait);
1307 balance_pgdat(pgdat, order);
1313 * A zone is low on free memory, so wake its kswapd task to service it.
1315 void wakeup_kswapd(struct zone *zone, int order)
1319 if (!populated_zone(zone))
1322 pgdat = zone->zone_pgdat;
1323 if (zone_watermark_ok(zone, order, zone->pages_low, 0, 0))
1325 if (pgdat->kswapd_max_order < order)
1326 pgdat->kswapd_max_order = order;
1327 if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
1329 if (!waitqueue_active(&pgdat->kswapd_wait))
1331 wake_up_interruptible(&pgdat->kswapd_wait);
1336 * Helper function for shrink_all_memory(). Tries to reclaim 'nr_pages' pages
1337 * from LRU lists system-wide, for given pass and priority, and returns the
1338 * number of reclaimed pages
1340 * For pass > 3 we also try to shrink the LRU lists that contain a few pages
1342 static unsigned long shrink_all_zones(unsigned long nr_pages, int pass,
1343 int prio, struct scan_control *sc)
1346 unsigned long nr_to_scan, ret = 0;
1348 for_each_zone(zone) {
1350 if (!populated_zone(zone))
1353 if (zone->all_unreclaimable && prio != DEF_PRIORITY)
1356 /* For pass = 0 we don't shrink the active list */
1358 zone->nr_scan_active += (zone->nr_active >> prio) + 1;
1359 if (zone->nr_scan_active >= nr_pages || pass > 3) {
1360 zone->nr_scan_active = 0;
1361 nr_to_scan = min(nr_pages, zone->nr_active);
1362 shrink_active_list(nr_to_scan, zone, sc, prio);
1366 zone->nr_scan_inactive += (zone->nr_inactive >> prio) + 1;
1367 if (zone->nr_scan_inactive >= nr_pages || pass > 3) {
1368 zone->nr_scan_inactive = 0;
1369 nr_to_scan = min(nr_pages, zone->nr_inactive);
1370 ret += shrink_inactive_list(nr_to_scan, zone, sc);
1371 if (ret >= nr_pages)
1380 * Try to free `nr_pages' of memory, system-wide, and return the number of
1383 * Rather than trying to age LRUs the aim is to preserve the overall
1384 * LRU order by reclaiming preferentially
1385 * inactive > active > active referenced > active mapped
1387 unsigned long shrink_all_memory(unsigned long nr_pages)
1389 unsigned long lru_pages, nr_slab;
1390 unsigned long ret = 0;
1392 struct reclaim_state reclaim_state;
1394 struct scan_control sc = {
1395 .gfp_mask = GFP_KERNEL,
1397 .swap_cluster_max = nr_pages,
1399 .swappiness = vm_swappiness,
1402 current->reclaim_state = &reclaim_state;
1406 lru_pages += zone->nr_active + zone->nr_inactive;
1408 nr_slab = global_page_state(NR_SLAB);
1409 /* If slab caches are huge, it's better to hit them first */
1410 while (nr_slab >= lru_pages) {
1411 reclaim_state.reclaimed_slab = 0;
1412 shrink_slab(nr_pages, sc.gfp_mask, lru_pages);
1413 if (!reclaim_state.reclaimed_slab)
1416 ret += reclaim_state.reclaimed_slab;
1417 if (ret >= nr_pages)
1420 nr_slab -= reclaim_state.reclaimed_slab;
1424 * We try to shrink LRUs in 5 passes:
1425 * 0 = Reclaim from inactive_list only
1426 * 1 = Reclaim from active list but don't reclaim mapped
1427 * 2 = 2nd pass of type 1
1428 * 3 = Reclaim mapped (normal reclaim)
1429 * 4 = 2nd pass of type 3
1431 for (pass = 0; pass < 5; pass++) {
1434 /* Needed for shrinking slab caches later on */
1436 for_each_zone(zone) {
1437 lru_pages += zone->nr_active;
1438 lru_pages += zone->nr_inactive;
1441 /* Force reclaiming mapped pages in the passes #3 and #4 */
1444 sc.swappiness = 100;
1447 for (prio = DEF_PRIORITY; prio >= 0; prio--) {
1448 unsigned long nr_to_scan = nr_pages - ret;
1451 ret += shrink_all_zones(nr_to_scan, prio, pass, &sc);
1452 if (ret >= nr_pages)
1455 reclaim_state.reclaimed_slab = 0;
1456 shrink_slab(sc.nr_scanned, sc.gfp_mask, lru_pages);
1457 ret += reclaim_state.reclaimed_slab;
1458 if (ret >= nr_pages)
1461 if (sc.nr_scanned && prio < DEF_PRIORITY - 2)
1462 blk_congestion_wait(WRITE, HZ / 10);
1469 * If ret = 0, we could not shrink LRUs, but there may be something
1474 reclaim_state.reclaimed_slab = 0;
1475 shrink_slab(nr_pages, sc.gfp_mask, lru_pages);
1476 ret += reclaim_state.reclaimed_slab;
1477 } while (ret < nr_pages && reclaim_state.reclaimed_slab > 0);
1480 current->reclaim_state = NULL;
1486 #ifdef CONFIG_HOTPLUG_CPU
1487 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1488 not required for correctness. So if the last cpu in a node goes
1489 away, we get changed to run anywhere: as the first one comes back,
1490 restore their cpu bindings. */
1491 static int __devinit cpu_callback(struct notifier_block *nfb,
1492 unsigned long action, void *hcpu)
1497 if (action == CPU_ONLINE) {
1498 for_each_online_pgdat(pgdat) {
1499 mask = node_to_cpumask(pgdat->node_id);
1500 if (any_online_cpu(mask) != NR_CPUS)
1501 /* One of our CPUs online: restore mask */
1502 set_cpus_allowed(pgdat->kswapd, mask);
1507 #endif /* CONFIG_HOTPLUG_CPU */
1510 * This kswapd start function will be called by init and node-hot-add.
1511 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
1513 int kswapd_run(int nid)
1515 pg_data_t *pgdat = NODE_DATA(nid);
1521 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
1522 if (IS_ERR(pgdat->kswapd)) {
1523 /* failure at boot is fatal */
1524 BUG_ON(system_state == SYSTEM_BOOTING);
1525 printk("Failed to start kswapd on node %d\n",nid);
1531 static int __init kswapd_init(void)
1536 for_each_online_node(nid)
1538 hotcpu_notifier(cpu_callback, 0);
1542 module_init(kswapd_init)
1548 * If non-zero call zone_reclaim when the number of free pages falls below
1551 int zone_reclaim_mode __read_mostly;
1553 #define RECLAIM_OFF 0
1554 #define RECLAIM_ZONE (1<<0) /* Run shrink_cache on the zone */
1555 #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
1556 #define RECLAIM_SWAP (1<<2) /* Swap pages out during reclaim */
1559 * Priority for ZONE_RECLAIM. This determines the fraction of pages
1560 * of a node considered for each zone_reclaim. 4 scans 1/16th of
1563 #define ZONE_RECLAIM_PRIORITY 4
1566 * Percentage of pages in a zone that must be unmapped for zone_reclaim to
1569 int sysctl_min_unmapped_ratio = 1;
1572 * If the number of slab pages in a zone grows beyond this percentage then
1573 * slab reclaim needs to occur.
1575 int sysctl_min_slab_ratio = 5;
1578 * Try to free up some pages from this zone through reclaim.
1580 static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
1582 /* Minimum pages needed in order to stay on node */
1583 const unsigned long nr_pages = 1 << order;
1584 struct task_struct *p = current;
1585 struct reclaim_state reclaim_state;
1587 unsigned long nr_reclaimed = 0;
1588 struct scan_control sc = {
1589 .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
1590 .may_swap = !!(zone_reclaim_mode & RECLAIM_SWAP),
1591 .swap_cluster_max = max_t(unsigned long, nr_pages,
1593 .gfp_mask = gfp_mask,
1594 .swappiness = vm_swappiness,
1597 disable_swap_token();
1600 * We need to be able to allocate from the reserves for RECLAIM_SWAP
1601 * and we also need to be able to write out pages for RECLAIM_WRITE
1604 p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
1605 reclaim_state.reclaimed_slab = 0;
1606 p->reclaim_state = &reclaim_state;
1608 if (zone_page_state(zone, NR_FILE_PAGES) -
1609 zone_page_state(zone, NR_FILE_MAPPED) >
1610 zone->min_unmapped_ratio) {
1612 * Free memory by calling shrink zone with increasing
1613 * priorities until we have enough memory freed.
1615 priority = ZONE_RECLAIM_PRIORITY;
1617 note_zone_scanning_priority(zone, priority);
1618 nr_reclaimed += shrink_zone(priority, zone, &sc);
1620 } while (priority >= 0 && nr_reclaimed < nr_pages);
1623 if (zone_page_state(zone, NR_SLAB) > zone->min_slab_pages) {
1625 * shrink_slab() does not currently allow us to determine how
1626 * many pages were freed in this zone. So we take the current
1627 * number of slab pages and shake the slab until it is reduced
1628 * by the same nr_pages that we used for reclaiming unmapped
1631 * Note that shrink_slab will free memory on all zones and may
1634 unsigned long limit = zone_page_state(zone,
1635 NR_SLAB) - nr_pages;
1637 while (shrink_slab(sc.nr_scanned, gfp_mask, order) &&
1638 zone_page_state(zone, NR_SLAB) > limit)
1642 p->reclaim_state = NULL;
1643 current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
1644 return nr_reclaimed >= nr_pages;
1647 int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
1653 * Zone reclaim reclaims unmapped file backed pages and
1654 * slab pages if we are over the defined limits.
1656 * A small portion of unmapped file backed pages is needed for
1657 * file I/O otherwise pages read by file I/O will be immediately
1658 * thrown out if the zone is overallocated. So we do not reclaim
1659 * if less than a specified percentage of the zone is used by
1660 * unmapped file backed pages.
1662 if (zone_page_state(zone, NR_FILE_PAGES) -
1663 zone_page_state(zone, NR_FILE_MAPPED) <= zone->min_unmapped_ratio
1664 && zone_page_state(zone, NR_SLAB)
1665 <= zone->min_slab_pages)
1669 * Avoid concurrent zone reclaims, do not reclaim in a zone that does
1670 * not have reclaimable pages and if we should not delay the allocation
1673 if (!(gfp_mask & __GFP_WAIT) ||
1674 zone->all_unreclaimable ||
1675 atomic_read(&zone->reclaim_in_progress) > 0 ||
1676 (current->flags & PF_MEMALLOC))
1680 * Only run zone reclaim on the local zone or on zones that do not
1681 * have associated processors. This will favor the local processor
1682 * over remote processors and spread off node memory allocations
1683 * as wide as possible.
1685 node_id = zone->zone_pgdat->node_id;
1686 mask = node_to_cpumask(node_id);
1687 if (!cpus_empty(mask) && node_id != numa_node_id())
1689 return __zone_reclaim(zone, gfp_mask, order);