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/suspend.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/notifier.h>
36 #include <asm/pgalloc.h>
37 #include <asm/tlbflush.h>
38 #include <asm/div64.h>
40 #include <linux/swapops.h>
43 * From 0 .. 100. Higher means more swappy.
45 int vm_swappiness = 60;
46 static long total_memory;
48 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
50 #ifdef ARCH_HAS_PREFETCH
51 #define prefetch_prev_lru_page(_page, _base, _field) \
53 if ((_page)->lru.prev != _base) { \
56 prev = lru_to_page(&(_page->lru)); \
57 prefetch(&prev->_field); \
61 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
64 #ifdef ARCH_HAS_PREFETCHW
65 #define prefetchw_prev_lru_page(_page, _base, _field) \
67 if ((_page)->lru.prev != _base) { \
70 prev = lru_to_page(&(_page->lru)); \
71 prefetchw(&prev->_field); \
75 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
79 * The list of shrinker callbacks used by to apply pressure to
84 struct list_head list;
85 int seeks; /* seeks to recreate an obj */
86 long nr; /* objs pending delete */
89 static LIST_HEAD(shrinker_list);
90 static DECLARE_MUTEX(shrinker_sem);
93 * Add a shrinker callback to be called from the vm
95 struct shrinker *set_shrinker(int seeks, shrinker_t theshrinker)
97 struct shrinker *shrinker;
99 shrinker = kmalloc(sizeof(*shrinker), GFP_KERNEL);
101 shrinker->shrinker = theshrinker;
102 shrinker->seeks = seeks;
105 list_add(&shrinker->list, &shrinker_list);
111 EXPORT_SYMBOL(set_shrinker);
116 void remove_shrinker(struct shrinker *shrinker)
119 list_del(&shrinker->list);
124 EXPORT_SYMBOL(remove_shrinker);
126 #define SHRINK_BATCH 128
128 * Call the shrink functions to age shrinkable caches
130 * Here we assume it costs one seek to replace a lru page and that it also
131 * takes a seek to recreate a cache object. With this in mind we age equal
132 * percentages of the lru and ageable caches. This should balance the seeks
133 * generated by these structures.
135 * If the vm encounted mapped pages on the LRU it increase the pressure on
136 * slab to avoid swapping.
138 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
140 static int shrink_slab(unsigned long scanned, unsigned int gfp_mask)
142 struct shrinker *shrinker;
145 if (down_trylock(&shrinker_sem))
148 pages = nr_used_zone_pages();
149 list_for_each_entry(shrinker, &shrinker_list, list) {
150 unsigned long long delta;
152 delta = (4 * scanned) / shrinker->seeks;
153 delta *= (*shrinker->shrinker)(0, gfp_mask);
154 do_div(delta, pages + 1);
155 shrinker->nr += delta;
156 if (shrinker->nr > SHRINK_BATCH) {
157 long nr_to_scan = shrinker->nr;
160 mod_page_state(slabs_scanned, nr_to_scan);
162 long this_scan = nr_to_scan;
166 (*shrinker->shrinker)(this_scan, gfp_mask);
167 nr_to_scan -= this_scan;
176 /* Must be called with page's rmap lock held. */
177 static inline int page_mapping_inuse(struct page *page)
179 struct address_space *mapping;
181 /* Page is in somebody's page tables. */
182 if (page_mapped(page))
185 /* Be more reluctant to reclaim swapcache than pagecache */
186 if (PageSwapCache(page))
189 mapping = page_mapping(page);
193 /* File is mmap'd by somebody? */
194 return mapping_mapped(mapping);
197 static inline int is_page_cache_freeable(struct page *page)
199 return page_count(page) - !!PagePrivate(page) == 2;
202 static int may_write_to_queue(struct backing_dev_info *bdi)
204 if (current_is_kswapd())
206 if (current_is_pdflush()) /* This is unlikely, but why not... */
208 if (!bdi_write_congested(bdi))
210 if (bdi == current->backing_dev_info)
216 * We detected a synchronous write error writing a page out. Probably
217 * -ENOSPC. We need to propagate that into the address_space for a subsequent
218 * fsync(), msync() or close().
220 * The tricky part is that after writepage we cannot touch the mapping: nothing
221 * prevents it from being freed up. But we have a ref on the page and once
222 * that page is locked, the mapping is pinned.
224 * We're allowed to run sleeping lock_page() here because we know the caller has
227 static void handle_write_error(struct address_space *mapping,
228 struct page *page, int error)
231 if (page_mapping(page) == mapping) {
232 if (error == -ENOSPC)
233 set_bit(AS_ENOSPC, &mapping->flags);
235 set_bit(AS_EIO, &mapping->flags);
241 * shrink_list returns the number of reclaimed pages
244 shrink_list(struct list_head *page_list, unsigned int gfp_mask,
245 int *nr_scanned, int do_writepage)
247 struct address_space *mapping;
248 LIST_HEAD(ret_pages);
249 struct pagevec freed_pvec;
255 pagevec_init(&freed_pvec, 1);
256 while (!list_empty(page_list)) {
261 page = lru_to_page(page_list);
262 list_del(&page->lru);
264 if (TestSetPageLocked(page))
267 /* Double the slab pressure for mapped and swapcache pages */
268 if (page_mapped(page) || PageSwapCache(page))
271 BUG_ON(PageActive(page));
273 if (PageWriteback(page))
277 referenced = page_referenced(page);
278 if (referenced && page_mapping_inuse(page)) {
279 /* In active use or really unfreeable. Activate it. */
281 goto activate_locked;
284 mapping = page_mapping(page);
285 may_enter_fs = (gfp_mask & __GFP_FS);
289 * Anonymous process memory has backing store?
290 * Try to allocate it some swap space here.
292 * XXX: implement swap clustering ?
294 if (PageAnon(page) && !PageSwapCache(page)) {
296 if (!add_to_swap(page))
297 goto activate_locked;
300 if (PageSwapCache(page)) {
301 mapping = &swapper_space;
302 may_enter_fs = (gfp_mask & __GFP_IO);
304 #endif /* CONFIG_SWAP */
307 * The page is mapped into the page tables of one or more
308 * processes. Try to unmap it here.
310 if (page_mapped(page) && mapping) {
311 switch (try_to_unmap(page)) {
314 goto activate_locked;
319 ; /* try to free the page below */
325 * If the page is dirty, only perform writeback if that write
326 * will be non-blocking. To prevent this allocation from being
327 * stalled by pagecache activity. But note that there may be
328 * stalls if we need to run get_block(). We could test
329 * PagePrivate for that.
331 * If this process is currently in generic_file_write() against
332 * this page's queue, we can perform writeback even if that
335 * If the page is swapcache, write it back even if that would
336 * block, for some throttling. This happens by accident, because
337 * swap_backing_dev_info is bust: it doesn't reflect the
338 * congestion state of the swapdevs. Easy to fix, if needed.
339 * See swapfile.c:page_queue_congested().
341 if (PageDirty(page)) {
344 if (!is_page_cache_freeable(page))
348 if (mapping->a_ops->writepage == NULL)
349 goto activate_locked;
352 if (!may_write_to_queue(mapping->backing_dev_info))
354 if (laptop_mode && !do_writepage)
356 if (clear_page_dirty_for_io(page)) {
358 struct writeback_control wbc = {
359 .sync_mode = WB_SYNC_NONE,
360 .nr_to_write = SWAP_CLUSTER_MAX,
365 SetPageReclaim(page);
366 res = mapping->a_ops->writepage(page, &wbc);
368 handle_write_error(mapping, page, res);
369 if (res == WRITEPAGE_ACTIVATE) {
370 ClearPageReclaim(page);
371 goto activate_locked;
373 if (!PageWriteback(page)) {
374 /* synchronous write or broken a_ops? */
375 ClearPageReclaim(page);
382 * If the page has buffers, try to free the buffer mappings
383 * associated with this page. If we succeed we try to free
386 * We do this even if the page is PageDirty().
387 * try_to_release_page() does not perform I/O, but it is
388 * possible for a page to have PageDirty set, but it is actually
389 * clean (all its buffers are clean). This happens if the
390 * buffers were written out directly, with submit_bh(). ext3
391 * will do this, as well as the blockdev mapping.
392 * try_to_release_page() will discover that cleanness and will
393 * drop the buffers and mark the page clean - it can be freed.
395 * Rarely, pages can have buffers and no ->mapping. These are
396 * the pages which were not successfully invalidated in
397 * truncate_complete_page(). We try to drop those buffers here
398 * and if that worked, and the page is no longer mapped into
399 * process address space (page_count == 0) it can be freed.
400 * Otherwise, leave the page on the LRU so it is swappable.
402 if (PagePrivate(page)) {
403 if (!try_to_release_page(page, gfp_mask))
404 goto activate_locked;
405 if (!mapping && page_count(page) == 1)
410 goto keep_locked; /* truncate got there first */
412 spin_lock_irq(&mapping->tree_lock);
415 * The non-racy check for busy page. It is critical to check
416 * PageDirty _after_ making sure that the page is freeable and
417 * not in use by anybody. (pagecache + us == 2)
419 if (page_count(page) != 2 || PageDirty(page)) {
420 spin_unlock_irq(&mapping->tree_lock);
425 if (PageSwapCache(page)) {
426 swp_entry_t swap = { .val = page->private };
427 __delete_from_swap_cache(page);
428 spin_unlock_irq(&mapping->tree_lock);
430 __put_page(page); /* The pagecache ref */
433 #endif /* CONFIG_SWAP */
435 __remove_from_page_cache(page);
436 spin_unlock_irq(&mapping->tree_lock);
442 if (!pagevec_add(&freed_pvec, page))
443 __pagevec_release_nonlru(&freed_pvec);
452 list_add(&page->lru, &ret_pages);
453 BUG_ON(PageLRU(page));
455 list_splice(&ret_pages, page_list);
456 if (pagevec_count(&freed_pvec))
457 __pagevec_release_nonlru(&freed_pvec);
458 mod_page_state(pgactivate, pgactivate);
463 * zone->lru_lock is heavily contented. We relieve it by quickly privatising
464 * a batch of pages and working on them outside the lock. Any pages which were
465 * not freed will be added back to the LRU.
467 * shrink_cache() is passed the number of pages to scan and returns the number
468 * of pages which were reclaimed.
470 * For pagecache intensive workloads, the first loop here is the hottest spot
471 * in the kernel (apart from the copy_*_user functions).
474 shrink_cache(struct zone *zone, unsigned int gfp_mask,
475 int max_scan, int *total_scanned, int do_writepage)
477 LIST_HEAD(page_list);
481 pagevec_init(&pvec, 1);
484 spin_lock_irq(&zone->lru_lock);
485 while (max_scan > 0) {
491 while (nr_scan++ < SWAP_CLUSTER_MAX &&
492 !list_empty(&zone->inactive_list)) {
493 page = lru_to_page(&zone->inactive_list);
495 prefetchw_prev_lru_page(page,
496 &zone->inactive_list, flags);
498 if (!TestClearPageLRU(page))
500 list_del(&page->lru);
501 if (page_count(page) == 0) {
502 /* It is currently in pagevec_release() */
504 list_add(&page->lru, &zone->inactive_list);
507 list_add(&page->lru, &page_list);
508 page_cache_get(page);
511 zone->nr_inactive -= nr_taken;
512 zone->pages_scanned += nr_taken;
513 spin_unlock_irq(&zone->lru_lock);
519 if (current_is_kswapd())
520 mod_page_state_zone(zone, pgscan_kswapd, nr_scan);
522 mod_page_state_zone(zone, pgscan_direct, nr_scan);
523 nr_freed = shrink_list(&page_list, gfp_mask,
524 total_scanned, do_writepage);
525 *total_scanned += nr_taken;
526 if (current_is_kswapd())
527 mod_page_state(kswapd_steal, nr_freed);
528 mod_page_state_zone(zone, pgsteal, nr_freed);
531 if (nr_freed <= 0 && list_empty(&page_list))
534 spin_lock_irq(&zone->lru_lock);
536 * Put back any unfreeable pages.
538 while (!list_empty(&page_list)) {
539 page = lru_to_page(&page_list);
540 if (TestSetPageLRU(page))
542 list_del(&page->lru);
543 if (PageActive(page))
544 add_page_to_active_list(zone, page);
546 add_page_to_inactive_list(zone, page);
547 if (!pagevec_add(&pvec, page)) {
548 spin_unlock_irq(&zone->lru_lock);
549 __pagevec_release(&pvec);
550 spin_lock_irq(&zone->lru_lock);
554 spin_unlock_irq(&zone->lru_lock);
556 pagevec_release(&pvec);
561 * This moves pages from the active list to the inactive list.
563 * We move them the other way if the page is referenced by one or more
564 * processes, from rmap.
566 * If the pages are mostly unmapped, the processing is fast and it is
567 * appropriate to hold zone->lru_lock across the whole operation. But if
568 * the pages are mapped, the processing is slow (page_referenced()) so we
569 * should drop zone->lru_lock around each page. It's impossible to balance
570 * this, so instead we remove the pages from the LRU while processing them.
571 * It is safe to rely on PG_active against the non-LRU pages in here because
572 * nobody will play with that bit on a non-LRU page.
574 * The downside is that we have to touch page->count against each page.
575 * But we had to alter page->flags anyway.
578 refill_inactive_zone(struct zone *zone, const int nr_pages_in,
579 struct page_state *ps)
582 int pgdeactivate = 0;
583 int nr_pages = nr_pages_in;
584 LIST_HEAD(l_hold); /* The pages which were snipped off */
585 LIST_HEAD(l_inactive); /* Pages to go onto the inactive_list */
586 LIST_HEAD(l_active); /* Pages to go onto the active_list */
589 int reclaim_mapped = 0;
596 spin_lock_irq(&zone->lru_lock);
597 while (nr_pages && !list_empty(&zone->active_list)) {
598 page = lru_to_page(&zone->active_list);
599 prefetchw_prev_lru_page(page, &zone->active_list, flags);
600 if (!TestClearPageLRU(page))
602 list_del(&page->lru);
603 if (page_count(page) == 0) {
604 /* It is currently in pagevec_release() */
606 list_add(&page->lru, &zone->active_list);
608 page_cache_get(page);
609 list_add(&page->lru, &l_hold);
614 zone->nr_active -= pgmoved;
615 spin_unlock_irq(&zone->lru_lock);
618 * `distress' is a measure of how much trouble we're having reclaiming
619 * pages. 0 -> no problems. 100 -> great trouble.
621 distress = 100 >> zone->prev_priority;
624 * The point of this algorithm is to decide when to start reclaiming
625 * mapped memory instead of just pagecache. Work out how much memory
628 mapped_ratio = (ps->nr_mapped * 100) / total_memory;
631 * Now decide how much we really want to unmap some pages. The mapped
632 * ratio is downgraded - just because there's a lot of mapped memory
633 * doesn't necessarily mean that page reclaim isn't succeeding.
635 * The distress ratio is important - we don't want to start going oom.
637 * A 100% value of vm_swappiness overrides this algorithm altogether.
639 swap_tendency = mapped_ratio / 2 + distress + vm_swappiness;
642 * Now use this metric to decide whether to start moving mapped memory
643 * onto the inactive list.
645 if (swap_tendency >= 100)
648 while (!list_empty(&l_hold)) {
649 page = lru_to_page(&l_hold);
650 list_del(&page->lru);
651 if (page_mapped(page)) {
652 if (!reclaim_mapped) {
653 list_add(&page->lru, &l_active);
657 if (page_referenced(page)) {
659 list_add(&page->lru, &l_active);
665 * FIXME: need to consider page_count(page) here if/when we
666 * reap orphaned pages via the LRU (Daniel's locking stuff)
668 if (total_swap_pages == 0 && PageAnon(page)) {
669 list_add(&page->lru, &l_active);
672 list_add(&page->lru, &l_inactive);
675 pagevec_init(&pvec, 1);
677 spin_lock_irq(&zone->lru_lock);
678 while (!list_empty(&l_inactive)) {
679 page = lru_to_page(&l_inactive);
680 prefetchw_prev_lru_page(page, &l_inactive, flags);
681 if (TestSetPageLRU(page))
683 if (!TestClearPageActive(page))
685 list_move(&page->lru, &zone->inactive_list);
687 if (!pagevec_add(&pvec, page)) {
688 zone->nr_inactive += pgmoved;
689 spin_unlock_irq(&zone->lru_lock);
690 pgdeactivate += pgmoved;
692 if (buffer_heads_over_limit)
693 pagevec_strip(&pvec);
694 __pagevec_release(&pvec);
695 spin_lock_irq(&zone->lru_lock);
698 zone->nr_inactive += pgmoved;
699 pgdeactivate += pgmoved;
700 if (buffer_heads_over_limit) {
701 spin_unlock_irq(&zone->lru_lock);
702 pagevec_strip(&pvec);
703 spin_lock_irq(&zone->lru_lock);
707 while (!list_empty(&l_active)) {
708 page = lru_to_page(&l_active);
709 prefetchw_prev_lru_page(page, &l_active, flags);
710 if (TestSetPageLRU(page))
712 BUG_ON(!PageActive(page));
713 list_move(&page->lru, &zone->active_list);
715 if (!pagevec_add(&pvec, page)) {
716 zone->nr_active += pgmoved;
718 spin_unlock_irq(&zone->lru_lock);
719 __pagevec_release(&pvec);
720 spin_lock_irq(&zone->lru_lock);
723 zone->nr_active += pgmoved;
724 spin_unlock_irq(&zone->lru_lock);
725 pagevec_release(&pvec);
727 mod_page_state_zone(zone, pgrefill, nr_pages_in - nr_pages);
728 mod_page_state(pgdeactivate, pgdeactivate);
732 * Scan `nr_pages' from this zone. Returns the number of reclaimed pages.
733 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
736 shrink_zone(struct zone *zone, int max_scan, unsigned int gfp_mask,
737 int *total_scanned, struct page_state *ps, int do_writepage)
743 * Try to keep the active list 2/3 of the size of the cache. And
744 * make sure that refill_inactive is given a decent number of pages.
746 * The "ratio+1" here is important. With pagecache-intensive workloads
747 * the inactive list is huge, and `ratio' evaluates to zero all the
748 * time. Which pins the active list memory. So we add one to `ratio'
749 * just to make sure that the kernel will slowly sift through the
752 ratio = (unsigned long)SWAP_CLUSTER_MAX * zone->nr_active /
753 ((zone->nr_inactive | 1) * 2);
755 atomic_add(ratio+1, &zone->nr_scan_active);
756 count = atomic_read(&zone->nr_scan_active);
757 if (count >= SWAP_CLUSTER_MAX) {
758 atomic_set(&zone->nr_scan_active, 0);
759 refill_inactive_zone(zone, count, ps);
762 atomic_add(max_scan, &zone->nr_scan_inactive);
763 count = atomic_read(&zone->nr_scan_inactive);
764 if (count >= SWAP_CLUSTER_MAX) {
765 atomic_set(&zone->nr_scan_inactive, 0);
766 return shrink_cache(zone, gfp_mask, count,
767 total_scanned, do_writepage);
773 * This is the direct reclaim path, for page-allocating processes. We only
774 * try to reclaim pages from zones which will satisfy the caller's allocation
777 * We reclaim from a zone even if that zone is over pages_high. Because:
778 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
780 * b) The zones may be over pages_high but they must go *over* pages_high to
781 * satisfy the `incremental min' zone defense algorithm.
783 * Returns the number of reclaimed pages.
785 * If a zone is deemed to be full of pinned pages then just give it a light
786 * scan then give up on it.
789 shrink_caches(struct zone **zones, int priority, int *total_scanned,
790 int gfp_mask, struct page_state *ps, int do_writepage)
795 for (i = 0; zones[i] != NULL; i++) {
796 struct zone *zone = zones[i];
799 if (zone->free_pages < zone->pages_high)
800 zone->temp_priority = priority;
802 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
803 continue; /* Let kswapd poll it */
805 max_scan = zone->nr_inactive >> priority;
806 ret += shrink_zone(zone, max_scan, gfp_mask,
807 total_scanned, ps, do_writepage);
813 * This is the main entry point to direct page reclaim.
815 * If a full scan of the inactive list fails to free enough memory then we
816 * are "out of memory" and something needs to be killed.
818 * If the caller is !__GFP_FS then the probability of a failure is reasonably
819 * high - the zone may be full of dirty or under-writeback pages, which this
820 * caller can't do much about. So for !__GFP_FS callers, we just perform a
821 * small LRU walk and if that didn't work out, fail the allocation back to the
822 * caller. GFP_NOFS allocators need to know how to deal with it. Kicking
823 * bdflush, waiting and retrying will work.
825 * This is a fairly lame algorithm - it can result in excessive CPU burning and
826 * excessive rotation of the inactive list, which is _supposed_ to be an LRU,
829 int try_to_free_pages(struct zone **zones,
830 unsigned int gfp_mask, unsigned int order)
834 int nr_reclaimed = 0;
835 struct reclaim_state *reclaim_state = current->reclaim_state;
837 unsigned long total_scanned = 0;
838 int do_writepage = 0;
840 inc_page_state(allocstall);
842 for (i = 0; zones[i] != 0; i++)
843 zones[i]->temp_priority = DEF_PRIORITY;
845 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
847 struct page_state ps;
850 nr_reclaimed += shrink_caches(zones, priority, &scanned,
851 gfp_mask, &ps, do_writepage);
852 shrink_slab(scanned, gfp_mask);
854 nr_reclaimed += reclaim_state->reclaimed_slab;
855 reclaim_state->reclaimed_slab = 0;
857 if (nr_reclaimed >= SWAP_CLUSTER_MAX) {
861 if (!(gfp_mask & __GFP_FS))
862 break; /* Let the caller handle it */
864 * Try to write back as many pages as we just scanned. This
865 * tends to cause slow streaming writers to write data to the
866 * disk smoothly, at the dirtying rate, which is nice. But
867 * that's undesirable in laptop mode, where we *want* lumpy
868 * writeout. So in laptop mode, write out the whole world.
870 total_scanned += scanned;
871 if (total_scanned > SWAP_CLUSTER_MAX + SWAP_CLUSTER_MAX/2) {
872 wakeup_bdflush(laptop_mode ? 0 : total_scanned);
876 /* Take a nap, wait for some writeback to complete */
877 if (scanned && priority < DEF_PRIORITY - 2)
878 blk_congestion_wait(WRITE, HZ/10);
880 if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY))
883 for (i = 0; zones[i] != 0; i++)
884 zones[i]->prev_priority = zones[i]->temp_priority;
889 * For kswapd, balance_pgdat() will work across all this node's zones until
890 * they are all at pages_high.
892 * If `nr_pages' is non-zero then it is the number of pages which are to be
893 * reclaimed, regardless of the zone occupancies. This is a software suspend
896 * Returns the number of pages which were actually freed.
898 * There is special handling here for zones which are full of pinned pages.
899 * This can happen if the pages are all mlocked, or if they are all used by
900 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
901 * What we do is to detect the case where all pages in the zone have been
902 * scanned twice and there has been zero successful reclaim. Mark the zone as
903 * dead and from now on, only perform a short scan. Basically we're polling
904 * the zone for when the problem goes away.
906 * kswapd scans the zones in the highmem->normal->dma direction. It skips
907 * zones which have free_pages > pages_high, but once a zone is found to have
908 * free_pages <= pages_high, we scan that zone and the lower zones regardless
909 * of the number of free pages in the lower zones. This interoperates with
910 * the page allocator fallback scheme to ensure that aging of pages is balanced
913 static int balance_pgdat(pg_data_t *pgdat, int nr_pages, struct page_state *ps)
915 int to_free = nr_pages;
918 struct reclaim_state *reclaim_state = current->reclaim_state;
919 unsigned long total_scanned = 0;
920 unsigned long total_reclaimed = 0;
921 int do_writepage = 0;
923 inc_page_state(pageoutrun);
925 for (i = 0; i < pgdat->nr_zones; i++) {
926 struct zone *zone = pgdat->node_zones + i;
928 zone->temp_priority = DEF_PRIORITY;
931 for (priority = DEF_PRIORITY; priority; priority--) {
932 int all_zones_ok = 1;
933 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
938 * Scan in the highmem->dma direction for the highest
939 * zone which needs scanning
941 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
942 struct zone *zone = pgdat->node_zones + i;
944 if (zone->all_unreclaimable &&
945 priority != DEF_PRIORITY)
948 if (zone->free_pages <= zone->pages_high) {
955 end_zone = pgdat->nr_zones - 1;
959 * Now scan the zone in the dma->highmem direction, stopping
960 * at the last zone which needs scanning.
962 * We do this because the page allocator works in the opposite
963 * direction. This prevents the page allocator from allocating
964 * pages behind kswapd's direction of progress, which would
965 * cause too much scanning of the lower zones.
967 for (i = 0; i <= end_zone; i++) {
968 struct zone *zone = pgdat->node_zones + i;
973 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
976 if (nr_pages == 0) { /* Not software suspend */
977 if (zone->free_pages <= zone->pages_high)
980 zone->temp_priority = priority;
981 max_scan = zone->nr_inactive >> priority;
982 reclaimed = shrink_zone(zone, max_scan, GFP_KERNEL,
983 &scanned, ps, do_writepage);
984 total_scanned += scanned;
985 reclaim_state->reclaimed_slab = 0;
986 shrink_slab(scanned, GFP_KERNEL);
987 reclaimed += reclaim_state->reclaimed_slab;
988 total_reclaimed += reclaimed;
989 to_free -= reclaimed;
990 if (zone->all_unreclaimable)
992 if (zone->pages_scanned > zone->present_pages * 2)
993 zone->all_unreclaimable = 1;
995 * If we've done a decent amount of scanning and
996 * the reclaim ratio is low, start doing writepage
997 * even in laptop mode
999 if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
1000 total_scanned > total_reclaimed+total_reclaimed/2)
1003 if (nr_pages && to_free > 0)
1004 continue; /* swsusp: need to do more work */
1006 break; /* kswapd: all done */
1008 * OK, kswapd is getting into trouble. Take a nap, then take
1009 * another pass across the zones.
1011 if (total_scanned && priority < DEF_PRIORITY - 2)
1012 blk_congestion_wait(WRITE, HZ/10);
1015 for (i = 0; i < pgdat->nr_zones; i++) {
1016 struct zone *zone = pgdat->node_zones + i;
1018 zone->prev_priority = zone->temp_priority;
1020 return total_reclaimed;
1024 * The background pageout daemon, started as a kernel thread
1025 * from the init process.
1027 * This basically trickles out pages so that we have _some_
1028 * free memory available even if there is no other activity
1029 * that frees anything up. This is needed for things like routing
1030 * etc, where we otherwise might have all activity going on in
1031 * asynchronous contexts that cannot page things out.
1033 * If there are applications that are active memory-allocators
1034 * (most normal use), this basically shouldn't matter.
1038 pg_data_t *pgdat = (pg_data_t*)p;
1039 struct task_struct *tsk = current;
1041 struct reclaim_state reclaim_state = {
1042 .reclaimed_slab = 0,
1046 daemonize("kswapd%d", pgdat->node_id);
1047 cpumask = node_to_cpumask(pgdat->node_id);
1048 if (!cpus_empty(cpumask))
1049 set_cpus_allowed(tsk, cpumask);
1050 current->reclaim_state = &reclaim_state;
1053 * Tell the memory management that we're a "memory allocator",
1054 * and that if we need more memory we should get access to it
1055 * regardless (see "__alloc_pages()"). "kswapd" should
1056 * never get caught in the normal page freeing logic.
1058 * (Kswapd normally doesn't need memory anyway, but sometimes
1059 * you need a small amount of memory in order to be able to
1060 * page out something else, and this flag essentially protects
1061 * us from recursively trying to free more memory as we're
1062 * trying to free the first piece of memory in the first place).
1064 tsk->flags |= PF_MEMALLOC|PF_KSWAPD;
1067 struct page_state ps;
1069 if (current->flags & PF_FREEZE)
1070 refrigerator(PF_FREEZE);
1071 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
1073 finish_wait(&pgdat->kswapd_wait, &wait);
1074 get_page_state(&ps);
1075 balance_pgdat(pgdat, 0, &ps);
1080 * A zone is low on free memory, so wake its kswapd task to service it.
1082 void wakeup_kswapd(struct zone *zone)
1084 if (zone->free_pages > zone->pages_low)
1086 if (!waitqueue_active(&zone->zone_pgdat->kswapd_wait))
1088 wake_up_interruptible(&zone->zone_pgdat->kswapd_wait);
1093 * Try to free `nr_pages' of memory, system-wide. Returns the number of freed
1096 int shrink_all_memory(int nr_pages)
1099 int nr_to_free = nr_pages;
1101 struct reclaim_state reclaim_state = {
1102 .reclaimed_slab = 0,
1105 current->reclaim_state = &reclaim_state;
1106 for_each_pgdat(pgdat) {
1108 struct page_state ps;
1110 get_page_state(&ps);
1111 freed = balance_pgdat(pgdat, nr_to_free, &ps);
1113 nr_to_free -= freed;
1114 if (nr_to_free <= 0)
1117 current->reclaim_state = NULL;
1122 #ifdef CONFIG_HOTPLUG_CPU
1123 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1124 not required for correctness. So if the last cpu in a node goes
1125 away, we get changed to run anywhere: as the first one comes back,
1126 restore their cpu bindings. */
1127 static int __devinit cpu_callback(struct notifier_block *nfb,
1128 unsigned long action,
1134 if (action == CPU_ONLINE) {
1135 for_each_pgdat(pgdat) {
1136 mask = node_to_cpumask(pgdat->node_id);
1137 if (any_online_cpu(mask) != NR_CPUS)
1138 /* One of our CPUs online: restore mask */
1139 set_cpus_allowed(pgdat->kswapd, mask);
1144 #endif /* CONFIG_HOTPLUG_CPU */
1146 static int __init kswapd_init(void)
1150 for_each_pgdat(pgdat)
1152 = find_task_by_pid(kernel_thread(kswapd, pgdat, CLONE_KERNEL));
1153 total_memory = nr_free_pagecache_pages();
1154 hotcpu_notifier(cpu_callback, 0);
1158 module_init(kswapd_init)