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/notifier.h>
34 #include <linux/rwsem.h>
36 #include <asm/tlbflush.h>
37 #include <asm/div64.h>
39 #include <linux/swapops.h>
41 /* possible outcome of pageout() */
43 /* failed to write page out, page is locked */
45 /* move page to the active list, page is locked */
47 /* page has been sent to the disk successfully, page is unlocked */
49 /* page is clean and locked */
54 /* Ask refill_inactive_zone, or shrink_cache to scan this many pages */
55 unsigned long nr_to_scan;
57 /* Incremented by the number of inactive pages that were scanned */
58 unsigned long nr_scanned;
60 /* Incremented by the number of pages reclaimed */
61 unsigned long nr_reclaimed;
63 unsigned long nr_mapped; /* From page_state */
65 /* How many pages shrink_cache() should reclaim */
68 /* Ask shrink_caches, or shrink_zone to scan at this priority */
69 unsigned int priority;
71 /* This context's GFP mask */
72 unsigned int gfp_mask;
78 * The list of shrinker callbacks used by to apply pressure to
83 struct list_head list;
84 int seeks; /* seeks to recreate an obj */
85 long nr; /* objs pending delete */
88 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
90 #ifdef ARCH_HAS_PREFETCH
91 #define prefetch_prev_lru_page(_page, _base, _field) \
93 if ((_page)->lru.prev != _base) { \
96 prev = lru_to_page(&(_page->lru)); \
97 prefetch(&prev->_field); \
101 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
104 #ifdef ARCH_HAS_PREFETCHW
105 #define prefetchw_prev_lru_page(_page, _base, _field) \
107 if ((_page)->lru.prev != _base) { \
110 prev = lru_to_page(&(_page->lru)); \
111 prefetchw(&prev->_field); \
115 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
119 * From 0 .. 100. Higher means more swappy.
121 int vm_swappiness = 60;
122 static long total_memory;
124 static LIST_HEAD(shrinker_list);
125 static DECLARE_RWSEM(shrinker_rwsem);
128 * Add a shrinker callback to be called from the vm
130 struct shrinker *set_shrinker(int seeks, shrinker_t theshrinker)
132 struct shrinker *shrinker;
134 shrinker = kmalloc(sizeof(*shrinker), GFP_KERNEL);
136 shrinker->shrinker = theshrinker;
137 shrinker->seeks = seeks;
139 down_write(&shrinker_rwsem);
140 list_add(&shrinker->list, &shrinker_list);
141 up_write(&shrinker_rwsem);
145 EXPORT_SYMBOL(set_shrinker);
150 void remove_shrinker(struct shrinker *shrinker)
152 down_write(&shrinker_rwsem);
153 list_del(&shrinker->list);
154 up_write(&shrinker_rwsem);
157 EXPORT_SYMBOL(remove_shrinker);
159 #define SHRINK_BATCH 128
161 * Call the shrink functions to age shrinkable caches
163 * Here we assume it costs one seek to replace a lru page and that it also
164 * takes a seek to recreate a cache object. With this in mind we age equal
165 * percentages of the lru and ageable caches. This should balance the seeks
166 * generated by these structures.
168 * If the vm encounted mapped pages on the LRU it increase the pressure on
169 * slab to avoid swapping.
171 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
173 * `lru_pages' represents the number of on-LRU pages in all the zones which
174 * are eligible for the caller's allocation attempt. It is used for balancing
175 * slab reclaim versus page reclaim.
177 static int shrink_slab(unsigned long scanned, unsigned int gfp_mask,
178 unsigned long lru_pages)
180 struct shrinker *shrinker;
183 scanned = SWAP_CLUSTER_MAX;
185 if (!down_read_trylock(&shrinker_rwsem))
188 list_for_each_entry(shrinker, &shrinker_list, list) {
189 unsigned long long delta;
190 unsigned long total_scan;
192 delta = (4 * scanned) / shrinker->seeks;
193 delta *= (*shrinker->shrinker)(0, gfp_mask);
194 do_div(delta, lru_pages + 1);
195 shrinker->nr += delta;
196 if (shrinker->nr < 0)
197 shrinker->nr = LONG_MAX; /* It wrapped! */
199 total_scan = shrinker->nr;
202 while (total_scan >= SHRINK_BATCH) {
203 long this_scan = SHRINK_BATCH;
206 shrink_ret = (*shrinker->shrinker)(this_scan, gfp_mask);
207 if (shrink_ret == -1)
209 mod_page_state(slabs_scanned, this_scan);
210 total_scan -= this_scan;
215 shrinker->nr += total_scan;
217 up_read(&shrinker_rwsem);
221 /* Called without lock on whether page is mapped, so answer is unstable */
222 static inline int page_mapping_inuse(struct page *page)
224 struct address_space *mapping;
226 /* Page is in somebody's page tables. */
227 if (page_mapped(page))
230 /* Be more reluctant to reclaim swapcache than pagecache */
231 if (PageSwapCache(page))
234 mapping = page_mapping(page);
238 /* File is mmap'd by somebody? */
239 return mapping_mapped(mapping);
242 static inline int is_page_cache_freeable(struct page *page)
244 return page_count(page) - !!PagePrivate(page) == 2;
247 static int may_write_to_queue(struct backing_dev_info *bdi)
249 if (current_is_kswapd())
251 if (current_is_pdflush()) /* This is unlikely, but why not... */
253 if (!bdi_write_congested(bdi))
255 if (bdi == current->backing_dev_info)
261 * We detected a synchronous write error writing a page out. Probably
262 * -ENOSPC. We need to propagate that into the address_space for a subsequent
263 * fsync(), msync() or close().
265 * The tricky part is that after writepage we cannot touch the mapping: nothing
266 * prevents it from being freed up. But we have a ref on the page and once
267 * that page is locked, the mapping is pinned.
269 * We're allowed to run sleeping lock_page() here because we know the caller has
272 static void handle_write_error(struct address_space *mapping,
273 struct page *page, int error)
276 if (page_mapping(page) == mapping) {
277 if (error == -ENOSPC)
278 set_bit(AS_ENOSPC, &mapping->flags);
280 set_bit(AS_EIO, &mapping->flags);
286 * pageout is called by shrink_list() for each dirty page. Calls ->writepage().
288 static pageout_t pageout(struct page *page, struct address_space *mapping)
291 * If the page is dirty, only perform writeback if that write
292 * will be non-blocking. To prevent this allocation from being
293 * stalled by pagecache activity. But note that there may be
294 * stalls if we need to run get_block(). We could test
295 * PagePrivate for that.
297 * If this process is currently in generic_file_write() against
298 * this page's queue, we can perform writeback even if that
301 * If the page is swapcache, write it back even if that would
302 * block, for some throttling. This happens by accident, because
303 * swap_backing_dev_info is bust: it doesn't reflect the
304 * congestion state of the swapdevs. Easy to fix, if needed.
305 * See swapfile.c:page_queue_congested().
307 if (!is_page_cache_freeable(page))
311 if (mapping->a_ops->writepage == NULL)
312 return PAGE_ACTIVATE;
313 if (!may_write_to_queue(mapping->backing_dev_info))
316 if (clear_page_dirty_for_io(page)) {
318 struct writeback_control wbc = {
319 .sync_mode = WB_SYNC_NONE,
320 .nr_to_write = SWAP_CLUSTER_MAX,
325 SetPageReclaim(page);
326 res = mapping->a_ops->writepage(page, &wbc);
328 handle_write_error(mapping, page, res);
329 if (res == WRITEPAGE_ACTIVATE) {
330 ClearPageReclaim(page);
331 return PAGE_ACTIVATE;
333 if (!PageWriteback(page)) {
334 /* synchronous write or broken a_ops? */
335 ClearPageReclaim(page);
345 * shrink_list adds the number of reclaimed pages to sc->nr_reclaimed
347 static int shrink_list(struct list_head *page_list, struct scan_control *sc)
349 LIST_HEAD(ret_pages);
350 struct pagevec freed_pvec;
356 pagevec_init(&freed_pvec, 1);
357 while (!list_empty(page_list)) {
358 struct address_space *mapping;
365 page = lru_to_page(page_list);
366 list_del(&page->lru);
368 if (TestSetPageLocked(page))
371 BUG_ON(PageActive(page));
374 /* Double the slab pressure for mapped and swapcache pages */
375 if (page_mapped(page) || PageSwapCache(page))
378 if (PageWriteback(page))
381 referenced = page_referenced(page, 1, sc->priority <= 0);
382 /* In active use or really unfreeable? Activate it. */
383 if (referenced && page_mapping_inuse(page))
384 goto activate_locked;
388 * Anonymous process memory has backing store?
389 * Try to allocate it some swap space here.
391 if (PageAnon(page) && !PageSwapCache(page)) {
392 if (!add_to_swap(page))
393 goto activate_locked;
395 #endif /* CONFIG_SWAP */
397 mapping = page_mapping(page);
398 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
399 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
402 * The page is mapped into the page tables of one or more
403 * processes. Try to unmap it here.
405 if (page_mapped(page) && mapping) {
406 switch (try_to_unmap(page)) {
408 goto activate_locked;
412 ; /* try to free the page below */
416 if (PageDirty(page)) {
421 if (laptop_mode && !sc->may_writepage)
424 /* Page is dirty, try to write it out here */
425 switch(pageout(page, mapping)) {
429 goto activate_locked;
431 if (PageWriteback(page) || PageDirty(page))
434 * A synchronous write - probably a ramdisk. Go
435 * ahead and try to reclaim the page.
437 if (TestSetPageLocked(page))
439 if (PageDirty(page) || PageWriteback(page))
441 mapping = page_mapping(page);
443 ; /* try to free the page below */
448 * If the page has buffers, try to free the buffer mappings
449 * associated with this page. If we succeed we try to free
452 * We do this even if the page is PageDirty().
453 * try_to_release_page() does not perform I/O, but it is
454 * possible for a page to have PageDirty set, but it is actually
455 * clean (all its buffers are clean). This happens if the
456 * buffers were written out directly, with submit_bh(). ext3
457 * will do this, as well as the blockdev mapping.
458 * try_to_release_page() will discover that cleanness and will
459 * drop the buffers and mark the page clean - it can be freed.
461 * Rarely, pages can have buffers and no ->mapping. These are
462 * the pages which were not successfully invalidated in
463 * truncate_complete_page(). We try to drop those buffers here
464 * and if that worked, and the page is no longer mapped into
465 * process address space (page_count == 1) it can be freed.
466 * Otherwise, leave the page on the LRU so it is swappable.
468 if (PagePrivate(page)) {
469 if (!try_to_release_page(page, sc->gfp_mask))
470 goto activate_locked;
471 if (!mapping && page_count(page) == 1)
476 goto keep_locked; /* truncate got there first */
478 spin_lock_irq(&mapping->tree_lock);
481 * The non-racy check for busy page. It is critical to check
482 * PageDirty _after_ making sure that the page is freeable and
483 * not in use by anybody. (pagecache + us == 2)
485 if (page_count(page) != 2 || PageDirty(page)) {
486 spin_unlock_irq(&mapping->tree_lock);
491 if (PageSwapCache(page)) {
492 swp_entry_t swap = { .val = page->private };
493 __delete_from_swap_cache(page);
494 spin_unlock_irq(&mapping->tree_lock);
496 __put_page(page); /* The pagecache ref */
499 #endif /* CONFIG_SWAP */
501 __remove_from_page_cache(page);
502 spin_unlock_irq(&mapping->tree_lock);
508 if (!pagevec_add(&freed_pvec, page))
509 __pagevec_release_nonlru(&freed_pvec);
518 list_add(&page->lru, &ret_pages);
519 BUG_ON(PageLRU(page));
521 list_splice(&ret_pages, page_list);
522 if (pagevec_count(&freed_pvec))
523 __pagevec_release_nonlru(&freed_pvec);
524 mod_page_state(pgactivate, pgactivate);
525 sc->nr_reclaimed += reclaimed;
530 * zone->lru_lock is heavily contented. We relieve it by quickly privatising
531 * a batch of pages and working on them outside the lock. Any pages which were
532 * not freed will be added back to the LRU.
534 * shrink_cache() adds the number of pages reclaimed to sc->nr_reclaimed
536 * For pagecache intensive workloads, the first loop here is the hottest spot
537 * in the kernel (apart from the copy_*_user functions).
539 static void shrink_cache(struct zone *zone, struct scan_control *sc)
541 LIST_HEAD(page_list);
543 int max_scan = sc->nr_to_scan;
545 pagevec_init(&pvec, 1);
548 spin_lock_irq(&zone->lru_lock);
549 while (max_scan > 0) {
555 while (nr_scan++ < SWAP_CLUSTER_MAX &&
556 !list_empty(&zone->inactive_list)) {
557 page = lru_to_page(&zone->inactive_list);
559 prefetchw_prev_lru_page(page,
560 &zone->inactive_list, flags);
562 if (!TestClearPageLRU(page))
564 list_del(&page->lru);
565 if (get_page_testone(page)) {
567 * It is being freed elsewhere
571 list_add(&page->lru, &zone->inactive_list);
574 list_add(&page->lru, &page_list);
577 zone->nr_inactive -= nr_taken;
578 zone->pages_scanned += nr_scan;
579 spin_unlock_irq(&zone->lru_lock);
585 if (current_is_kswapd())
586 mod_page_state_zone(zone, pgscan_kswapd, nr_scan);
588 mod_page_state_zone(zone, pgscan_direct, nr_scan);
589 nr_freed = shrink_list(&page_list, sc);
590 if (current_is_kswapd())
591 mod_page_state(kswapd_steal, nr_freed);
592 mod_page_state_zone(zone, pgsteal, nr_freed);
593 sc->nr_to_reclaim -= nr_freed;
595 spin_lock_irq(&zone->lru_lock);
597 * Put back any unfreeable pages.
599 while (!list_empty(&page_list)) {
600 page = lru_to_page(&page_list);
601 if (TestSetPageLRU(page))
603 list_del(&page->lru);
604 if (PageActive(page))
605 add_page_to_active_list(zone, page);
607 add_page_to_inactive_list(zone, page);
608 if (!pagevec_add(&pvec, page)) {
609 spin_unlock_irq(&zone->lru_lock);
610 __pagevec_release(&pvec);
611 spin_lock_irq(&zone->lru_lock);
615 spin_unlock_irq(&zone->lru_lock);
617 pagevec_release(&pvec);
621 * This moves pages from the active list to the inactive list.
623 * We move them the other way if the page is referenced by one or more
624 * processes, from rmap.
626 * If the pages are mostly unmapped, the processing is fast and it is
627 * appropriate to hold zone->lru_lock across the whole operation. But if
628 * the pages are mapped, the processing is slow (page_referenced()) so we
629 * should drop zone->lru_lock around each page. It's impossible to balance
630 * this, so instead we remove the pages from the LRU while processing them.
631 * It is safe to rely on PG_active against the non-LRU pages in here because
632 * nobody will play with that bit on a non-LRU page.
634 * The downside is that we have to touch page->_count against each page.
635 * But we had to alter page->flags anyway.
638 refill_inactive_zone(struct zone *zone, struct scan_control *sc)
641 int pgdeactivate = 0;
643 int nr_pages = sc->nr_to_scan;
644 LIST_HEAD(l_hold); /* The pages which were snipped off */
645 LIST_HEAD(l_inactive); /* Pages to go onto the inactive_list */
646 LIST_HEAD(l_active); /* Pages to go onto the active_list */
649 int reclaim_mapped = 0;
656 spin_lock_irq(&zone->lru_lock);
657 while (pgscanned < nr_pages && !list_empty(&zone->active_list)) {
658 page = lru_to_page(&zone->active_list);
659 prefetchw_prev_lru_page(page, &zone->active_list, flags);
660 if (!TestClearPageLRU(page))
662 list_del(&page->lru);
663 if (get_page_testone(page)) {
665 * It was already free! release_pages() or put_page()
666 * are about to remove it from the LRU and free it. So
667 * put the refcount back and put the page back on the
672 list_add(&page->lru, &zone->active_list);
674 list_add(&page->lru, &l_hold);
679 zone->pages_scanned += pgscanned;
680 zone->nr_active -= pgmoved;
681 spin_unlock_irq(&zone->lru_lock);
684 * `distress' is a measure of how much trouble we're having reclaiming
685 * pages. 0 -> no problems. 100 -> great trouble.
687 distress = 100 >> zone->prev_priority;
690 * The point of this algorithm is to decide when to start reclaiming
691 * mapped memory instead of just pagecache. Work out how much memory
694 mapped_ratio = (sc->nr_mapped * 100) / total_memory;
697 * Now decide how much we really want to unmap some pages. The mapped
698 * ratio is downgraded - just because there's a lot of mapped memory
699 * doesn't necessarily mean that page reclaim isn't succeeding.
701 * The distress ratio is important - we don't want to start going oom.
703 * A 100% value of vm_swappiness overrides this algorithm altogether.
705 swap_tendency = mapped_ratio / 2 + distress + vm_swappiness;
708 * Now use this metric to decide whether to start moving mapped memory
709 * onto the inactive list.
711 if (swap_tendency >= 100)
714 while (!list_empty(&l_hold)) {
716 page = lru_to_page(&l_hold);
717 list_del(&page->lru);
718 if (page_mapped(page)) {
719 if (!reclaim_mapped ||
720 (total_swap_pages == 0 && PageAnon(page)) ||
721 page_referenced(page, 0, sc->priority <= 0)) {
722 list_add(&page->lru, &l_active);
726 list_add(&page->lru, &l_inactive);
729 pagevec_init(&pvec, 1);
731 spin_lock_irq(&zone->lru_lock);
732 while (!list_empty(&l_inactive)) {
733 page = lru_to_page(&l_inactive);
734 prefetchw_prev_lru_page(page, &l_inactive, flags);
735 if (TestSetPageLRU(page))
737 if (!TestClearPageActive(page))
739 list_move(&page->lru, &zone->inactive_list);
741 if (!pagevec_add(&pvec, page)) {
742 zone->nr_inactive += pgmoved;
743 spin_unlock_irq(&zone->lru_lock);
744 pgdeactivate += pgmoved;
746 if (buffer_heads_over_limit)
747 pagevec_strip(&pvec);
748 __pagevec_release(&pvec);
749 spin_lock_irq(&zone->lru_lock);
752 zone->nr_inactive += pgmoved;
753 pgdeactivate += pgmoved;
754 if (buffer_heads_over_limit) {
755 spin_unlock_irq(&zone->lru_lock);
756 pagevec_strip(&pvec);
757 spin_lock_irq(&zone->lru_lock);
761 while (!list_empty(&l_active)) {
762 page = lru_to_page(&l_active);
763 prefetchw_prev_lru_page(page, &l_active, flags);
764 if (TestSetPageLRU(page))
766 BUG_ON(!PageActive(page));
767 list_move(&page->lru, &zone->active_list);
769 if (!pagevec_add(&pvec, page)) {
770 zone->nr_active += pgmoved;
772 spin_unlock_irq(&zone->lru_lock);
773 __pagevec_release(&pvec);
774 spin_lock_irq(&zone->lru_lock);
777 zone->nr_active += pgmoved;
778 spin_unlock_irq(&zone->lru_lock);
779 pagevec_release(&pvec);
781 mod_page_state_zone(zone, pgrefill, pgscanned);
782 mod_page_state(pgdeactivate, pgdeactivate);
786 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
789 shrink_zone(struct zone *zone, struct scan_control *sc)
791 unsigned long nr_active;
792 unsigned long nr_inactive;
795 * Add one to `nr_to_scan' just to make sure that the kernel will
796 * slowly sift through the active list.
798 zone->nr_scan_active += (zone->nr_active >> sc->priority) + 1;
799 nr_active = zone->nr_scan_active;
800 if (nr_active >= SWAP_CLUSTER_MAX)
801 zone->nr_scan_active = 0;
805 zone->nr_scan_inactive += (zone->nr_inactive >> sc->priority) + 1;
806 nr_inactive = zone->nr_scan_inactive;
807 if (nr_inactive >= SWAP_CLUSTER_MAX)
808 zone->nr_scan_inactive = 0;
812 sc->nr_to_reclaim = SWAP_CLUSTER_MAX;
814 while (nr_active || nr_inactive) {
816 sc->nr_to_scan = min(nr_active,
817 (unsigned long)SWAP_CLUSTER_MAX);
818 nr_active -= sc->nr_to_scan;
819 refill_inactive_zone(zone, sc);
823 sc->nr_to_scan = min(nr_inactive,
824 (unsigned long)SWAP_CLUSTER_MAX);
825 nr_inactive -= sc->nr_to_scan;
826 shrink_cache(zone, sc);
827 if (sc->nr_to_reclaim <= 0)
834 * This is the direct reclaim path, for page-allocating processes. We only
835 * try to reclaim pages from zones which will satisfy the caller's allocation
838 * We reclaim from a zone even if that zone is over pages_high. Because:
839 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
841 * b) The zones may be over pages_high but they must go *over* pages_high to
842 * satisfy the `incremental min' zone defense algorithm.
844 * Returns the number of reclaimed pages.
846 * If a zone is deemed to be full of pinned pages then just give it a light
847 * scan then give up on it.
850 shrink_caches(struct zone **zones, struct scan_control *sc)
854 for (i = 0; zones[i] != NULL; i++) {
855 struct zone *zone = zones[i];
857 if (zone->present_pages == 0)
860 zone->temp_priority = sc->priority;
861 if (zone->prev_priority > sc->priority)
862 zone->prev_priority = sc->priority;
864 if (zone->all_unreclaimable && sc->priority != DEF_PRIORITY)
865 continue; /* Let kswapd poll it */
867 shrink_zone(zone, sc);
872 * This is the main entry point to direct page reclaim.
874 * If a full scan of the inactive list fails to free enough memory then we
875 * are "out of memory" and something needs to be killed.
877 * If the caller is !__GFP_FS then the probability of a failure is reasonably
878 * high - the zone may be full of dirty or under-writeback pages, which this
879 * caller can't do much about. We kick pdflush and take explicit naps in the
880 * hope that some of these pages can be written. But if the allocating task
881 * holds filesystem locks which prevent writeout this might not work, and the
882 * allocation attempt will fail.
884 int try_to_free_pages(struct zone **zones,
885 unsigned int gfp_mask, unsigned int order)
889 int total_scanned = 0, total_reclaimed = 0;
890 struct reclaim_state *reclaim_state = current->reclaim_state;
891 struct scan_control sc;
892 unsigned long lru_pages = 0;
895 sc.gfp_mask = gfp_mask;
896 sc.may_writepage = 0;
898 inc_page_state(allocstall);
900 for (i = 0; zones[i] != NULL; i++) {
901 struct zone *zone = zones[i];
903 zone->temp_priority = DEF_PRIORITY;
904 lru_pages += zone->nr_active + zone->nr_inactive;
907 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
908 sc.nr_mapped = read_page_state(nr_mapped);
911 sc.priority = priority;
912 shrink_caches(zones, &sc);
913 shrink_slab(sc.nr_scanned, gfp_mask, lru_pages);
915 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
916 reclaim_state->reclaimed_slab = 0;
918 if (sc.nr_reclaimed >= SWAP_CLUSTER_MAX) {
922 total_scanned += sc.nr_scanned;
923 total_reclaimed += sc.nr_reclaimed;
926 * Try to write back as many pages as we just scanned. This
927 * tends to cause slow streaming writers to write data to the
928 * disk smoothly, at the dirtying rate, which is nice. But
929 * that's undesirable in laptop mode, where we *want* lumpy
930 * writeout. So in laptop mode, write out the whole world.
932 if (total_scanned > SWAP_CLUSTER_MAX + SWAP_CLUSTER_MAX/2) {
933 wakeup_bdflush(laptop_mode ? 0 : total_scanned);
934 sc.may_writepage = 1;
937 /* Take a nap, wait for some writeback to complete */
938 if (sc.nr_scanned && priority < DEF_PRIORITY - 2)
939 blk_congestion_wait(WRITE, HZ/10);
942 for (i = 0; zones[i] != 0; i++)
943 zones[i]->prev_priority = zones[i]->temp_priority;
948 * For kswapd, balance_pgdat() will work across all this node's zones until
949 * they are all at pages_high.
951 * If `nr_pages' is non-zero then it is the number of pages which are to be
952 * reclaimed, regardless of the zone occupancies. This is a software suspend
955 * Returns the number of pages which were actually freed.
957 * There is special handling here for zones which are full of pinned pages.
958 * This can happen if the pages are all mlocked, or if they are all used by
959 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
960 * What we do is to detect the case where all pages in the zone have been
961 * scanned twice and there has been zero successful reclaim. Mark the zone as
962 * dead and from now on, only perform a short scan. Basically we're polling
963 * the zone for when the problem goes away.
965 * kswapd scans the zones in the highmem->normal->dma direction. It skips
966 * zones which have free_pages > pages_high, but once a zone is found to have
967 * free_pages <= pages_high, we scan that zone and the lower zones regardless
968 * of the number of free pages in the lower zones. This interoperates with
969 * the page allocator fallback scheme to ensure that aging of pages is balanced
972 static int balance_pgdat(pg_data_t *pgdat, int nr_pages, int order)
974 int to_free = nr_pages;
978 int total_scanned, total_reclaimed;
979 struct reclaim_state *reclaim_state = current->reclaim_state;
980 struct scan_control sc;
985 sc.gfp_mask = GFP_KERNEL;
986 sc.may_writepage = 0;
987 sc.nr_mapped = read_page_state(nr_mapped);
989 inc_page_state(pageoutrun);
991 for (i = 0; i < pgdat->nr_zones; i++) {
992 struct zone *zone = pgdat->node_zones + i;
994 zone->temp_priority = DEF_PRIORITY;
997 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
998 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
999 unsigned long lru_pages = 0;
1003 if (nr_pages == 0) {
1005 * Scan in the highmem->dma direction for the highest
1006 * zone which needs scanning
1008 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
1009 struct zone *zone = pgdat->node_zones + i;
1011 if (zone->present_pages == 0)
1014 if (zone->all_unreclaimable &&
1015 priority != DEF_PRIORITY)
1018 if (!zone_watermark_ok(zone, order,
1019 zone->pages_high, 0, 0, 0)) {
1026 end_zone = pgdat->nr_zones - 1;
1029 for (i = 0; i <= end_zone; i++) {
1030 struct zone *zone = pgdat->node_zones + i;
1032 lru_pages += zone->nr_active + zone->nr_inactive;
1036 * Now scan the zone in the dma->highmem direction, stopping
1037 * at the last zone which needs scanning.
1039 * We do this because the page allocator works in the opposite
1040 * direction. This prevents the page allocator from allocating
1041 * pages behind kswapd's direction of progress, which would
1042 * cause too much scanning of the lower zones.
1044 for (i = 0; i <= end_zone; i++) {
1045 struct zone *zone = pgdat->node_zones + i;
1047 if (zone->present_pages == 0)
1050 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1053 if (nr_pages == 0) { /* Not software suspend */
1054 if (!zone_watermark_ok(zone, order,
1055 zone->pages_high, end_zone, 0, 0))
1058 zone->temp_priority = priority;
1059 if (zone->prev_priority > priority)
1060 zone->prev_priority = priority;
1062 sc.nr_reclaimed = 0;
1063 sc.priority = priority;
1064 shrink_zone(zone, &sc);
1065 reclaim_state->reclaimed_slab = 0;
1066 shrink_slab(sc.nr_scanned, GFP_KERNEL, lru_pages);
1067 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
1068 total_reclaimed += sc.nr_reclaimed;
1069 total_scanned += sc.nr_scanned;
1070 if (zone->all_unreclaimable)
1072 if (zone->pages_scanned >= (zone->nr_active +
1073 zone->nr_inactive) * 4)
1074 zone->all_unreclaimable = 1;
1076 * If we've done a decent amount of scanning and
1077 * the reclaim ratio is low, start doing writepage
1078 * even in laptop mode
1080 if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
1081 total_scanned > total_reclaimed+total_reclaimed/2)
1082 sc.may_writepage = 1;
1084 if (nr_pages && to_free > total_reclaimed)
1085 continue; /* swsusp: need to do more work */
1087 break; /* kswapd: all done */
1089 * OK, kswapd is getting into trouble. Take a nap, then take
1090 * another pass across the zones.
1092 if (total_scanned && priority < DEF_PRIORITY - 2)
1093 blk_congestion_wait(WRITE, HZ/10);
1096 * We do this so kswapd doesn't build up large priorities for
1097 * example when it is freeing in parallel with allocators. It
1098 * matches the direct reclaim path behaviour in terms of impact
1099 * on zone->*_priority.
1101 if (total_reclaimed >= SWAP_CLUSTER_MAX)
1105 for (i = 0; i < pgdat->nr_zones; i++) {
1106 struct zone *zone = pgdat->node_zones + i;
1108 zone->prev_priority = zone->temp_priority;
1110 if (!all_zones_ok) {
1115 return total_reclaimed;
1119 * The background pageout daemon, started as a kernel thread
1120 * from the init process.
1122 * This basically trickles out pages so that we have _some_
1123 * free memory available even if there is no other activity
1124 * that frees anything up. This is needed for things like routing
1125 * etc, where we otherwise might have all activity going on in
1126 * asynchronous contexts that cannot page things out.
1128 * If there are applications that are active memory-allocators
1129 * (most normal use), this basically shouldn't matter.
1131 static int kswapd(void *p)
1133 unsigned long order;
1134 pg_data_t *pgdat = (pg_data_t*)p;
1135 struct task_struct *tsk = current;
1137 struct reclaim_state reclaim_state = {
1138 .reclaimed_slab = 0,
1142 daemonize("kswapd%d", pgdat->node_id);
1143 cpumask = node_to_cpumask(pgdat->node_id);
1144 if (!cpus_empty(cpumask))
1145 set_cpus_allowed(tsk, cpumask);
1146 current->reclaim_state = &reclaim_state;
1149 * Tell the memory management that we're a "memory allocator",
1150 * and that if we need more memory we should get access to it
1151 * regardless (see "__alloc_pages()"). "kswapd" should
1152 * never get caught in the normal page freeing logic.
1154 * (Kswapd normally doesn't need memory anyway, but sometimes
1155 * you need a small amount of memory in order to be able to
1156 * page out something else, and this flag essentially protects
1157 * us from recursively trying to free more memory as we're
1158 * trying to free the first piece of memory in the first place).
1160 tsk->flags |= PF_MEMALLOC|PF_KSWAPD;
1164 unsigned long new_order;
1165 if (current->flags & PF_FREEZE)
1166 refrigerator(PF_FREEZE);
1168 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
1169 new_order = pgdat->kswapd_max_order;
1170 pgdat->kswapd_max_order = 0;
1171 if (order < new_order) {
1173 * Don't sleep if someone wants a larger 'order'
1179 order = pgdat->kswapd_max_order;
1181 finish_wait(&pgdat->kswapd_wait, &wait);
1183 balance_pgdat(pgdat, 0, order);
1189 * A zone is low on free memory, so wake its kswapd task to service it.
1191 void wakeup_kswapd(struct zone *zone, int order)
1195 if (zone->present_pages == 0)
1198 pgdat = zone->zone_pgdat;
1199 if (zone_watermark_ok(zone, order, zone->pages_low, 0, 0, 0))
1201 if (pgdat->kswapd_max_order < order)
1202 pgdat->kswapd_max_order = order;
1203 if (!waitqueue_active(&zone->zone_pgdat->kswapd_wait))
1205 wake_up_interruptible(&zone->zone_pgdat->kswapd_wait);
1210 * Try to free `nr_pages' of memory, system-wide. Returns the number of freed
1213 int shrink_all_memory(int nr_pages)
1216 int nr_to_free = nr_pages;
1218 struct reclaim_state reclaim_state = {
1219 .reclaimed_slab = 0,
1222 current->reclaim_state = &reclaim_state;
1223 for_each_pgdat(pgdat) {
1225 freed = balance_pgdat(pgdat, nr_to_free, 0);
1227 nr_to_free -= freed;
1228 if (nr_to_free <= 0)
1231 current->reclaim_state = NULL;
1236 #ifdef CONFIG_HOTPLUG_CPU
1237 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1238 not required for correctness. So if the last cpu in a node goes
1239 away, we get changed to run anywhere: as the first one comes back,
1240 restore their cpu bindings. */
1241 static int __devinit cpu_callback(struct notifier_block *nfb,
1242 unsigned long action,
1248 if (action == CPU_ONLINE) {
1249 for_each_pgdat(pgdat) {
1250 mask = node_to_cpumask(pgdat->node_id);
1251 if (any_online_cpu(mask) != NR_CPUS)
1252 /* One of our CPUs online: restore mask */
1253 set_cpus_allowed(pgdat->kswapd, mask);
1258 #endif /* CONFIG_HOTPLUG_CPU */
1260 static int __init kswapd_init(void)
1264 for_each_pgdat(pgdat)
1266 = find_task_by_real_pid(kernel_thread(kswapd, pgdat, CLONE_KERNEL));
1267 total_memory = nr_free_pagecache_pages();
1268 hotcpu_notifier(cpu_callback, 0);
1272 module_init(kswapd_init)