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/tlbflush.h>
37 #include <asm/div64.h>
39 #include <linux/swapops.h>
40 #include <linux/ckrm_mem.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;
75 /* Flag used by CKRM */
76 unsigned int ckrm_flags;
82 * The list of shrinker callbacks used by to apply pressure to
87 struct list_head list;
88 int seeks; /* seeks to recreate an obj */
89 long nr; /* objs pending delete */
94 void try_to_clip_inodes(void);
97 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
99 #ifdef ARCH_HAS_PREFETCH
100 #define prefetch_prev_lru_page(_page, _base, _field) \
102 if ((_page)->lru.prev != _base) { \
105 prev = lru_to_page(&(_page->lru)); \
106 prefetch(&prev->_field); \
110 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
113 #ifdef ARCH_HAS_PREFETCHW
114 #define prefetchw_prev_lru_page(_page, _base, _field) \
116 if ((_page)->lru.prev != _base) { \
119 prev = lru_to_page(&(_page->lru)); \
120 prefetchw(&prev->_field); \
124 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
128 * From 0 .. 100. Higher means more swappy.
130 int vm_swappiness = 60;
131 static long total_memory;
133 static LIST_HEAD(shrinker_list);
134 static DECLARE_MUTEX(shrinker_sem);
137 * Add a shrinker callback to be called from the vm
139 struct shrinker *set_shrinker(int seeks, shrinker_t theshrinker)
141 struct shrinker *shrinker;
143 shrinker = kmalloc(sizeof(*shrinker), GFP_KERNEL);
145 shrinker->shrinker = theshrinker;
146 shrinker->seeks = seeks;
149 list_add(&shrinker->list, &shrinker_list);
154 EXPORT_SYMBOL(set_shrinker);
159 void remove_shrinker(struct shrinker *shrinker)
162 list_del(&shrinker->list);
166 EXPORT_SYMBOL(remove_shrinker);
168 #define SHRINK_BATCH 128
170 * Call the shrink functions to age shrinkable caches
172 * Here we assume it costs one seek to replace a lru page and that it also
173 * takes a seek to recreate a cache object. With this in mind we age equal
174 * percentages of the lru and ageable caches. This should balance the seeks
175 * generated by these structures.
177 * If the vm encounted mapped pages on the LRU it increase the pressure on
178 * slab to avoid swapping.
180 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
182 * `lru_pages' represents the number of on-LRU pages in all the zones which
183 * are eligible for the caller's allocation attempt. It is used for balancing
184 * slab reclaim versus page reclaim.
186 static int shrink_slab(unsigned long scanned, unsigned int gfp_mask,
187 unsigned long lru_pages)
189 struct shrinker *shrinker;
191 if (down_trylock(&shrinker_sem))
194 list_for_each_entry(shrinker, &shrinker_list, list) {
195 unsigned long long delta;
197 delta = (4 * scanned) / shrinker->seeks;
198 delta *= (*shrinker->shrinker)(0, gfp_mask);
199 do_div(delta, lru_pages + 1);
200 shrinker->nr += delta;
201 if (shrinker->nr < 0)
202 shrinker->nr = LONG_MAX; /* It wrapped! */
204 if (shrinker->nr <= SHRINK_BATCH)
206 while (shrinker->nr) {
207 long this_scan = shrinker->nr;
212 shrink_ret = (*shrinker->shrinker)(this_scan, gfp_mask);
213 mod_page_state(slabs_scanned, this_scan);
214 shrinker->nr -= this_scan;
215 if (shrink_ret == -1)
224 /* Must be called with page's rmap lock held. */
225 static inline int page_mapping_inuse(struct page *page)
227 struct address_space *mapping;
229 /* Page is in somebody's page tables. */
230 if (page_mapped(page))
233 /* Be more reluctant to reclaim swapcache than pagecache */
234 if (PageSwapCache(page))
237 mapping = page_mapping(page);
241 /* File is mmap'd by somebody? */
242 return mapping_mapped(mapping);
245 static inline int is_page_cache_freeable(struct page *page)
247 return page_count(page) - !!PagePrivate(page) == 2;
250 static int may_write_to_queue(struct backing_dev_info *bdi)
252 if (current_is_kswapd())
254 if (current_is_pdflush()) /* This is unlikely, but why not... */
256 if (!bdi_write_congested(bdi))
258 if (bdi == current->backing_dev_info)
264 * We detected a synchronous write error writing a page out. Probably
265 * -ENOSPC. We need to propagate that into the address_space for a subsequent
266 * fsync(), msync() or close().
268 * The tricky part is that after writepage we cannot touch the mapping: nothing
269 * prevents it from being freed up. But we have a ref on the page and once
270 * that page is locked, the mapping is pinned.
272 * We're allowed to run sleeping lock_page() here because we know the caller has
275 static void handle_write_error(struct address_space *mapping,
276 struct page *page, int error)
279 if (page_mapping(page) == mapping) {
280 if (error == -ENOSPC)
281 set_bit(AS_ENOSPC, &mapping->flags);
283 set_bit(AS_EIO, &mapping->flags);
289 * pageout is called by shrink_list() for each dirty page. Calls ->writepage().
291 static pageout_t pageout(struct page *page, struct address_space *mapping)
294 * If the page is dirty, only perform writeback if that write
295 * will be non-blocking. To prevent this allocation from being
296 * stalled by pagecache activity. But note that there may be
297 * stalls if we need to run get_block(). We could test
298 * PagePrivate for that.
300 * If this process is currently in generic_file_write() against
301 * this page's queue, we can perform writeback even if that
304 * If the page is swapcache, write it back even if that would
305 * block, for some throttling. This happens by accident, because
306 * swap_backing_dev_info is bust: it doesn't reflect the
307 * congestion state of the swapdevs. Easy to fix, if needed.
308 * See swapfile.c:page_queue_congested().
310 if (!is_page_cache_freeable(page))
314 if (mapping->a_ops->writepage == NULL)
315 return PAGE_ACTIVATE;
316 if (!may_write_to_queue(mapping->backing_dev_info))
319 if (clear_page_dirty_for_io(page)) {
321 struct writeback_control wbc = {
322 .sync_mode = WB_SYNC_NONE,
323 .nr_to_write = SWAP_CLUSTER_MAX,
328 SetPageReclaim(page);
329 res = mapping->a_ops->writepage(page, &wbc);
331 handle_write_error(mapping, page, res);
332 if (res == WRITEPAGE_ACTIVATE) {
333 ClearPageReclaim(page);
334 return PAGE_ACTIVATE;
336 if (!PageWriteback(page)) {
337 /* synchronous write or broken a_ops? */
338 ClearPageReclaim(page);
348 * shrink_list adds the number of reclaimed pages to sc->nr_reclaimed
350 static int shrink_list(struct list_head *page_list, struct scan_control *sc)
352 LIST_HEAD(ret_pages);
353 struct pagevec freed_pvec;
359 pagevec_init(&freed_pvec, 1);
360 while (!list_empty(page_list)) {
361 struct address_space *mapping;
368 page = lru_to_page(page_list);
369 list_del(&page->lru);
371 if (TestSetPageLocked(page))
374 BUG_ON(PageActive(page));
376 if (PageWriteback(page))
380 /* Double the slab pressure for mapped and swapcache pages */
381 if (page_mapped(page) || PageSwapCache(page))
385 referenced = page_referenced(page);
386 if (referenced && page_mapping_inuse(page)) {
387 /* In active use or really unfreeable. Activate it. */
388 page_map_unlock(page);
389 goto activate_locked;
394 * Anonymous process memory has backing store?
395 * Try to allocate it some swap space here.
397 * XXX: implement swap clustering ?
399 if (PageAnon(page) && !PageSwapCache(page)) {
400 page_map_unlock(page);
401 if (!add_to_swap(page))
402 goto activate_locked;
405 #endif /* CONFIG_SWAP */
407 mapping = page_mapping(page);
408 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
409 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
412 * The page is mapped into the page tables of one or more
413 * processes. Try to unmap it here.
415 if (page_mapped(page) && mapping) {
416 switch (try_to_unmap(page)) {
418 page_map_unlock(page);
419 goto activate_locked;
421 page_map_unlock(page);
424 ; /* try to free the page below */
427 page_map_unlock(page);
429 if (PageDirty(page)) {
434 if (laptop_mode && !sc->may_writepage)
437 /* Page is dirty, try to write it out here */
438 switch(pageout(page, mapping)) {
442 goto activate_locked;
444 if (PageWriteback(page) || PageDirty(page))
447 * A synchronous write - probably a ramdisk. Go
448 * ahead and try to reclaim the page.
450 if (TestSetPageLocked(page))
452 if (PageDirty(page) || PageWriteback(page))
454 mapping = page_mapping(page);
456 ; /* try to free the page below */
461 * If the page has buffers, try to free the buffer mappings
462 * associated with this page. If we succeed we try to free
465 * We do this even if the page is PageDirty().
466 * try_to_release_page() does not perform I/O, but it is
467 * possible for a page to have PageDirty set, but it is actually
468 * clean (all its buffers are clean). This happens if the
469 * buffers were written out directly, with submit_bh(). ext3
470 * will do this, as well as the blockdev mapping.
471 * try_to_release_page() will discover that cleanness and will
472 * drop the buffers and mark the page clean - it can be freed.
474 * Rarely, pages can have buffers and no ->mapping. These are
475 * the pages which were not successfully invalidated in
476 * truncate_complete_page(). We try to drop those buffers here
477 * and if that worked, and the page is no longer mapped into
478 * process address space (page_count == 1) it can be freed.
479 * Otherwise, leave the page on the LRU so it is swappable.
481 if (PagePrivate(page)) {
482 if (!try_to_release_page(page, sc->gfp_mask))
483 goto activate_locked;
484 if (!mapping && page_count(page) == 1)
489 goto keep_locked; /* truncate got there first */
491 spin_lock_irq(&mapping->tree_lock);
494 * The non-racy check for busy page. It is critical to check
495 * PageDirty _after_ making sure that the page is freeable and
496 * not in use by anybody. (pagecache + us == 2)
498 if (page_count(page) != 2 || PageDirty(page)) {
499 spin_unlock_irq(&mapping->tree_lock);
504 if (PageSwapCache(page)) {
505 swp_entry_t swap = { .val = page->private };
506 __delete_from_swap_cache(page);
507 spin_unlock_irq(&mapping->tree_lock);
509 __put_page(page); /* The pagecache ref */
512 #endif /* CONFIG_SWAP */
514 __remove_from_page_cache(page);
515 spin_unlock_irq(&mapping->tree_lock);
521 if (!pagevec_add(&freed_pvec, page))
522 __pagevec_release_nonlru(&freed_pvec);
531 list_add(&page->lru, &ret_pages);
532 BUG_ON(PageLRU(page));
534 list_splice(&ret_pages, page_list);
535 if (pagevec_count(&freed_pvec))
536 __pagevec_release_nonlru(&freed_pvec);
537 mod_page_state(pgactivate, pgactivate);
538 sc->nr_reclaimed += reclaimed;
543 * zone->lru_lock is heavily contented. We relieve it by quickly privatising
544 * a batch of pages and working on them outside the lock. Any pages which were
545 * not freed will be added back to the LRU.
547 * shrink_cache() adds the number of pages reclaimed to sc->nr_reclaimed
549 * For pagecache intensive workloads, the first loop here is the hottest spot
550 * in the kernel (apart from the copy_*_user functions).
552 static void shrink_cache(struct zone *zone, struct scan_control *sc)
554 LIST_HEAD(page_list);
556 int max_scan = sc->nr_to_scan, nr_pass;
557 unsigned int ckrm_flags = sc->ckrm_flags, bit_flag;
559 pagevec_init(&pvec, 1);
562 spin_lock_irq(&zone->lru_lock);
564 ckrm_get_reclaim_bits(&ckrm_flags, &bit_flag);
565 nr_pass = zone->nr_inactive;
566 while (max_scan > 0) {
572 while (nr_pass-- && nr_scan++ < SWAP_CLUSTER_MAX &&
573 !list_empty(&zone->inactive_list)) {
574 page = lru_to_page(&zone->inactive_list);
576 prefetchw_prev_lru_page(page,
577 &zone->inactive_list, flags);
579 if (!TestClearPageLRU(page))
581 list_del(&page->lru);
582 if (get_page_testone(page)) {
584 * It is being freed elsewhere
588 list_add(&page->lru, &zone->inactive_list);
590 } else if (bit_flag && !ckrm_kick_page(page, bit_flag)) {
593 #ifdef CONFIG_CKRM_MEM_LRUORDER_CHANGE
594 list_add_tail(&page->lru, &zone->inactive_list);
596 list_add(&page->lru, &zone->inactive_list);
600 list_add(&page->lru, &page_list);
601 ckrm_mem_dec_inactive(page);
604 zone->nr_inactive -= nr_taken;
605 zone->pages_scanned += nr_taken;
606 spin_unlock_irq(&zone->lru_lock);
608 if ((bit_flag == 0) && (nr_taken == 0))
612 if (current_is_kswapd())
613 mod_page_state_zone(zone, pgscan_kswapd, nr_scan);
615 mod_page_state_zone(zone, pgscan_direct, nr_scan);
616 nr_freed = shrink_list(&page_list, sc);
617 if (current_is_kswapd())
618 mod_page_state(kswapd_steal, nr_freed);
619 mod_page_state_zone(zone, pgsteal, nr_freed);
620 sc->nr_to_reclaim -= nr_freed;
622 spin_lock_irq(&zone->lru_lock);
624 * Put back any unfreeable pages.
626 while (!list_empty(&page_list)) {
627 page = lru_to_page(&page_list);
628 if (TestSetPageLRU(page))
630 list_del(&page->lru);
631 if (PageActive(page))
632 add_page_to_active_list(zone, page);
634 add_page_to_inactive_list(zone, page);
635 if (!pagevec_add(&pvec, page)) {
636 spin_unlock_irq(&zone->lru_lock);
637 __pagevec_release(&pvec);
638 spin_lock_irq(&zone->lru_lock);
641 if (ckrm_flags && (nr_pass <= 0)) {
645 spin_unlock_irq(&zone->lru_lock);
647 pagevec_release(&pvec);
651 * This moves pages from the active list to the inactive list.
653 * We move them the other way if the page is referenced by one or more
654 * processes, from rmap.
656 * If the pages are mostly unmapped, the processing is fast and it is
657 * appropriate to hold zone->lru_lock across the whole operation. But if
658 * the pages are mapped, the processing is slow (page_referenced()) so we
659 * should drop zone->lru_lock around each page. It's impossible to balance
660 * this, so instead we remove the pages from the LRU while processing them.
661 * It is safe to rely on PG_active against the non-LRU pages in here because
662 * nobody will play with that bit on a non-LRU page.
664 * The downside is that we have to touch page->_count against each page.
665 * But we had to alter page->flags anyway.
668 refill_inactive_zone(struct zone *zone, struct scan_control *sc)
671 int pgdeactivate = 0;
673 int nr_pages = sc->nr_to_scan;
674 LIST_HEAD(l_hold); /* The pages which were snipped off */
675 LIST_HEAD(l_inactive); /* Pages to go onto the inactive_list */
676 LIST_HEAD(l_active); /* Pages to go onto the active_list */
679 int reclaim_mapped = 0;
683 unsigned int ckrm_flags = sc->ckrm_flags, bit_flag;
688 spin_lock_irq(&zone->lru_lock);
690 ckrm_get_reclaim_bits(&ckrm_flags, &bit_flag);
691 nr_pass = zone->nr_active;
692 while (pgscanned < nr_pages && !list_empty(&zone->active_list) &&
694 page = lru_to_page(&zone->active_list);
695 prefetchw_prev_lru_page(page, &zone->active_list, flags);
696 if (!TestClearPageLRU(page))
698 list_del(&page->lru);
699 if (get_page_testone(page)) {
701 * It was already free! release_pages() or put_page()
702 * are about to remove it from the LRU and free it. So
703 * put the refcount back and put the page back on the
708 list_add(&page->lru, &zone->active_list);
710 } else if (bit_flag && !ckrm_kick_page(page, bit_flag)) {
713 #ifdef CONFIG_CKRM_MEM_LRUORDER_CHANGE
714 list_add_tail(&page->lru, &zone->active_list);
716 list_add(&page->lru, &zone->active_list);
719 list_add(&page->lru, &l_hold);
720 ckrm_mem_dec_active(page);
724 if (!--nr_pass && ckrm_flags) {
728 zone->nr_active -= pgmoved;
729 spin_unlock_irq(&zone->lru_lock);
732 * `distress' is a measure of how much trouble we're having reclaiming
733 * pages. 0 -> no problems. 100 -> great trouble.
735 distress = 100 >> zone->prev_priority;
738 * The point of this algorithm is to decide when to start reclaiming
739 * mapped memory instead of just pagecache. Work out how much memory
742 mapped_ratio = (sc->nr_mapped * 100) / total_memory;
745 * Now decide how much we really want to unmap some pages. The mapped
746 * ratio is downgraded - just because there's a lot of mapped memory
747 * doesn't necessarily mean that page reclaim isn't succeeding.
749 * The distress ratio is important - we don't want to start going oom.
751 * A 100% value of vm_swappiness overrides this algorithm altogether.
753 swap_tendency = mapped_ratio / 2 + distress + vm_swappiness;
756 * Now use this metric to decide whether to start moving mapped memory
757 * onto the inactive list.
759 if (swap_tendency >= 100)
762 while (!list_empty(&l_hold)) {
764 page = lru_to_page(&l_hold);
765 list_del(&page->lru);
766 if (page_mapped(page)) {
767 if (!reclaim_mapped) {
768 list_add(&page->lru, &l_active);
772 if (page_referenced(page)) {
773 page_map_unlock(page);
774 list_add(&page->lru, &l_active);
777 page_map_unlock(page);
780 * FIXME: need to consider page_count(page) here if/when we
781 * reap orphaned pages via the LRU (Daniel's locking stuff)
783 if (total_swap_pages == 0 && PageAnon(page)) {
784 list_add(&page->lru, &l_active);
787 list_add(&page->lru, &l_inactive);
790 pagevec_init(&pvec, 1);
792 spin_lock_irq(&zone->lru_lock);
793 while (!list_empty(&l_inactive)) {
794 page = lru_to_page(&l_inactive);
795 prefetchw_prev_lru_page(page, &l_inactive, flags);
796 if (TestSetPageLRU(page))
798 if (!TestClearPageActive(page))
800 list_move(&page->lru, &zone->inactive_list);
801 ckrm_mem_inc_inactive(page);
803 if (!pagevec_add(&pvec, page)) {
804 zone->nr_inactive += pgmoved;
805 spin_unlock_irq(&zone->lru_lock);
806 pgdeactivate += pgmoved;
808 if (buffer_heads_over_limit)
809 pagevec_strip(&pvec);
810 __pagevec_release(&pvec);
811 spin_lock_irq(&zone->lru_lock);
814 zone->nr_inactive += pgmoved;
815 pgdeactivate += pgmoved;
816 if (buffer_heads_over_limit) {
817 spin_unlock_irq(&zone->lru_lock);
818 pagevec_strip(&pvec);
819 spin_lock_irq(&zone->lru_lock);
823 while (!list_empty(&l_active)) {
824 page = lru_to_page(&l_active);
825 prefetchw_prev_lru_page(page, &l_active, flags);
826 if (TestSetPageLRU(page))
828 BUG_ON(!PageActive(page));
829 list_move(&page->lru, &zone->active_list);
830 ckrm_mem_inc_active(page);
832 if (!pagevec_add(&pvec, page)) {
833 zone->nr_active += pgmoved;
835 spin_unlock_irq(&zone->lru_lock);
836 __pagevec_release(&pvec);
837 spin_lock_irq(&zone->lru_lock);
840 zone->nr_active += pgmoved;
841 spin_unlock_irq(&zone->lru_lock);
842 pagevec_release(&pvec);
844 mod_page_state_zone(zone, pgrefill, pgscanned);
845 mod_page_state(pgdeactivate, pgdeactivate);
849 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
852 shrink_zone(struct zone *zone, struct scan_control *sc)
854 unsigned long nr_active;
855 unsigned long nr_inactive;
858 * Add one to `nr_to_scan' just to make sure that the kernel will
859 * slowly sift through the active list.
861 zone->nr_scan_active += (zone->nr_active >> sc->priority) + 1;
862 nr_active = zone->nr_scan_active;
863 if (nr_active >= SWAP_CLUSTER_MAX)
864 zone->nr_scan_active = 0;
868 zone->nr_scan_inactive += (zone->nr_inactive >> sc->priority) + 1;
869 nr_inactive = zone->nr_scan_inactive;
870 if (nr_inactive >= SWAP_CLUSTER_MAX)
871 zone->nr_scan_inactive = 0;
875 sc->nr_to_reclaim = SWAP_CLUSTER_MAX;
877 while (nr_active || nr_inactive) {
878 sc->ckrm_flags = ckrm_setup_reclamation();
880 sc->nr_to_scan = min(nr_active,
881 (unsigned long)SWAP_CLUSTER_MAX);
882 nr_active -= sc->nr_to_scan;
883 refill_inactive_zone(zone, sc);
887 sc->nr_to_scan = min(nr_inactive,
888 (unsigned long)SWAP_CLUSTER_MAX);
889 nr_inactive -= sc->nr_to_scan;
890 shrink_cache(zone, sc);
891 if (sc->nr_to_reclaim <= 0)
894 ckrm_teardown_reclamation();
898 #ifdef CONFIG_CKRM_RES_MEM
899 // This function needs to be given more thought.
900 // Shrink the class to be at 90% of its limit
902 ckrm_shrink_class(ckrm_mem_res_t *cls)
904 struct scan_control sc;
906 int zindex = 0, active_credit = 0, inactive_credit = 0;
908 if (ckrm_test_set_shrink(cls)) { // set the SHRINK bit atomically
909 // if it is already set somebody is working on it. so... leave
912 sc.nr_mapped = read_page_state(nr_mapped);
914 sc.ckrm_flags = ckrm_get_reclaim_flags(cls);
916 sc.priority = 0; // always very high priority
918 for_each_zone(zone) {
919 int zone_total, zone_limit, active_limit, inactive_limit;
920 int active_over, inactive_over;
921 unsigned long nr_active, nr_inactive;
924 zone->temp_priority = zone->prev_priority;
925 zone->prev_priority = sc.priority;
927 zone_total = zone->nr_active + zone->nr_inactive + zone->free_pages;
929 temp = (u64) cls->pg_limit * zone_total;
930 do_div(temp, ckrm_tot_lru_pages);
931 zone_limit = (int) temp;
932 active_limit = (6 * zone_limit) / 10; // 2/3rd in active list
933 inactive_limit = (3 * zone_limit) / 10; // 1/3rd in inactive list
935 active_over = cls->nr_active[zindex] - active_limit + active_credit;
936 inactive_over = active_over +
937 (cls->nr_inactive[zindex] - inactive_limit) + inactive_credit;
939 if (active_over > 0) {
940 zone->nr_scan_active += active_over + 1;
941 nr_active = zone->nr_scan_active;
944 active_credit += active_over;
948 if (inactive_over > 0) {
949 zone->nr_scan_inactive += inactive_over;
950 nr_inactive = zone->nr_scan_inactive;
953 inactive_credit += inactive_over;
956 while (nr_active || nr_inactive) {
958 sc.nr_to_scan = min(nr_active,
959 (unsigned long)SWAP_CLUSTER_MAX);
960 nr_active -= sc.nr_to_scan;
961 refill_inactive_zone(zone, &sc);
965 sc.nr_to_scan = min(nr_inactive,
966 (unsigned long)SWAP_CLUSTER_MAX);
967 nr_inactive -= sc.nr_to_scan;
968 shrink_cache(zone, &sc);
969 if (sc.nr_to_reclaim <= 0)
973 zone->prev_priority = zone->temp_priority;
976 ckrm_clear_shrink(cls);
980 ckrm_shrink_classes(void)
984 spin_lock(&ckrm_mem_lock);
985 while (!ckrm_shrink_list_empty()) {
986 cls = list_entry(ckrm_shrink_list.next, ckrm_mem_res_t,
988 spin_unlock(&ckrm_mem_lock);
989 ckrm_shrink_class(cls);
990 spin_lock(&ckrm_mem_lock);
991 list_del(&cls->shrink_list);
992 cls->flags &= ~MEM_AT_LIMIT;
994 spin_unlock(&ckrm_mem_lock);
998 #define ckrm_shrink_classes() do { } while(0)
1002 * This is the direct reclaim path, for page-allocating processes. We only
1003 * try to reclaim pages from zones which will satisfy the caller's allocation
1006 * We reclaim from a zone even if that zone is over pages_high. Because:
1007 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
1009 * b) The zones may be over pages_high but they must go *over* pages_high to
1010 * satisfy the `incremental min' zone defense algorithm.
1012 * Returns the number of reclaimed pages.
1014 * If a zone is deemed to be full of pinned pages then just give it a light
1015 * scan then give up on it.
1018 shrink_caches(struct zone **zones, struct scan_control *sc)
1022 for (i = 0; zones[i] != NULL; i++) {
1023 struct zone *zone = zones[i];
1025 zone->temp_priority = sc->priority;
1026 if (zone->prev_priority > sc->priority)
1027 zone->prev_priority = sc->priority;
1029 if (zone->all_unreclaimable && sc->priority != DEF_PRIORITY)
1030 continue; /* Let kswapd poll it */
1032 shrink_zone(zone, sc);
1037 * This is the main entry point to direct page reclaim.
1039 * If a full scan of the inactive list fails to free enough memory then we
1040 * are "out of memory" and something needs to be killed.
1042 * If the caller is !__GFP_FS then the probability of a failure is reasonably
1043 * high - the zone may be full of dirty or under-writeback pages, which this
1044 * caller can't do much about. We kick pdflush and take explicit naps in the
1045 * hope that some of these pages can be written. But if the allocating task
1046 * holds filesystem locks which prevent writeout this might not work, and the
1047 * allocation attempt will fail.
1049 int try_to_free_pages(struct zone **zones,
1050 unsigned int gfp_mask, unsigned int order)
1054 int total_scanned = 0, total_reclaimed = 0;
1055 struct reclaim_state *reclaim_state = current->reclaim_state;
1056 struct scan_control sc;
1057 unsigned long lru_pages = 0;
1060 sc.gfp_mask = gfp_mask;
1061 sc.may_writepage = 0;
1063 inc_page_state(allocstall);
1065 for (i = 0; zones[i] != NULL; i++) {
1066 struct zone *zone = zones[i];
1068 zone->temp_priority = DEF_PRIORITY;
1069 lru_pages += zone->nr_active + zone->nr_inactive;
1072 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1073 sc.nr_mapped = read_page_state(nr_mapped);
1075 sc.nr_reclaimed = 0;
1076 sc.priority = priority;
1077 shrink_caches(zones, &sc);
1078 shrink_slab(sc.nr_scanned, gfp_mask, lru_pages);
1079 if (reclaim_state) {
1080 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
1081 reclaim_state->reclaimed_slab = 0;
1083 if (sc.nr_reclaimed >= SWAP_CLUSTER_MAX) {
1087 total_scanned += sc.nr_scanned;
1088 total_reclaimed += sc.nr_reclaimed;
1091 * Try to write back as many pages as we just scanned. This
1092 * tends to cause slow streaming writers to write data to the
1093 * disk smoothly, at the dirtying rate, which is nice. But
1094 * that's undesirable in laptop mode, where we *want* lumpy
1095 * writeout. So in laptop mode, write out the whole world.
1097 if (total_scanned > SWAP_CLUSTER_MAX + SWAP_CLUSTER_MAX/2) {
1098 wakeup_bdflush(laptop_mode ? 0 : total_scanned);
1099 sc.may_writepage = 1;
1102 /* Take a nap, wait for some writeback to complete */
1103 if (sc.nr_scanned && priority < DEF_PRIORITY - 2)
1104 blk_congestion_wait(WRITE, HZ/10);
1106 if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY))
1107 out_of_memory(gfp_mask);
1109 for (i = 0; zones[i] != 0; i++)
1110 zones[i]->prev_priority = zones[i]->temp_priority;
1115 * For kswapd, balance_pgdat() will work across all this node's zones until
1116 * they are all at pages_high.
1118 * If `nr_pages' is non-zero then it is the number of pages which are to be
1119 * reclaimed, regardless of the zone occupancies. This is a software suspend
1122 * Returns the number of pages which were actually freed.
1124 * There is special handling here for zones which are full of pinned pages.
1125 * This can happen if the pages are all mlocked, or if they are all used by
1126 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
1127 * What we do is to detect the case where all pages in the zone have been
1128 * scanned twice and there has been zero successful reclaim. Mark the zone as
1129 * dead and from now on, only perform a short scan. Basically we're polling
1130 * the zone for when the problem goes away.
1132 * kswapd scans the zones in the highmem->normal->dma direction. It skips
1133 * zones which have free_pages > pages_high, but once a zone is found to have
1134 * free_pages <= pages_high, we scan that zone and the lower zones regardless
1135 * of the number of free pages in the lower zones. This interoperates with
1136 * the page allocator fallback scheme to ensure that aging of pages is balanced
1139 static int balance_pgdat(pg_data_t *pgdat, int nr_pages)
1141 int to_free = nr_pages;
1144 int total_scanned = 0, total_reclaimed = 0;
1145 struct reclaim_state *reclaim_state = current->reclaim_state;
1146 struct scan_control sc;
1148 sc.gfp_mask = GFP_KERNEL;
1149 sc.may_writepage = 0;
1150 sc.nr_mapped = read_page_state(nr_mapped);
1152 inc_page_state(pageoutrun);
1154 for (i = 0; i < pgdat->nr_zones; i++) {
1155 struct zone *zone = pgdat->node_zones + i;
1157 zone->temp_priority = DEF_PRIORITY;
1160 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1161 int all_zones_ok = 1;
1162 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
1163 unsigned long lru_pages = 0;
1165 if (nr_pages == 0) {
1167 * Scan in the highmem->dma direction for the highest
1168 * zone which needs scanning
1170 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
1171 struct zone *zone = pgdat->node_zones + i;
1173 if (zone->all_unreclaimable &&
1174 priority != DEF_PRIORITY)
1177 if (zone->free_pages <= zone->pages_high) {
1184 end_zone = pgdat->nr_zones - 1;
1187 for (i = 0; i <= end_zone; i++) {
1188 struct zone *zone = pgdat->node_zones + i;
1190 lru_pages += zone->nr_active + zone->nr_inactive;
1194 * Now scan the zone in the dma->highmem direction, stopping
1195 * at the last zone which needs scanning.
1197 * We do this because the page allocator works in the opposite
1198 * direction. This prevents the page allocator from allocating
1199 * pages behind kswapd's direction of progress, which would
1200 * cause too much scanning of the lower zones.
1202 for (i = 0; i <= end_zone; i++) {
1203 struct zone *zone = pgdat->node_zones + i;
1205 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1208 if (nr_pages == 0) { /* Not software suspend */
1209 if (zone->free_pages <= zone->pages_high)
1212 zone->temp_priority = priority;
1213 if (zone->prev_priority > priority)
1214 zone->prev_priority = priority;
1216 sc.nr_reclaimed = 0;
1217 sc.priority = priority;
1218 shrink_zone(zone, &sc);
1219 reclaim_state->reclaimed_slab = 0;
1220 shrink_slab(sc.nr_scanned, GFP_KERNEL, lru_pages);
1221 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
1222 total_reclaimed += sc.nr_reclaimed;
1223 if (zone->all_unreclaimable)
1225 if (zone->pages_scanned > zone->present_pages * 2)
1226 zone->all_unreclaimable = 1;
1228 * If we've done a decent amount of scanning and
1229 * the reclaim ratio is low, start doing writepage
1230 * even in laptop mode
1232 if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
1233 total_scanned > total_reclaimed+total_reclaimed/2)
1234 sc.may_writepage = 1;
1236 if (nr_pages && to_free > total_reclaimed)
1237 continue; /* swsusp: need to do more work */
1239 break; /* kswapd: all done */
1241 * OK, kswapd is getting into trouble. Take a nap, then take
1242 * another pass across the zones.
1244 if (total_scanned && priority < DEF_PRIORITY - 2)
1245 blk_congestion_wait(WRITE, HZ/10);
1248 for (i = 0; i < pgdat->nr_zones; i++) {
1249 struct zone *zone = pgdat->node_zones + i;
1251 zone->prev_priority = zone->temp_priority;
1253 return total_reclaimed;
1257 * The background pageout daemon, started as a kernel thread
1258 * from the init process.
1260 * This basically trickles out pages so that we have _some_
1261 * free memory available even if there is no other activity
1262 * that frees anything up. This is needed for things like routing
1263 * etc, where we otherwise might have all activity going on in
1264 * asynchronous contexts that cannot page things out.
1266 * If there are applications that are active memory-allocators
1267 * (most normal use), this basically shouldn't matter.
1269 static int kswapd(void *p)
1271 pg_data_t *pgdat = (pg_data_t*)p;
1272 struct task_struct *tsk = current;
1274 struct reclaim_state reclaim_state = {
1275 .reclaimed_slab = 0,
1279 daemonize("kswapd%d", pgdat->node_id);
1280 cpumask = node_to_cpumask(pgdat->node_id);
1281 if (!cpus_empty(cpumask))
1282 set_cpus_allowed(tsk, cpumask);
1283 current->reclaim_state = &reclaim_state;
1286 * Tell the memory management that we're a "memory allocator",
1287 * and that if we need more memory we should get access to it
1288 * regardless (see "__alloc_pages()"). "kswapd" should
1289 * never get caught in the normal page freeing logic.
1291 * (Kswapd normally doesn't need memory anyway, but sometimes
1292 * you need a small amount of memory in order to be able to
1293 * page out something else, and this flag essentially protects
1294 * us from recursively trying to free more memory as we're
1295 * trying to free the first piece of memory in the first place).
1297 tsk->flags |= PF_MEMALLOC|PF_KSWAPD;
1300 if (current->flags & PF_FREEZE)
1301 refrigerator(PF_FREEZE);
1302 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
1304 finish_wait(&pgdat->kswapd_wait, &wait);
1305 try_to_clip_inodes();
1307 if (!ckrm_shrink_list_empty())
1308 ckrm_shrink_classes();
1310 balance_pgdat(pgdat, 0);
1316 * A zone is low on free memory, so wake its kswapd task to service it.
1318 void wakeup_kswapd(struct zone *zone)
1320 if ((zone->free_pages > zone->pages_low) && ckrm_shrink_list_empty())
1322 if (!waitqueue_active(&zone->zone_pgdat->kswapd_wait))
1324 wake_up_interruptible(&zone->zone_pgdat->kswapd_wait);
1329 * Try to free `nr_pages' of memory, system-wide. Returns the number of freed
1332 int shrink_all_memory(int nr_pages)
1335 int nr_to_free = nr_pages;
1337 struct reclaim_state reclaim_state = {
1338 .reclaimed_slab = 0,
1341 current->reclaim_state = &reclaim_state;
1342 for_each_pgdat(pgdat) {
1344 freed = balance_pgdat(pgdat, nr_to_free);
1346 nr_to_free -= freed;
1347 if (nr_to_free <= 0)
1350 current->reclaim_state = NULL;
1355 #ifdef CONFIG_HOTPLUG_CPU
1356 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1357 not required for correctness. So if the last cpu in a node goes
1358 away, we get changed to run anywhere: as the first one comes back,
1359 restore their cpu bindings. */
1360 static int __devinit cpu_callback(struct notifier_block *nfb,
1361 unsigned long action,
1367 if (action == CPU_ONLINE) {
1368 for_each_pgdat(pgdat) {
1369 mask = node_to_cpumask(pgdat->node_id);
1370 if (any_online_cpu(mask) != NR_CPUS)
1371 /* One of our CPUs online: restore mask */
1372 set_cpus_allowed(pgdat->kswapd, mask);
1377 #endif /* CONFIG_HOTPLUG_CPU */
1379 static int __init kswapd_init(void)
1383 for_each_pgdat(pgdat)
1385 = find_task_by_pid(kernel_thread(kswapd, pgdat, CLONE_KERNEL));
1386 total_memory = nr_free_pagecache_pages();
1387 hotcpu_notifier(cpu_callback, 0);
1391 module_init(kswapd_init)