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>
35 #include <linux/rwsem.h>
37 #include <asm/tlbflush.h>
38 #include <asm/div64.h>
40 #include <linux/swapops.h>
42 /* possible outcome of pageout() */
44 /* failed to write page out, page is locked */
46 /* move page to the active list, page is locked */
48 /* page has been sent to the disk successfully, page is unlocked */
50 /* page is clean and locked */
55 /* Ask refill_inactive_zone, or shrink_cache to scan this many pages */
56 unsigned long nr_to_scan;
58 /* Incremented by the number of inactive pages that were scanned */
59 unsigned long nr_scanned;
61 /* Incremented by the number of pages reclaimed */
62 unsigned long nr_reclaimed;
64 unsigned long nr_mapped; /* From page_state */
66 /* How many pages shrink_cache() should reclaim */
69 /* Ask shrink_caches, or shrink_zone to scan at this priority */
70 unsigned int priority;
72 /* This context's GFP mask */
73 unsigned int gfp_mask;
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 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
91 #ifdef ARCH_HAS_PREFETCH
92 #define prefetch_prev_lru_page(_page, _base, _field) \
94 if ((_page)->lru.prev != _base) { \
97 prev = lru_to_page(&(_page->lru)); \
98 prefetch(&prev->_field); \
102 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
105 #ifdef ARCH_HAS_PREFETCHW
106 #define prefetchw_prev_lru_page(_page, _base, _field) \
108 if ((_page)->lru.prev != _base) { \
111 prev = lru_to_page(&(_page->lru)); \
112 prefetchw(&prev->_field); \
116 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
120 * From 0 .. 100. Higher means more swappy.
122 int vm_swappiness = 60;
123 static long total_memory;
125 static LIST_HEAD(shrinker_list);
126 static DECLARE_RWSEM(shrinker_rwsem);
129 * Add a shrinker callback to be called from the vm
131 struct shrinker *set_shrinker(int seeks, shrinker_t theshrinker)
133 struct shrinker *shrinker;
135 shrinker = kmalloc(sizeof(*shrinker), GFP_KERNEL);
137 shrinker->shrinker = theshrinker;
138 shrinker->seeks = seeks;
140 down_write(&shrinker_rwsem);
141 list_add(&shrinker->list, &shrinker_list);
142 up_write(&shrinker_rwsem);
146 EXPORT_SYMBOL(set_shrinker);
151 void remove_shrinker(struct shrinker *shrinker)
153 down_write(&shrinker_rwsem);
154 list_del(&shrinker->list);
155 up_write(&shrinker_rwsem);
158 EXPORT_SYMBOL(remove_shrinker);
160 #define SHRINK_BATCH 128
162 * Call the shrink functions to age shrinkable caches
164 * Here we assume it costs one seek to replace a lru page and that it also
165 * takes a seek to recreate a cache object. With this in mind we age equal
166 * percentages of the lru and ageable caches. This should balance the seeks
167 * generated by these structures.
169 * If the vm encounted mapped pages on the LRU it increase the pressure on
170 * slab to avoid swapping.
172 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
174 * `lru_pages' represents the number of on-LRU pages in all the zones which
175 * are eligible for the caller's allocation attempt. It is used for balancing
176 * slab reclaim versus page reclaim.
178 static int shrink_slab(unsigned long scanned, unsigned int gfp_mask,
179 unsigned long lru_pages)
181 struct shrinker *shrinker;
186 if (!down_read_trylock(&shrinker_rwsem))
189 list_for_each_entry(shrinker, &shrinker_list, list) {
190 unsigned long long delta;
191 unsigned long total_scan;
193 delta = (4 * scanned) / shrinker->seeks;
194 delta *= (*shrinker->shrinker)(0, gfp_mask);
195 do_div(delta, lru_pages + 1);
196 shrinker->nr += delta;
197 if (shrinker->nr < 0)
198 shrinker->nr = LONG_MAX; /* It wrapped! */
200 total_scan = shrinker->nr;
203 while (total_scan >= SHRINK_BATCH) {
204 long this_scan = SHRINK_BATCH;
207 shrink_ret = (*shrinker->shrinker)(this_scan, gfp_mask);
208 if (shrink_ret == -1)
210 mod_page_state(slabs_scanned, this_scan);
211 total_scan -= this_scan;
216 shrinker->nr += total_scan;
218 up_read(&shrinker_rwsem);
222 /* Must be called with page's rmap lock held. */
223 static inline int page_mapping_inuse(struct page *page)
225 struct address_space *mapping;
227 /* Page is in somebody's page tables. */
228 if (page_mapped(page))
231 /* Be more reluctant to reclaim swapcache than pagecache */
232 if (PageSwapCache(page))
235 mapping = page_mapping(page);
239 /* File is mmap'd by somebody? */
240 return mapping_mapped(mapping);
243 static inline int is_page_cache_freeable(struct page *page)
245 return page_count(page) - !!PagePrivate(page) == 2;
248 static int may_write_to_queue(struct backing_dev_info *bdi)
250 if (current_is_kswapd())
252 if (current_is_pdflush()) /* This is unlikely, but why not... */
254 if (!bdi_write_congested(bdi))
256 if (bdi == current->backing_dev_info)
262 * We detected a synchronous write error writing a page out. Probably
263 * -ENOSPC. We need to propagate that into the address_space for a subsequent
264 * fsync(), msync() or close().
266 * The tricky part is that after writepage we cannot touch the mapping: nothing
267 * prevents it from being freed up. But we have a ref on the page and once
268 * that page is locked, the mapping is pinned.
270 * We're allowed to run sleeping lock_page() here because we know the caller has
273 static void handle_write_error(struct address_space *mapping,
274 struct page *page, int error)
277 if (page_mapping(page) == mapping) {
278 if (error == -ENOSPC)
279 set_bit(AS_ENOSPC, &mapping->flags);
281 set_bit(AS_EIO, &mapping->flags);
287 * pageout is called by shrink_list() for each dirty page. Calls ->writepage().
289 static pageout_t pageout(struct page *page, struct address_space *mapping)
292 * If the page is dirty, only perform writeback if that write
293 * will be non-blocking. To prevent this allocation from being
294 * stalled by pagecache activity. But note that there may be
295 * stalls if we need to run get_block(). We could test
296 * PagePrivate for that.
298 * If this process is currently in generic_file_write() against
299 * this page's queue, we can perform writeback even if that
302 * If the page is swapcache, write it back even if that would
303 * block, for some throttling. This happens by accident, because
304 * swap_backing_dev_info is bust: it doesn't reflect the
305 * congestion state of the swapdevs. Easy to fix, if needed.
306 * See swapfile.c:page_queue_congested().
308 if (!is_page_cache_freeable(page))
312 if (mapping->a_ops->writepage == NULL)
313 return PAGE_ACTIVATE;
314 if (!may_write_to_queue(mapping->backing_dev_info))
317 if (clear_page_dirty_for_io(page)) {
319 struct writeback_control wbc = {
320 .sync_mode = WB_SYNC_NONE,
321 .nr_to_write = SWAP_CLUSTER_MAX,
326 SetPageReclaim(page);
327 res = mapping->a_ops->writepage(page, &wbc);
329 handle_write_error(mapping, page, res);
330 if (res == WRITEPAGE_ACTIVATE) {
331 ClearPageReclaim(page);
332 return PAGE_ACTIVATE;
334 if (!PageWriteback(page)) {
335 /* synchronous write or broken a_ops? */
336 ClearPageReclaim(page);
346 * shrink_list adds the number of reclaimed pages to sc->nr_reclaimed
348 static int shrink_list(struct list_head *page_list, struct scan_control *sc)
350 LIST_HEAD(ret_pages);
351 struct pagevec freed_pvec;
357 pagevec_init(&freed_pvec, 1);
358 while (!list_empty(page_list)) {
359 struct address_space *mapping;
364 page = lru_to_page(page_list);
365 list_del(&page->lru);
367 if (TestSetPageLocked(page))
370 BUG_ON(PageActive(page));
372 if (PageWriteback(page))
376 /* Double the slab pressure for mapped and swapcache pages */
377 if (page_mapped(page) || PageSwapCache(page))
381 referenced = page_referenced(page);
382 if (referenced && page_mapping_inuse(page)) {
383 /* In active use or really unfreeable. Activate it. */
384 page_map_unlock(page);
385 goto activate_locked;
390 * Anonymous process memory has backing store?
391 * Try to allocate it some swap space here.
393 * XXX: implement swap clustering ?
395 if (PageAnon(page) && !PageSwapCache(page)) {
396 page_map_unlock(page);
397 if (!add_to_swap(page))
398 goto activate_locked;
401 #endif /* CONFIG_SWAP */
403 mapping = page_mapping(page);
404 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
405 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
408 * The page is mapped into the page tables of one or more
409 * processes. Try to unmap it here.
411 if (page_mapped(page) && mapping) {
412 switch (try_to_unmap(page)) {
414 page_map_unlock(page);
415 goto activate_locked;
417 page_map_unlock(page);
420 ; /* try to free the page below */
423 page_map_unlock(page);
425 if (PageDirty(page)) {
430 if (laptop_mode && !sc->may_writepage)
433 /* Page is dirty, try to write it out here */
434 switch(pageout(page, mapping)) {
438 goto activate_locked;
440 if (PageWriteback(page) || PageDirty(page))
443 * A synchronous write - probably a ramdisk. Go
444 * ahead and try to reclaim the page.
446 if (TestSetPageLocked(page))
448 if (PageDirty(page) || PageWriteback(page))
450 mapping = page_mapping(page);
452 ; /* try to free the page below */
457 * If the page has buffers, try to free the buffer mappings
458 * associated with this page. If we succeed we try to free
461 * We do this even if the page is PageDirty().
462 * try_to_release_page() does not perform I/O, but it is
463 * possible for a page to have PageDirty set, but it is actually
464 * clean (all its buffers are clean). This happens if the
465 * buffers were written out directly, with submit_bh(). ext3
466 * will do this, as well as the blockdev mapping.
467 * try_to_release_page() will discover that cleanness and will
468 * drop the buffers and mark the page clean - it can be freed.
470 * Rarely, pages can have buffers and no ->mapping. These are
471 * the pages which were not successfully invalidated in
472 * truncate_complete_page(). We try to drop those buffers here
473 * and if that worked, and the page is no longer mapped into
474 * process address space (page_count == 1) it can be freed.
475 * Otherwise, leave the page on the LRU so it is swappable.
477 if (PagePrivate(page)) {
478 if (!try_to_release_page(page, sc->gfp_mask))
479 goto activate_locked;
481 * file system may manually remove page from the page
482 * cache in ->releasepage(). Check for this.
484 mapping = page_mapping(page);
485 if (!mapping && page_count(page) == 1)
490 goto keep_locked; /* truncate got there first */
492 write_lock_irq(&mapping->tree_lock);
495 * The non-racy check for busy page. It is critical to check
496 * PageDirty _after_ making sure that the page is freeable and
497 * not in use by anybody. (pagecache + us == 2)
499 if (page_count(page) != 2 || PageDirty(page)) {
500 write_unlock_irq(&mapping->tree_lock);
505 if (PageSwapCache(page)) {
506 swp_entry_t swap = { .val = page->private };
507 __delete_from_swap_cache(page);
508 write_unlock_irq(&mapping->tree_lock);
510 __put_page(page); /* The pagecache ref */
513 #endif /* CONFIG_SWAP */
515 __remove_from_page_cache(page);
516 write_unlock_irq(&mapping->tree_lock);
522 if (!pagevec_add(&freed_pvec, page))
523 __pagevec_release_nonlru(&freed_pvec);
532 list_add(&page->lru, &ret_pages);
533 BUG_ON(PageLRU(page));
535 list_splice(&ret_pages, page_list);
536 if (pagevec_count(&freed_pvec))
537 __pagevec_release_nonlru(&freed_pvec);
538 mod_page_state(pgactivate, pgactivate);
539 sc->nr_reclaimed += reclaimed;
544 * zone->lru_lock is heavily contented. We relieve it by quickly privatising
545 * a batch of pages and working on them outside the lock. Any pages which were
546 * not freed will be added back to the LRU.
548 * shrink_cache() adds the number of pages reclaimed to sc->nr_reclaimed
550 * For pagecache intensive workloads, the first loop here is the hottest spot
551 * in the kernel (apart from the copy_*_user functions).
553 static void shrink_cache(struct zone *zone, struct scan_control *sc)
555 LIST_HEAD(page_list);
557 int max_scan = sc->nr_to_scan;
559 pagevec_init(&pvec, 1);
562 spin_lock_irq(&zone->lru_lock);
563 while (max_scan > 0) {
569 while (nr_scan++ < SWAP_CLUSTER_MAX &&
570 !list_empty(&zone->inactive_list)) {
571 page = lru_to_page(&zone->inactive_list);
573 prefetchw_prev_lru_page(page,
574 &zone->inactive_list, flags);
576 if (!TestClearPageLRU(page))
578 list_del(&page->lru);
579 if (get_page_testone(page)) {
581 * It is being freed elsewhere
585 list_add(&page->lru, &zone->inactive_list);
588 list_add(&page->lru, &page_list);
591 zone->nr_inactive -= nr_taken;
592 zone->pages_scanned += nr_taken;
593 spin_unlock_irq(&zone->lru_lock);
599 if (current_is_kswapd())
600 mod_page_state_zone(zone, pgscan_kswapd, nr_scan);
602 mod_page_state_zone(zone, pgscan_direct, nr_scan);
603 nr_freed = shrink_list(&page_list, sc);
604 if (current_is_kswapd())
605 mod_page_state(kswapd_steal, nr_freed);
606 mod_page_state_zone(zone, pgsteal, nr_freed);
607 sc->nr_to_reclaim -= nr_freed;
609 spin_lock_irq(&zone->lru_lock);
611 * Put back any unfreeable pages.
613 while (!list_empty(&page_list)) {
614 page = lru_to_page(&page_list);
615 if (TestSetPageLRU(page))
617 list_del(&page->lru);
618 if (PageActive(page))
619 add_page_to_active_list(zone, page);
621 add_page_to_inactive_list(zone, page);
622 if (!pagevec_add(&pvec, page)) {
623 spin_unlock_irq(&zone->lru_lock);
624 __pagevec_release(&pvec);
625 spin_lock_irq(&zone->lru_lock);
629 spin_unlock_irq(&zone->lru_lock);
631 pagevec_release(&pvec);
635 * This moves pages from the active list to the inactive list.
637 * We move them the other way if the page is referenced by one or more
638 * processes, from rmap.
640 * If the pages are mostly unmapped, the processing is fast and it is
641 * appropriate to hold zone->lru_lock across the whole operation. But if
642 * the pages are mapped, the processing is slow (page_referenced()) so we
643 * should drop zone->lru_lock around each page. It's impossible to balance
644 * this, so instead we remove the pages from the LRU while processing them.
645 * It is safe to rely on PG_active against the non-LRU pages in here because
646 * nobody will play with that bit on a non-LRU page.
648 * The downside is that we have to touch page->_count against each page.
649 * But we had to alter page->flags anyway.
652 refill_inactive_zone(struct zone *zone, struct scan_control *sc)
655 int pgdeactivate = 0;
657 int nr_pages = sc->nr_to_scan;
658 LIST_HEAD(l_hold); /* The pages which were snipped off */
659 LIST_HEAD(l_inactive); /* Pages to go onto the inactive_list */
660 LIST_HEAD(l_active); /* Pages to go onto the active_list */
663 int reclaim_mapped = 0;
670 spin_lock_irq(&zone->lru_lock);
671 while (pgscanned < nr_pages && !list_empty(&zone->active_list)) {
672 page = lru_to_page(&zone->active_list);
673 prefetchw_prev_lru_page(page, &zone->active_list, flags);
674 if (!TestClearPageLRU(page))
676 list_del(&page->lru);
677 if (get_page_testone(page)) {
679 * It was already free! release_pages() or put_page()
680 * are about to remove it from the LRU and free it. So
681 * put the refcount back and put the page back on the
686 list_add(&page->lru, &zone->active_list);
688 list_add(&page->lru, &l_hold);
693 zone->nr_active -= pgmoved;
694 spin_unlock_irq(&zone->lru_lock);
697 * `distress' is a measure of how much trouble we're having reclaiming
698 * pages. 0 -> no problems. 100 -> great trouble.
700 distress = 100 >> zone->prev_priority;
703 * The point of this algorithm is to decide when to start reclaiming
704 * mapped memory instead of just pagecache. Work out how much memory
707 mapped_ratio = (sc->nr_mapped * 100) / total_memory;
710 * Now decide how much we really want to unmap some pages. The mapped
711 * ratio is downgraded - just because there's a lot of mapped memory
712 * doesn't necessarily mean that page reclaim isn't succeeding.
714 * The distress ratio is important - we don't want to start going oom.
716 * A 100% value of vm_swappiness overrides this algorithm altogether.
718 swap_tendency = mapped_ratio / 2 + distress + vm_swappiness;
721 * Now use this metric to decide whether to start moving mapped memory
722 * onto the inactive list.
724 if (swap_tendency >= 100)
727 while (!list_empty(&l_hold)) {
728 page = lru_to_page(&l_hold);
729 list_del(&page->lru);
730 if (page_mapped(page)) {
731 if (!reclaim_mapped) {
732 list_add(&page->lru, &l_active);
736 if (page_referenced(page)) {
737 page_map_unlock(page);
738 list_add(&page->lru, &l_active);
741 page_map_unlock(page);
744 * FIXME: need to consider page_count(page) here if/when we
745 * reap orphaned pages via the LRU (Daniel's locking stuff)
747 if (total_swap_pages == 0 && PageAnon(page)) {
748 list_add(&page->lru, &l_active);
751 list_add(&page->lru, &l_inactive);
754 pagevec_init(&pvec, 1);
756 spin_lock_irq(&zone->lru_lock);
757 while (!list_empty(&l_inactive)) {
758 page = lru_to_page(&l_inactive);
759 prefetchw_prev_lru_page(page, &l_inactive, flags);
760 if (TestSetPageLRU(page))
762 if (!TestClearPageActive(page))
764 list_move(&page->lru, &zone->inactive_list);
766 if (!pagevec_add(&pvec, page)) {
767 zone->nr_inactive += pgmoved;
768 spin_unlock_irq(&zone->lru_lock);
769 pgdeactivate += pgmoved;
771 if (buffer_heads_over_limit)
772 pagevec_strip(&pvec);
773 __pagevec_release(&pvec);
774 spin_lock_irq(&zone->lru_lock);
777 zone->nr_inactive += pgmoved;
778 pgdeactivate += pgmoved;
779 if (buffer_heads_over_limit) {
780 spin_unlock_irq(&zone->lru_lock);
781 pagevec_strip(&pvec);
782 spin_lock_irq(&zone->lru_lock);
786 while (!list_empty(&l_active)) {
787 page = lru_to_page(&l_active);
788 prefetchw_prev_lru_page(page, &l_active, flags);
789 if (TestSetPageLRU(page))
791 BUG_ON(!PageActive(page));
792 list_move(&page->lru, &zone->active_list);
794 if (!pagevec_add(&pvec, page)) {
795 zone->nr_active += pgmoved;
797 spin_unlock_irq(&zone->lru_lock);
798 __pagevec_release(&pvec);
799 spin_lock_irq(&zone->lru_lock);
802 zone->nr_active += pgmoved;
803 spin_unlock_irq(&zone->lru_lock);
804 pagevec_release(&pvec);
806 mod_page_state_zone(zone, pgrefill, pgscanned);
807 mod_page_state(pgdeactivate, pgdeactivate);
811 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
814 shrink_zone(struct zone *zone, struct scan_control *sc)
816 unsigned long nr_active;
817 unsigned long nr_inactive;
820 * Add one to `nr_to_scan' just to make sure that the kernel will
821 * slowly sift through the active list.
823 zone->nr_scan_active += (zone->nr_active >> sc->priority) + 1;
824 nr_active = zone->nr_scan_active;
825 if (nr_active >= SWAP_CLUSTER_MAX)
826 zone->nr_scan_active = 0;
830 zone->nr_scan_inactive += (zone->nr_inactive >> sc->priority) + 1;
831 nr_inactive = zone->nr_scan_inactive;
832 if (nr_inactive >= SWAP_CLUSTER_MAX)
833 zone->nr_scan_inactive = 0;
837 sc->nr_to_reclaim = SWAP_CLUSTER_MAX;
839 while (nr_active || nr_inactive) {
841 sc->nr_to_scan = min(nr_active,
842 (unsigned long)SWAP_CLUSTER_MAX);
843 nr_active -= sc->nr_to_scan;
844 refill_inactive_zone(zone, sc);
848 sc->nr_to_scan = min(nr_inactive,
849 (unsigned long)SWAP_CLUSTER_MAX);
850 nr_inactive -= sc->nr_to_scan;
851 shrink_cache(zone, sc);
852 if (sc->nr_to_reclaim <= 0)
859 * This is the direct reclaim path, for page-allocating processes. We only
860 * try to reclaim pages from zones which will satisfy the caller's allocation
863 * We reclaim from a zone even if that zone is over pages_high. Because:
864 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
866 * b) The zones may be over pages_high but they must go *over* pages_high to
867 * satisfy the `incremental min' zone defense algorithm.
869 * Returns the number of reclaimed pages.
871 * If a zone is deemed to be full of pinned pages then just give it a light
872 * scan then give up on it.
875 shrink_caches(struct zone **zones, struct scan_control *sc)
879 for (i = 0; zones[i] != NULL; i++) {
880 struct zone *zone = zones[i];
882 zone->temp_priority = sc->priority;
883 if (zone->prev_priority > sc->priority)
884 zone->prev_priority = sc->priority;
886 if (zone->all_unreclaimable && sc->priority != DEF_PRIORITY)
887 continue; /* Let kswapd poll it */
889 shrink_zone(zone, sc);
894 * This is the main entry point to direct page reclaim.
896 * If a full scan of the inactive list fails to free enough memory then we
897 * are "out of memory" and something needs to be killed.
899 * If the caller is !__GFP_FS then the probability of a failure is reasonably
900 * high - the zone may be full of dirty or under-writeback pages, which this
901 * caller can't do much about. We kick pdflush and take explicit naps in the
902 * hope that some of these pages can be written. But if the allocating task
903 * holds filesystem locks which prevent writeout this might not work, and the
904 * allocation attempt will fail.
906 int try_to_free_pages(struct zone **zones,
907 unsigned int gfp_mask, unsigned int order)
911 int total_scanned = 0, total_reclaimed = 0;
912 struct reclaim_state *reclaim_state = current->reclaim_state;
913 struct scan_control sc;
914 unsigned long lru_pages = 0;
917 sc.gfp_mask = gfp_mask;
918 sc.may_writepage = 0;
920 inc_page_state(allocstall);
922 for (i = 0; zones[i] != NULL; i++) {
923 struct zone *zone = zones[i];
925 zone->temp_priority = DEF_PRIORITY;
926 lru_pages += zone->nr_active + zone->nr_inactive;
929 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
930 sc.nr_mapped = read_page_state(nr_mapped);
933 sc.priority = priority;
934 shrink_caches(zones, &sc);
935 shrink_slab(sc.nr_scanned, gfp_mask, lru_pages);
937 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
938 reclaim_state->reclaimed_slab = 0;
940 if (sc.nr_reclaimed >= SWAP_CLUSTER_MAX) {
944 total_scanned += sc.nr_scanned;
945 total_reclaimed += sc.nr_reclaimed;
948 * Try to write back as many pages as we just scanned. This
949 * tends to cause slow streaming writers to write data to the
950 * disk smoothly, at the dirtying rate, which is nice. But
951 * that's undesirable in laptop mode, where we *want* lumpy
952 * writeout. So in laptop mode, write out the whole world.
954 if (total_scanned > SWAP_CLUSTER_MAX + SWAP_CLUSTER_MAX/2) {
955 wakeup_bdflush(laptop_mode ? 0 : total_scanned);
956 sc.may_writepage = 1;
959 /* Take a nap, wait for some writeback to complete */
960 if (sc.nr_scanned && priority < DEF_PRIORITY - 2)
961 blk_congestion_wait(WRITE, HZ/10);
963 if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY))
964 out_of_memory(gfp_mask);
966 for (i = 0; zones[i] != 0; i++)
967 zones[i]->prev_priority = zones[i]->temp_priority;
972 * For kswapd, balance_pgdat() will work across all this node's zones until
973 * they are all at pages_high.
975 * If `nr_pages' is non-zero then it is the number of pages which are to be
976 * reclaimed, regardless of the zone occupancies. This is a software suspend
979 * Returns the number of pages which were actually freed.
981 * There is special handling here for zones which are full of pinned pages.
982 * This can happen if the pages are all mlocked, or if they are all used by
983 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
984 * What we do is to detect the case where all pages in the zone have been
985 * scanned twice and there has been zero successful reclaim. Mark the zone as
986 * dead and from now on, only perform a short scan. Basically we're polling
987 * the zone for when the problem goes away.
989 * kswapd scans the zones in the highmem->normal->dma direction. It skips
990 * zones which have free_pages > pages_high, but once a zone is found to have
991 * free_pages <= pages_high, we scan that zone and the lower zones regardless
992 * of the number of free pages in the lower zones. This interoperates with
993 * the page allocator fallback scheme to ensure that aging of pages is balanced
996 static int balance_pgdat(pg_data_t *pgdat, int nr_pages)
998 int to_free = nr_pages;
1001 int total_scanned = 0, total_reclaimed = 0;
1002 struct reclaim_state *reclaim_state = current->reclaim_state;
1003 struct scan_control sc;
1005 sc.gfp_mask = GFP_KERNEL;
1006 sc.may_writepage = 0;
1007 sc.nr_mapped = read_page_state(nr_mapped);
1009 inc_page_state(pageoutrun);
1011 for (i = 0; i < pgdat->nr_zones; i++) {
1012 struct zone *zone = pgdat->node_zones + i;
1014 zone->temp_priority = DEF_PRIORITY;
1017 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1018 int all_zones_ok = 1;
1019 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
1020 unsigned long lru_pages = 0;
1022 if (nr_pages == 0) {
1024 * Scan in the highmem->dma direction for the highest
1025 * zone which needs scanning
1027 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
1028 struct zone *zone = pgdat->node_zones + i;
1030 if (zone->all_unreclaimable &&
1031 priority != DEF_PRIORITY)
1034 if (zone->free_pages <= zone->pages_high) {
1041 end_zone = pgdat->nr_zones - 1;
1044 for (i = 0; i <= end_zone; i++) {
1045 struct zone *zone = pgdat->node_zones + i;
1047 lru_pages += zone->nr_active + zone->nr_inactive;
1051 * Now scan the zone in the dma->highmem direction, stopping
1052 * at the last zone which needs scanning.
1054 * We do this because the page allocator works in the opposite
1055 * direction. This prevents the page allocator from allocating
1056 * pages behind kswapd's direction of progress, which would
1057 * cause too much scanning of the lower zones.
1059 for (i = 0; i <= end_zone; i++) {
1060 struct zone *zone = pgdat->node_zones + i;
1062 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1065 if (nr_pages == 0) { /* Not software suspend */
1066 if (zone->free_pages <= zone->pages_high)
1069 zone->temp_priority = priority;
1070 if (zone->prev_priority > priority)
1071 zone->prev_priority = priority;
1073 sc.nr_reclaimed = 0;
1074 sc.priority = priority;
1075 shrink_zone(zone, &sc);
1076 reclaim_state->reclaimed_slab = 0;
1077 shrink_slab(sc.nr_scanned, GFP_KERNEL, lru_pages);
1078 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
1079 total_reclaimed += sc.nr_reclaimed;
1080 if (zone->all_unreclaimable)
1082 if (zone->pages_scanned > zone->present_pages * 2)
1083 zone->all_unreclaimable = 1;
1085 * If we've done a decent amount of scanning and
1086 * the reclaim ratio is low, start doing writepage
1087 * even in laptop mode
1089 if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
1090 total_scanned > total_reclaimed+total_reclaimed/2)
1091 sc.may_writepage = 1;
1093 if (nr_pages && to_free > total_reclaimed)
1094 continue; /* swsusp: need to do more work */
1096 break; /* kswapd: all done */
1098 * OK, kswapd is getting into trouble. Take a nap, then take
1099 * another pass across the zones.
1101 if (total_scanned && priority < DEF_PRIORITY - 2)
1102 blk_congestion_wait(WRITE, HZ/10);
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 return total_reclaimed;
1114 * The background pageout daemon, started as a kernel thread
1115 * from the init process.
1117 * This basically trickles out pages so that we have _some_
1118 * free memory available even if there is no other activity
1119 * that frees anything up. This is needed for things like routing
1120 * etc, where we otherwise might have all activity going on in
1121 * asynchronous contexts that cannot page things out.
1123 * If there are applications that are active memory-allocators
1124 * (most normal use), this basically shouldn't matter.
1128 pg_data_t *pgdat = (pg_data_t*)p;
1129 struct task_struct *tsk = current;
1131 struct reclaim_state reclaim_state = {
1132 .reclaimed_slab = 0,
1136 daemonize("kswapd%d", pgdat->node_id);
1137 cpumask = node_to_cpumask(pgdat->node_id);
1138 if (!cpus_empty(cpumask))
1139 set_cpus_allowed(tsk, cpumask);
1140 current->reclaim_state = &reclaim_state;
1143 * Tell the memory management that we're a "memory allocator",
1144 * and that if we need more memory we should get access to it
1145 * regardless (see "__alloc_pages()"). "kswapd" should
1146 * never get caught in the normal page freeing logic.
1148 * (Kswapd normally doesn't need memory anyway, but sometimes
1149 * you need a small amount of memory in order to be able to
1150 * page out something else, and this flag essentially protects
1151 * us from recursively trying to free more memory as we're
1152 * trying to free the first piece of memory in the first place).
1154 tsk->flags |= PF_MEMALLOC|PF_KSWAPD;
1157 if (current->flags & PF_FREEZE)
1158 refrigerator(PF_FREEZE);
1159 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
1161 finish_wait(&pgdat->kswapd_wait, &wait);
1163 balance_pgdat(pgdat, 0);
1169 * A zone is low on free memory, so wake its kswapd task to service it.
1171 void wakeup_kswapd(struct zone *zone)
1173 if (zone->free_pages > zone->pages_low)
1175 if (!waitqueue_active(&zone->zone_pgdat->kswapd_wait))
1177 wake_up_interruptible(&zone->zone_pgdat->kswapd_wait);
1182 * Try to free `nr_pages' of memory, system-wide. Returns the number of freed
1185 int shrink_all_memory(int nr_pages)
1188 int nr_to_free = nr_pages;
1190 struct reclaim_state reclaim_state = {
1191 .reclaimed_slab = 0,
1194 current->reclaim_state = &reclaim_state;
1195 for_each_pgdat(pgdat) {
1197 freed = balance_pgdat(pgdat, nr_to_free);
1199 nr_to_free -= freed;
1200 if (nr_to_free <= 0)
1203 current->reclaim_state = NULL;
1208 #ifdef CONFIG_HOTPLUG_CPU
1209 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1210 not required for correctness. So if the last cpu in a node goes
1211 away, we get changed to run anywhere: as the first one comes back,
1212 restore their cpu bindings. */
1213 static int __devinit cpu_callback(struct notifier_block *nfb,
1214 unsigned long action,
1220 if (action == CPU_ONLINE) {
1221 for_each_pgdat(pgdat) {
1222 mask = node_to_cpumask(pgdat->node_id);
1223 if (any_online_cpu(mask) != NR_CPUS)
1224 /* One of our CPUs online: restore mask */
1225 set_cpus_allowed(pgdat->kswapd, mask);
1230 #endif /* CONFIG_HOTPLUG_CPU */
1232 static int __init kswapd_init(void)
1236 for_each_pgdat(pgdat)
1238 = find_task_by_pid(kernel_thread(kswapd, pgdat, CLONE_KERNEL));
1239 total_memory = nr_free_pagecache_pages();
1240 hotcpu_notifier(cpu_callback, 0);
1244 module_init(kswapd_init)