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>
41 #include <linux/ckrm_mem.h>
43 #ifndef AT_LIMIT_SUPPORT
44 #warning "ckrm_at_limit disabled due to problems with memory hog tests -- seting ckrm_shrink_list_empty to true"
45 #undef ckrm_shrink_list_empty
46 #define ckrm_shrink_list_empty() (1)
49 /* possible outcome of pageout() */
51 /* failed to write page out, page is locked */
53 /* move page to the active list, page is locked */
55 /* page has been sent to the disk successfully, page is unlocked */
57 /* page is clean and locked */
62 /* Ask refill_inactive_zone, or shrink_cache to scan this many pages */
63 unsigned long nr_to_scan;
65 /* Incremented by the number of inactive pages that were scanned */
66 unsigned long nr_scanned;
68 /* Incremented by the number of pages reclaimed */
69 unsigned long nr_reclaimed;
71 unsigned long nr_mapped; /* From page_state */
73 /* How many pages shrink_cache() should reclaim */
76 /* Ask shrink_caches, or shrink_zone to scan at this priority */
77 unsigned int priority;
79 /* This context's GFP mask */
80 unsigned int gfp_mask;
82 /* Flag used by CKRM */
83 unsigned int ckrm_flags;
89 * The list of shrinker callbacks used by to apply pressure to
94 struct list_head list;
95 int seeks; /* seeks to recreate an obj */
96 long nr; /* objs pending delete */
99 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
101 #ifdef ARCH_HAS_PREFETCH
102 #define prefetch_prev_lru_page(_page, _base, _field) \
104 if ((_page)->lru.prev != _base) { \
107 prev = lru_to_page(&(_page->lru)); \
108 prefetch(&prev->_field); \
112 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
115 #ifdef ARCH_HAS_PREFETCHW
116 #define prefetchw_prev_lru_page(_page, _base, _field) \
118 if ((_page)->lru.prev != _base) { \
121 prev = lru_to_page(&(_page->lru)); \
122 prefetchw(&prev->_field); \
126 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
130 * From 0 .. 100. Higher means more swappy.
132 int vm_swappiness = 60;
133 static long total_memory;
135 static LIST_HEAD(shrinker_list);
136 static DECLARE_RWSEM(shrinker_rwsem);
139 * Add a shrinker callback to be called from the vm
141 struct shrinker *set_shrinker(int seeks, shrinker_t theshrinker)
143 struct shrinker *shrinker;
145 shrinker = kmalloc(sizeof(*shrinker), GFP_KERNEL);
147 shrinker->shrinker = theshrinker;
148 shrinker->seeks = seeks;
150 down_write(&shrinker_rwsem);
151 list_add(&shrinker->list, &shrinker_list);
152 up_write(&shrinker_rwsem);
156 EXPORT_SYMBOL(set_shrinker);
161 void remove_shrinker(struct shrinker *shrinker)
163 down_write(&shrinker_rwsem);
164 list_del(&shrinker->list);
165 up_write(&shrinker_rwsem);
168 EXPORT_SYMBOL(remove_shrinker);
170 #define SHRINK_BATCH 128
172 * Call the shrink functions to age shrinkable caches
174 * Here we assume it costs one seek to replace a lru page and that it also
175 * takes a seek to recreate a cache object. With this in mind we age equal
176 * percentages of the lru and ageable caches. This should balance the seeks
177 * generated by these structures.
179 * If the vm encounted mapped pages on the LRU it increase the pressure on
180 * slab to avoid swapping.
182 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
184 * `lru_pages' represents the number of on-LRU pages in all the zones which
185 * are eligible for the caller's allocation attempt. It is used for balancing
186 * slab reclaim versus page reclaim.
188 static int shrink_slab(unsigned long scanned, unsigned int gfp_mask,
189 unsigned long lru_pages)
191 struct shrinker *shrinker;
194 scanned = SWAP_CLUSTER_MAX;
196 if (!down_read_trylock(&shrinker_rwsem))
199 list_for_each_entry(shrinker, &shrinker_list, list) {
200 unsigned long long delta;
201 unsigned long total_scan;
203 delta = (4 * scanned) / shrinker->seeks;
204 delta *= (*shrinker->shrinker)(0, gfp_mask);
205 do_div(delta, lru_pages + 1);
206 shrinker->nr += delta;
207 if (shrinker->nr < 0)
208 shrinker->nr = LONG_MAX; /* It wrapped! */
210 total_scan = shrinker->nr;
213 while (total_scan >= SHRINK_BATCH) {
214 long this_scan = SHRINK_BATCH;
217 shrink_ret = (*shrinker->shrinker)(this_scan, gfp_mask);
218 if (shrink_ret == -1)
220 mod_page_state(slabs_scanned, this_scan);
221 total_scan -= this_scan;
226 shrinker->nr += total_scan;
228 up_read(&shrinker_rwsem);
232 /* Called without lock on whether page is mapped, so answer is unstable */
233 static inline int page_mapping_inuse(struct page *page)
235 struct address_space *mapping;
237 /* Page is in somebody's page tables. */
238 if (page_mapped(page))
241 /* Be more reluctant to reclaim swapcache than pagecache */
242 if (PageSwapCache(page))
245 mapping = page_mapping(page);
249 /* File is mmap'd by somebody? */
250 return mapping_mapped(mapping);
253 static inline int is_page_cache_freeable(struct page *page)
255 return page_count(page) - !!PagePrivate(page) == 2;
258 static int may_write_to_queue(struct backing_dev_info *bdi)
260 if (current_is_kswapd())
262 if (current_is_pdflush()) /* This is unlikely, but why not... */
264 if (!bdi_write_congested(bdi))
266 if (bdi == current->backing_dev_info)
272 * We detected a synchronous write error writing a page out. Probably
273 * -ENOSPC. We need to propagate that into the address_space for a subsequent
274 * fsync(), msync() or close().
276 * The tricky part is that after writepage we cannot touch the mapping: nothing
277 * prevents it from being freed up. But we have a ref on the page and once
278 * that page is locked, the mapping is pinned.
280 * We're allowed to run sleeping lock_page() here because we know the caller has
283 static void handle_write_error(struct address_space *mapping,
284 struct page *page, int error)
287 if (page_mapping(page) == mapping) {
288 if (error == -ENOSPC)
289 set_bit(AS_ENOSPC, &mapping->flags);
291 set_bit(AS_EIO, &mapping->flags);
297 * pageout is called by shrink_list() for each dirty page. Calls ->writepage().
299 static pageout_t pageout(struct page *page, struct address_space *mapping)
302 * If the page is dirty, only perform writeback if that write
303 * will be non-blocking. To prevent this allocation from being
304 * stalled by pagecache activity. But note that there may be
305 * stalls if we need to run get_block(). We could test
306 * PagePrivate for that.
308 * If this process is currently in generic_file_write() against
309 * this page's queue, we can perform writeback even if that
312 * If the page is swapcache, write it back even if that would
313 * block, for some throttling. This happens by accident, because
314 * swap_backing_dev_info is bust: it doesn't reflect the
315 * congestion state of the swapdevs. Easy to fix, if needed.
316 * See swapfile.c:page_queue_congested().
318 if (!is_page_cache_freeable(page))
322 if (mapping->a_ops->writepage == NULL)
323 return PAGE_ACTIVATE;
324 if (!may_write_to_queue(mapping->backing_dev_info))
327 if (clear_page_dirty_for_io(page)) {
329 struct writeback_control wbc = {
330 .sync_mode = WB_SYNC_NONE,
331 .nr_to_write = SWAP_CLUSTER_MAX,
336 SetPageReclaim(page);
337 res = mapping->a_ops->writepage(page, &wbc);
339 handle_write_error(mapping, page, res);
340 if (res == WRITEPAGE_ACTIVATE) {
341 ClearPageReclaim(page);
342 return PAGE_ACTIVATE;
344 if (!PageWriteback(page)) {
345 /* synchronous write or broken a_ops? */
346 ClearPageReclaim(page);
356 * shrink_list adds the number of reclaimed pages to sc->nr_reclaimed
358 static int shrink_list(struct list_head *page_list, struct scan_control *sc)
360 LIST_HEAD(ret_pages);
361 struct pagevec freed_pvec;
367 pagevec_init(&freed_pvec, 1);
368 while (!list_empty(page_list)) {
369 struct address_space *mapping;
374 page = lru_to_page(page_list);
375 list_del(&page->lru);
377 if (TestSetPageLocked(page))
380 BUG_ON(PageActive(page));
383 /* Double the slab pressure for mapped and swapcache pages */
384 if (page_mapped(page) || PageSwapCache(page))
387 if (PageWriteback(page))
390 referenced = page_referenced(page, 1, sc->priority <= 0);
391 /* In active use or really unfreeable? Activate it. */
392 if (referenced && page_mapping_inuse(page))
393 goto activate_locked;
397 * Anonymous process memory has backing store?
398 * Try to allocate it some swap space here.
400 if (PageAnon(page) && !PageSwapCache(page)) {
401 if (!add_to_swap(page))
402 goto activate_locked;
404 #endif /* CONFIG_SWAP */
406 mapping = page_mapping(page);
407 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
408 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
411 * The page is mapped into the page tables of one or more
412 * processes. Try to unmap it here.
414 if (page_mapped(page) && mapping) {
415 switch (try_to_unmap(page)) {
417 goto activate_locked;
421 ; /* try to free the page below */
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;
480 if (!mapping && page_count(page) == 1)
485 goto keep_locked; /* truncate got there first */
487 spin_lock_irq(&mapping->tree_lock);
490 * The non-racy check for busy page. It is critical to check
491 * PageDirty _after_ making sure that the page is freeable and
492 * not in use by anybody. (pagecache + us == 2)
494 if (page_count(page) != 2 || PageDirty(page)) {
495 spin_unlock_irq(&mapping->tree_lock);
500 if (PageSwapCache(page)) {
501 swp_entry_t swap = { .val = page->private };
502 __delete_from_swap_cache(page);
503 spin_unlock_irq(&mapping->tree_lock);
505 __put_page(page); /* The pagecache ref */
508 #endif /* CONFIG_SWAP */
510 __remove_from_page_cache(page);
511 spin_unlock_irq(&mapping->tree_lock);
517 if (!pagevec_add(&freed_pvec, page))
518 __pagevec_release_nonlru(&freed_pvec);
527 list_add(&page->lru, &ret_pages);
528 BUG_ON(PageLRU(page));
530 list_splice(&ret_pages, page_list);
531 if (pagevec_count(&freed_pvec))
532 __pagevec_release_nonlru(&freed_pvec);
533 mod_page_state(pgactivate, pgactivate);
534 sc->nr_reclaimed += reclaimed;
539 * zone->lru_lock is heavily contented. We relieve it by quickly privatising
540 * a batch of pages and working on them outside the lock. Any pages which were
541 * not freed will be added back to the LRU.
543 * shrink_cache() adds the number of pages reclaimed to sc->nr_reclaimed
545 * For pagecache intensive workloads, the first loop here is the hottest spot
546 * in the kernel (apart from the copy_*_user functions).
548 static void shrink_cache(struct zone *zone, struct scan_control *sc)
550 LIST_HEAD(page_list);
552 int max_scan = sc->nr_to_scan, nr_pass;
553 unsigned int ckrm_flags = sc->ckrm_flags, bit_flag;
555 pagevec_init(&pvec, 1);
558 spin_lock_irq(&zone->lru_lock);
560 ckrm_get_reclaim_bits(&ckrm_flags, &bit_flag);
561 nr_pass = zone->nr_inactive;
562 while (max_scan > 0) {
568 while (nr_pass-- && nr_scan++ < SWAP_CLUSTER_MAX &&
569 !list_empty(&zone->inactive_list)) {
570 page = lru_to_page(&zone->inactive_list);
572 prefetchw_prev_lru_page(page,
573 &zone->inactive_list, flags);
575 if (!TestClearPageLRU(page))
577 list_del(&page->lru);
578 if (get_page_testone(page)) {
580 * It is being freed elsewhere
584 list_add(&page->lru, &zone->inactive_list);
586 } else if (bit_flag && !ckrm_kick_page(page, bit_flag)) {
589 #ifdef CONFIG_CKRM_MEM_LRUORDER_CHANGE
590 list_add_tail(&page->lru, &zone->inactive_list);
592 list_add(&page->lru, &zone->inactive_list);
596 list_add(&page->lru, &page_list);
597 ckrm_mem_dec_inactive(page);
600 zone->nr_inactive -= nr_taken;
601 spin_unlock_irq(&zone->lru_lock);
603 if ((bit_flag == 0) && (nr_taken == 0))
607 if (current_is_kswapd())
608 mod_page_state_zone(zone, pgscan_kswapd, nr_scan);
610 mod_page_state_zone(zone, pgscan_direct, nr_scan);
611 nr_freed = shrink_list(&page_list, sc);
612 if (current_is_kswapd())
613 mod_page_state(kswapd_steal, nr_freed);
614 mod_page_state_zone(zone, pgsteal, nr_freed);
615 sc->nr_to_reclaim -= nr_freed;
617 spin_lock_irq(&zone->lru_lock);
619 * Put back any unfreeable pages.
621 while (!list_empty(&page_list)) {
622 page = lru_to_page(&page_list);
623 if (TestSetPageLRU(page))
625 list_del(&page->lru);
626 if (PageActive(page))
627 add_page_to_active_list(zone, page);
629 add_page_to_inactive_list(zone, page);
630 if (!pagevec_add(&pvec, page)) {
631 spin_unlock_irq(&zone->lru_lock);
632 __pagevec_release(&pvec);
633 spin_lock_irq(&zone->lru_lock);
636 if (ckrm_flags && (nr_pass <= 0)) {
640 spin_unlock_irq(&zone->lru_lock);
642 pagevec_release(&pvec);
646 * This moves pages from the active list to the inactive list.
648 * We move them the other way if the page is referenced by one or more
649 * processes, from rmap.
651 * If the pages are mostly unmapped, the processing is fast and it is
652 * appropriate to hold zone->lru_lock across the whole operation. But if
653 * the pages are mapped, the processing is slow (page_referenced()) so we
654 * should drop zone->lru_lock around each page. It's impossible to balance
655 * this, so instead we remove the pages from the LRU while processing them.
656 * It is safe to rely on PG_active against the non-LRU pages in here because
657 * nobody will play with that bit on a non-LRU page.
659 * The downside is that we have to touch page->_count against each page.
660 * But we had to alter page->flags anyway.
663 refill_inactive_zone(struct zone *zone, struct scan_control *sc)
666 int pgdeactivate = 0;
668 int nr_pages = sc->nr_to_scan;
669 LIST_HEAD(l_hold); /* The pages which were snipped off */
670 LIST_HEAD(l_inactive); /* Pages to go onto the inactive_list */
671 LIST_HEAD(l_active); /* Pages to go onto the active_list */
674 int reclaim_mapped = 0;
678 unsigned int ckrm_flags = sc->ckrm_flags, bit_flag;
683 spin_lock_irq(&zone->lru_lock);
685 ckrm_get_reclaim_bits(&ckrm_flags, &bit_flag);
686 nr_pass = zone->nr_active;
687 while (pgscanned < nr_pages && !list_empty(&zone->active_list) &&
689 page = lru_to_page(&zone->active_list);
690 prefetchw_prev_lru_page(page, &zone->active_list, flags);
691 if (!TestClearPageLRU(page))
693 list_del(&page->lru);
694 if (get_page_testone(page)) {
696 * It was already free! release_pages() or put_page()
697 * are about to remove it from the LRU and free it. So
698 * put the refcount back and put the page back on the
703 list_add(&page->lru, &zone->active_list);
705 } else if (bit_flag && !ckrm_kick_page(page, bit_flag)) {
708 #ifdef CONFIG_CKRM_MEM_LRUORDER_CHANGE
709 list_add_tail(&page->lru, &zone->active_list);
711 list_add(&page->lru, &zone->active_list);
714 list_add(&page->lru, &l_hold);
715 ckrm_mem_dec_active(page);
719 if (!--nr_pass && ckrm_flags) {
723 zone->pages_scanned += pgscanned;
724 zone->nr_active -= pgmoved;
725 spin_unlock_irq(&zone->lru_lock);
728 * `distress' is a measure of how much trouble we're having reclaiming
729 * pages. 0 -> no problems. 100 -> great trouble.
731 distress = 100 >> zone->prev_priority;
734 * The point of this algorithm is to decide when to start reclaiming
735 * mapped memory instead of just pagecache. Work out how much memory
738 mapped_ratio = (sc->nr_mapped * 100) / total_memory;
741 * Now decide how much we really want to unmap some pages. The mapped
742 * ratio is downgraded - just because there's a lot of mapped memory
743 * doesn't necessarily mean that page reclaim isn't succeeding.
745 * The distress ratio is important - we don't want to start going oom.
747 * A 100% value of vm_swappiness overrides this algorithm altogether.
749 swap_tendency = mapped_ratio / 2 + distress + vm_swappiness;
752 * Now use this metric to decide whether to start moving mapped memory
753 * onto the inactive list.
755 if (swap_tendency >= 100)
758 while (!list_empty(&l_hold)) {
759 page = lru_to_page(&l_hold);
760 list_del(&page->lru);
761 if (page_mapped(page)) {
762 if (!reclaim_mapped ||
763 (total_swap_pages == 0 && PageAnon(page)) ||
764 page_referenced(page, 0, sc->priority <= 0)) {
765 list_add(&page->lru, &l_active);
769 list_add(&page->lru, &l_inactive);
772 pagevec_init(&pvec, 1);
774 spin_lock_irq(&zone->lru_lock);
775 while (!list_empty(&l_inactive)) {
776 page = lru_to_page(&l_inactive);
777 prefetchw_prev_lru_page(page, &l_inactive, flags);
778 if (TestSetPageLRU(page))
780 if (!TestClearPageActive(page))
782 list_move(&page->lru, &zone->inactive_list);
783 ckrm_mem_inc_inactive(page);
785 if (!pagevec_add(&pvec, page)) {
786 zone->nr_inactive += pgmoved;
787 spin_unlock_irq(&zone->lru_lock);
788 pgdeactivate += pgmoved;
790 if (buffer_heads_over_limit)
791 pagevec_strip(&pvec);
792 __pagevec_release(&pvec);
793 spin_lock_irq(&zone->lru_lock);
796 zone->nr_inactive += pgmoved;
797 pgdeactivate += pgmoved;
798 if (buffer_heads_over_limit) {
799 spin_unlock_irq(&zone->lru_lock);
800 pagevec_strip(&pvec);
801 spin_lock_irq(&zone->lru_lock);
805 while (!list_empty(&l_active)) {
806 page = lru_to_page(&l_active);
807 prefetchw_prev_lru_page(page, &l_active, flags);
808 if (TestSetPageLRU(page))
810 BUG_ON(!PageActive(page));
811 list_move(&page->lru, &zone->active_list);
812 ckrm_mem_inc_active(page);
814 if (!pagevec_add(&pvec, page)) {
815 zone->nr_active += pgmoved;
817 spin_unlock_irq(&zone->lru_lock);
818 __pagevec_release(&pvec);
819 spin_lock_irq(&zone->lru_lock);
822 zone->nr_active += pgmoved;
823 spin_unlock_irq(&zone->lru_lock);
824 pagevec_release(&pvec);
826 mod_page_state_zone(zone, pgrefill, pgscanned);
827 mod_page_state(pgdeactivate, pgdeactivate);
831 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
834 shrink_zone(struct zone *zone, struct scan_control *sc)
836 unsigned long nr_active;
837 unsigned long nr_inactive;
840 * Add one to `nr_to_scan' just to make sure that the kernel will
841 * slowly sift through the active list.
843 zone->nr_scan_active += (zone->nr_active >> sc->priority) + 1;
844 nr_active = zone->nr_scan_active;
845 if (nr_active >= SWAP_CLUSTER_MAX)
846 zone->nr_scan_active = 0;
850 zone->nr_scan_inactive += (zone->nr_inactive >> sc->priority) + 1;
851 nr_inactive = zone->nr_scan_inactive;
852 if (nr_inactive >= SWAP_CLUSTER_MAX)
853 zone->nr_scan_inactive = 0;
857 sc->nr_to_reclaim = SWAP_CLUSTER_MAX;
859 while (nr_active || nr_inactive) {
860 sc->ckrm_flags = ckrm_setup_reclamation();
862 sc->nr_to_scan = min(nr_active,
863 (unsigned long)SWAP_CLUSTER_MAX);
864 nr_active -= sc->nr_to_scan;
865 refill_inactive_zone(zone, sc);
869 sc->nr_to_scan = min(nr_inactive,
870 (unsigned long)SWAP_CLUSTER_MAX);
871 nr_inactive -= sc->nr_to_scan;
872 shrink_cache(zone, sc);
873 if (sc->nr_to_reclaim <= 0)
876 ckrm_teardown_reclamation();
880 #if defined(CONFIG_CKRM_RES_MEM) && defined(AT_LIMIT_SUPPORT)
881 // This function needs to be given more thought.
882 // Shrink the class to be at 90% of its limit
884 ckrm_shrink_class(ckrm_mem_res_t *cls)
886 struct scan_control sc;
888 int zindex = 0, active_credit = 0, inactive_credit = 0;
890 if (ckrm_test_set_shrink(cls)) { // set the SHRINK bit atomically
891 // if it is already set somebody is working on it. so... leave
894 sc.nr_mapped = read_page_state(nr_mapped);
896 sc.ckrm_flags = ckrm_get_reclaim_flags(cls);
898 sc.priority = 0; // always very high priority
900 for_each_zone(zone) {
901 int zone_total, zone_limit, active_limit, inactive_limit;
902 int active_over, inactive_over;
903 unsigned long nr_active, nr_inactive;
906 zone->temp_priority = zone->prev_priority;
907 zone->prev_priority = sc.priority;
909 zone_total = zone->nr_active + zone->nr_inactive + zone->free_pages;
911 temp = (u64) cls->pg_limit * zone_total;
912 do_div(temp, ckrm_tot_lru_pages);
913 zone_limit = (int) temp;
914 active_limit = (6 * zone_limit) / 10; // 2/3rd in active list
915 inactive_limit = (3 * zone_limit) / 10; // 1/3rd in inactive list
917 active_over = cls->nr_active[zindex] - active_limit + active_credit;
918 inactive_over = active_over +
919 (cls->nr_inactive[zindex] - inactive_limit) + inactive_credit;
921 if (active_over > 0) {
922 zone->nr_scan_active += active_over + 1;
923 nr_active = zone->nr_scan_active;
926 active_credit += active_over;
930 if (inactive_over > 0) {
931 zone->nr_scan_inactive += inactive_over;
932 nr_inactive = zone->nr_scan_inactive;
935 inactive_credit += inactive_over;
938 while (nr_active || nr_inactive) {
940 sc.nr_to_scan = min(nr_active,
941 (unsigned long)SWAP_CLUSTER_MAX);
942 nr_active -= sc.nr_to_scan;
943 refill_inactive_zone(zone, &sc);
947 sc.nr_to_scan = min(nr_inactive,
948 (unsigned long)SWAP_CLUSTER_MAX);
949 nr_inactive -= sc.nr_to_scan;
950 shrink_cache(zone, &sc);
951 if (sc.nr_to_reclaim <= 0)
955 zone->prev_priority = zone->temp_priority;
958 ckrm_clear_shrink(cls);
962 ckrm_shrink_classes(void)
966 spin_lock(&ckrm_mem_lock);
967 while (!ckrm_shrink_list_empty()) {
968 cls = list_entry(ckrm_shrink_list.next, ckrm_mem_res_t,
970 spin_unlock(&ckrm_mem_lock);
971 ckrm_shrink_class(cls);
972 spin_lock(&ckrm_mem_lock);
973 list_del(&cls->shrink_list);
974 cls->flags &= ~MEM_AT_LIMIT;
976 spin_unlock(&ckrm_mem_lock);
977 throttle_vm_writeout();
982 #if defined(CONFIG_CKRM_RES_MEM) && !defined(AT_LIMIT_SUPPORT)
983 #warning "disabling ckrm_at_limit -- setting ckrm_shrink_classes to noop "
986 #define ckrm_shrink_classes() do { } while(0)
990 * This is the direct reclaim path, for page-allocating processes. We only
991 * try to reclaim pages from zones which will satisfy the caller's allocation
994 * We reclaim from a zone even if that zone is over pages_high. Because:
995 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
997 * b) The zones may be over pages_high but they must go *over* pages_high to
998 * satisfy the `incremental min' zone defense algorithm.
1000 * Returns the number of reclaimed pages.
1002 * If a zone is deemed to be full of pinned pages then just give it a light
1003 * scan then give up on it.
1006 shrink_caches(struct zone **zones, struct scan_control *sc)
1010 for (i = 0; zones[i] != NULL; i++) {
1011 struct zone *zone = zones[i];
1013 if (zone->present_pages == 0)
1016 zone->temp_priority = sc->priority;
1017 if (zone->prev_priority > sc->priority)
1018 zone->prev_priority = sc->priority;
1020 if (zone->all_unreclaimable && sc->priority != DEF_PRIORITY)
1021 continue; /* Let kswapd poll it */
1023 shrink_zone(zone, sc);
1028 * This is the main entry point to direct page reclaim.
1030 * If a full scan of the inactive list fails to free enough memory then we
1031 * are "out of memory" and something needs to be killed.
1033 * If the caller is !__GFP_FS then the probability of a failure is reasonably
1034 * high - the zone may be full of dirty or under-writeback pages, which this
1035 * caller can't do much about. We kick pdflush and take explicit naps in the
1036 * hope that some of these pages can be written. But if the allocating task
1037 * holds filesystem locks which prevent writeout this might not work, and the
1038 * allocation attempt will fail.
1040 int try_to_free_pages(struct zone **zones,
1041 unsigned int gfp_mask, unsigned int order)
1045 int total_scanned = 0, total_reclaimed = 0;
1046 struct reclaim_state *reclaim_state = current->reclaim_state;
1047 struct scan_control sc;
1048 unsigned long lru_pages = 0;
1051 sc.gfp_mask = gfp_mask;
1052 sc.may_writepage = 0;
1054 inc_page_state(allocstall);
1056 for (i = 0; zones[i] != NULL; i++) {
1057 struct zone *zone = zones[i];
1059 zone->temp_priority = DEF_PRIORITY;
1060 lru_pages += zone->nr_active + zone->nr_inactive;
1063 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1064 sc.nr_mapped = read_page_state(nr_mapped);
1066 sc.nr_reclaimed = 0;
1067 sc.priority = priority;
1068 shrink_caches(zones, &sc);
1069 shrink_slab(sc.nr_scanned, gfp_mask, lru_pages);
1070 if (reclaim_state) {
1071 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
1072 reclaim_state->reclaimed_slab = 0;
1074 if (sc.nr_reclaimed >= SWAP_CLUSTER_MAX) {
1078 total_scanned += sc.nr_scanned;
1079 total_reclaimed += sc.nr_reclaimed;
1082 * Try to write back as many pages as we just scanned. This
1083 * tends to cause slow streaming writers to write data to the
1084 * disk smoothly, at the dirtying rate, which is nice. But
1085 * that's undesirable in laptop mode, where we *want* lumpy
1086 * writeout. So in laptop mode, write out the whole world.
1088 if (total_scanned > SWAP_CLUSTER_MAX + SWAP_CLUSTER_MAX/2) {
1089 wakeup_bdflush(laptop_mode ? 0 : total_scanned);
1090 sc.may_writepage = 1;
1093 /* Take a nap, wait for some writeback to complete */
1094 if (sc.nr_scanned && priority < DEF_PRIORITY - 2)
1095 blk_congestion_wait(WRITE, HZ/10);
1097 if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY))
1098 out_of_memory(gfp_mask);
1100 for (i = 0; zones[i] != 0; i++)
1101 zones[i]->prev_priority = zones[i]->temp_priority;
1106 * For kswapd, balance_pgdat() will work across all this node's zones until
1107 * they are all at pages_high.
1109 * If `nr_pages' is non-zero then it is the number of pages which are to be
1110 * reclaimed, regardless of the zone occupancies. This is a software suspend
1113 * Returns the number of pages which were actually freed.
1115 * There is special handling here for zones which are full of pinned pages.
1116 * This can happen if the pages are all mlocked, or if they are all used by
1117 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
1118 * What we do is to detect the case where all pages in the zone have been
1119 * scanned twice and there has been zero successful reclaim. Mark the zone as
1120 * dead and from now on, only perform a short scan. Basically we're polling
1121 * the zone for when the problem goes away.
1123 * kswapd scans the zones in the highmem->normal->dma direction. It skips
1124 * zones which have free_pages > pages_high, but once a zone is found to have
1125 * free_pages <= pages_high, we scan that zone and the lower zones regardless
1126 * of the number of free pages in the lower zones. This interoperates with
1127 * the page allocator fallback scheme to ensure that aging of pages is balanced
1130 static int balance_pgdat(pg_data_t *pgdat, int nr_pages)
1132 int to_free = nr_pages;
1136 int total_scanned, total_reclaimed;
1137 struct reclaim_state *reclaim_state = current->reclaim_state;
1138 struct scan_control sc;
1142 total_reclaimed = 0;
1143 sc.gfp_mask = GFP_KERNEL;
1144 sc.may_writepage = 0;
1145 sc.nr_mapped = read_page_state(nr_mapped);
1147 inc_page_state(pageoutrun);
1149 for (i = 0; i < pgdat->nr_zones; i++) {
1150 struct zone *zone = pgdat->node_zones + i;
1152 zone->temp_priority = DEF_PRIORITY;
1155 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1156 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
1157 unsigned long lru_pages = 0;
1161 if (nr_pages == 0) {
1163 * Scan in the highmem->dma direction for the highest
1164 * zone which needs scanning
1166 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
1167 struct zone *zone = pgdat->node_zones + i;
1169 if (zone->present_pages == 0)
1172 if (zone->all_unreclaimable &&
1173 priority != DEF_PRIORITY)
1176 if (zone->free_pages <= zone->pages_high) {
1183 end_zone = pgdat->nr_zones - 1;
1186 for (i = 0; i <= end_zone; i++) {
1187 struct zone *zone = pgdat->node_zones + i;
1189 lru_pages += zone->nr_active + zone->nr_inactive;
1193 * Now scan the zone in the dma->highmem direction, stopping
1194 * at the last zone which needs scanning.
1196 * We do this because the page allocator works in the opposite
1197 * direction. This prevents the page allocator from allocating
1198 * pages behind kswapd's direction of progress, which would
1199 * cause too much scanning of the lower zones.
1201 for (i = 0; i <= end_zone; i++) {
1202 struct zone *zone = pgdat->node_zones + i;
1204 if (zone->present_pages == 0)
1207 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1210 if (nr_pages == 0) { /* Not software suspend */
1211 if (zone->free_pages <= zone->pages_high)
1214 zone->temp_priority = priority;
1215 if (zone->prev_priority > priority)
1216 zone->prev_priority = priority;
1218 sc.nr_reclaimed = 0;
1219 sc.priority = priority;
1220 shrink_zone(zone, &sc);
1221 reclaim_state->reclaimed_slab = 0;
1222 shrink_slab(sc.nr_scanned, GFP_KERNEL, lru_pages);
1223 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
1224 total_reclaimed += sc.nr_reclaimed;
1225 total_scanned += sc.nr_scanned;
1226 if (zone->all_unreclaimable)
1228 if (zone->pages_scanned >= (zone->nr_active +
1229 zone->nr_inactive) * 4)
1230 zone->all_unreclaimable = 1;
1232 * If we've done a decent amount of scanning and
1233 * the reclaim ratio is low, start doing writepage
1234 * even in laptop mode
1236 if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
1237 total_scanned > total_reclaimed+total_reclaimed/2)
1238 sc.may_writepage = 1;
1240 if (nr_pages && to_free > total_reclaimed)
1241 continue; /* swsusp: need to do more work */
1243 break; /* kswapd: all done */
1245 * OK, kswapd is getting into trouble. Take a nap, then take
1246 * another pass across the zones.
1248 if (total_scanned && priority < DEF_PRIORITY - 2)
1249 blk_congestion_wait(WRITE, HZ/10);
1252 * We do this so kswapd doesn't build up large priorities for
1253 * example when it is freeing in parallel with allocators. It
1254 * matches the direct reclaim path behaviour in terms of impact
1255 * on zone->*_priority.
1257 if (total_reclaimed >= SWAP_CLUSTER_MAX)
1261 for (i = 0; i < pgdat->nr_zones; i++) {
1262 struct zone *zone = pgdat->node_zones + i;
1264 zone->prev_priority = zone->temp_priority;
1266 if (!all_zones_ok) {
1271 return total_reclaimed;
1275 * The background pageout daemon, started as a kernel thread
1276 * from the init process.
1278 * This basically trickles out pages so that we have _some_
1279 * free memory available even if there is no other activity
1280 * that frees anything up. This is needed for things like routing
1281 * etc, where we otherwise might have all activity going on in
1282 * asynchronous contexts that cannot page things out.
1284 * If there are applications that are active memory-allocators
1285 * (most normal use), this basically shouldn't matter.
1287 static int kswapd(void *p)
1289 pg_data_t *pgdat = (pg_data_t*)p;
1290 struct task_struct *tsk = current;
1292 struct reclaim_state reclaim_state = {
1293 .reclaimed_slab = 0,
1297 daemonize("kswapd%d", pgdat->node_id);
1298 cpumask = node_to_cpumask(pgdat->node_id);
1299 if (!cpus_empty(cpumask))
1300 set_cpus_allowed(tsk, cpumask);
1301 current->reclaim_state = &reclaim_state;
1304 * Tell the memory management that we're a "memory allocator",
1305 * and that if we need more memory we should get access to it
1306 * regardless (see "__alloc_pages()"). "kswapd" should
1307 * never get caught in the normal page freeing logic.
1309 * (Kswapd normally doesn't need memory anyway, but sometimes
1310 * you need a small amount of memory in order to be able to
1311 * page out something else, and this flag essentially protects
1312 * us from recursively trying to free more memory as we're
1313 * trying to free the first piece of memory in the first place).
1315 tsk->flags |= PF_MEMALLOC|PF_KSWAPD;
1318 if (current->flags & PF_FREEZE)
1319 refrigerator(PF_FREEZE);
1320 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
1322 finish_wait(&pgdat->kswapd_wait, &wait);
1324 if (!ckrm_shrink_list_empty())
1325 ckrm_shrink_classes();
1327 balance_pgdat(pgdat, 0);
1333 * A zone is low on free memory, so wake its kswapd task to service it.
1335 void wakeup_kswapd(struct zone *zone)
1337 if (zone->present_pages == 0)
1339 if ((zone->free_pages > zone->pages_low) && ckrm_shrink_list_empty())
1341 if (!waitqueue_active(&zone->zone_pgdat->kswapd_wait))
1343 wake_up_interruptible(&zone->zone_pgdat->kswapd_wait);
1348 * Try to free `nr_pages' of memory, system-wide. Returns the number of freed
1351 int shrink_all_memory(int nr_pages)
1354 int nr_to_free = nr_pages;
1356 struct reclaim_state reclaim_state = {
1357 .reclaimed_slab = 0,
1360 current->reclaim_state = &reclaim_state;
1361 for_each_pgdat(pgdat) {
1363 freed = balance_pgdat(pgdat, nr_to_free);
1365 nr_to_free -= freed;
1366 if (nr_to_free <= 0)
1369 current->reclaim_state = NULL;
1374 #ifdef CONFIG_HOTPLUG_CPU
1375 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1376 not required for correctness. So if the last cpu in a node goes
1377 away, we get changed to run anywhere: as the first one comes back,
1378 restore their cpu bindings. */
1379 static int __devinit cpu_callback(struct notifier_block *nfb,
1380 unsigned long action,
1386 if (action == CPU_ONLINE) {
1387 for_each_pgdat(pgdat) {
1388 mask = node_to_cpumask(pgdat->node_id);
1389 if (any_online_cpu(mask) != NR_CPUS)
1390 /* One of our CPUs online: restore mask */
1391 set_cpus_allowed(pgdat->kswapd, mask);
1396 #endif /* CONFIG_HOTPLUG_CPU */
1398 static int __init kswapd_init(void)
1402 for_each_pgdat(pgdat)
1404 = find_task_by_real_pid(kernel_thread(kswapd, pgdat, CLONE_KERNEL));
1405 total_memory = nr_free_pagecache_pages();
1406 hotcpu_notifier(cpu_callback, 0);
1410 module_init(kswapd_init)