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;
376 page = lru_to_page(page_list);
377 list_del(&page->lru);
379 if (TestSetPageLocked(page))
382 BUG_ON(PageActive(page));
384 if (PageWriteback(page))
388 /* Double the slab pressure for mapped and swapcache pages */
389 if (page_mapped(page) || PageSwapCache(page))
392 referenced = page_referenced(page, 1, sc->priority <= 0);
393 /* In active use or really unfreeable? Activate it. */
394 if (referenced && page_mapping_inuse(page))
395 goto activate_locked;
399 * Anonymous process memory has backing store?
400 * Try to allocate it some swap space here.
402 if (PageAnon(page) && !PageSwapCache(page)) {
403 if (!add_to_swap(page))
404 goto activate_locked;
406 #endif /* CONFIG_SWAP */
408 mapping = page_mapping(page);
409 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
410 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
413 * The page is mapped into the page tables of one or more
414 * processes. Try to unmap it here.
416 if (page_mapped(page) && mapping) {
417 switch (try_to_unmap(page)) {
419 goto activate_locked;
423 ; /* try to free the page below */
427 if (PageDirty(page)) {
432 if (laptop_mode && !sc->may_writepage)
435 /* Page is dirty, try to write it out here */
436 switch(pageout(page, mapping)) {
440 goto activate_locked;
442 if (PageWriteback(page) || PageDirty(page))
445 * A synchronous write - probably a ramdisk. Go
446 * ahead and try to reclaim the page.
448 if (TestSetPageLocked(page))
450 if (PageDirty(page) || PageWriteback(page))
452 mapping = page_mapping(page);
454 ; /* try to free the page below */
459 * If the page has buffers, try to free the buffer mappings
460 * associated with this page. If we succeed we try to free
463 * We do this even if the page is PageDirty().
464 * try_to_release_page() does not perform I/O, but it is
465 * possible for a page to have PageDirty set, but it is actually
466 * clean (all its buffers are clean). This happens if the
467 * buffers were written out directly, with submit_bh(). ext3
468 * will do this, as well as the blockdev mapping.
469 * try_to_release_page() will discover that cleanness and will
470 * drop the buffers and mark the page clean - it can be freed.
472 * Rarely, pages can have buffers and no ->mapping. These are
473 * the pages which were not successfully invalidated in
474 * truncate_complete_page(). We try to drop those buffers here
475 * and if that worked, and the page is no longer mapped into
476 * process address space (page_count == 1) it can be freed.
477 * Otherwise, leave the page on the LRU so it is swappable.
479 if (PagePrivate(page)) {
480 if (!try_to_release_page(page, sc->gfp_mask))
481 goto activate_locked;
482 if (!mapping && page_count(page) == 1)
487 goto keep_locked; /* truncate got there first */
489 spin_lock_irq(&mapping->tree_lock);
492 * The non-racy check for busy page. It is critical to check
493 * PageDirty _after_ making sure that the page is freeable and
494 * not in use by anybody. (pagecache + us == 2)
496 if (page_count(page) != 2 || PageDirty(page)) {
497 spin_unlock_irq(&mapping->tree_lock);
502 if (PageSwapCache(page)) {
503 swp_entry_t swap = { .val = page->private };
504 __delete_from_swap_cache(page);
505 spin_unlock_irq(&mapping->tree_lock);
507 __put_page(page); /* The pagecache ref */
510 #endif /* CONFIG_SWAP */
512 __remove_from_page_cache(page);
513 spin_unlock_irq(&mapping->tree_lock);
519 if (!pagevec_add(&freed_pvec, page))
520 __pagevec_release_nonlru(&freed_pvec);
529 list_add(&page->lru, &ret_pages);
530 BUG_ON(PageLRU(page));
532 list_splice(&ret_pages, page_list);
533 if (pagevec_count(&freed_pvec))
534 __pagevec_release_nonlru(&freed_pvec);
535 mod_page_state(pgactivate, pgactivate);
536 sc->nr_reclaimed += reclaimed;
541 * zone->lru_lock is heavily contented. We relieve it by quickly privatising
542 * a batch of pages and working on them outside the lock. Any pages which were
543 * not freed will be added back to the LRU.
545 * shrink_cache() adds the number of pages reclaimed to sc->nr_reclaimed
547 * For pagecache intensive workloads, the first loop here is the hottest spot
548 * in the kernel (apart from the copy_*_user functions).
550 static void shrink_cache(struct zone *zone, struct scan_control *sc)
552 LIST_HEAD(page_list);
554 int max_scan = sc->nr_to_scan, nr_pass;
555 unsigned int ckrm_flags = sc->ckrm_flags, bit_flag;
557 pagevec_init(&pvec, 1);
560 spin_lock_irq(&zone->lru_lock);
562 ckrm_get_reclaim_bits(&ckrm_flags, &bit_flag);
563 nr_pass = zone->nr_inactive;
564 while (max_scan > 0) {
570 while (nr_pass-- && nr_scan++ < SWAP_CLUSTER_MAX &&
571 !list_empty(&zone->inactive_list)) {
572 page = lru_to_page(&zone->inactive_list);
574 prefetchw_prev_lru_page(page,
575 &zone->inactive_list, flags);
577 if (!TestClearPageLRU(page))
579 list_del(&page->lru);
580 if (get_page_testone(page)) {
582 * It is being freed elsewhere
586 list_add(&page->lru, &zone->inactive_list);
588 } else if (bit_flag && !ckrm_kick_page(page, bit_flag)) {
591 #ifdef CONFIG_CKRM_MEM_LRUORDER_CHANGE
592 list_add_tail(&page->lru, &zone->inactive_list);
594 list_add(&page->lru, &zone->inactive_list);
598 list_add(&page->lru, &page_list);
599 ckrm_mem_dec_inactive(page);
602 zone->nr_inactive -= nr_taken;
603 zone->pages_scanned += nr_taken;
604 spin_unlock_irq(&zone->lru_lock);
606 if ((bit_flag == 0) && (nr_taken == 0))
610 if (current_is_kswapd())
611 mod_page_state_zone(zone, pgscan_kswapd, nr_scan);
613 mod_page_state_zone(zone, pgscan_direct, nr_scan);
614 nr_freed = shrink_list(&page_list, sc);
615 if (current_is_kswapd())
616 mod_page_state(kswapd_steal, nr_freed);
617 mod_page_state_zone(zone, pgsteal, nr_freed);
618 sc->nr_to_reclaim -= nr_freed;
620 spin_lock_irq(&zone->lru_lock);
622 * Put back any unfreeable pages.
624 while (!list_empty(&page_list)) {
625 page = lru_to_page(&page_list);
626 if (TestSetPageLRU(page))
628 list_del(&page->lru);
629 if (PageActive(page))
630 add_page_to_active_list(zone, page);
632 add_page_to_inactive_list(zone, page);
633 if (!pagevec_add(&pvec, page)) {
634 spin_unlock_irq(&zone->lru_lock);
635 __pagevec_release(&pvec);
636 spin_lock_irq(&zone->lru_lock);
639 if (ckrm_flags && (nr_pass <= 0)) {
643 spin_unlock_irq(&zone->lru_lock);
645 pagevec_release(&pvec);
649 * This moves pages from the active list to the inactive list.
651 * We move them the other way if the page is referenced by one or more
652 * processes, from rmap.
654 * If the pages are mostly unmapped, the processing is fast and it is
655 * appropriate to hold zone->lru_lock across the whole operation. But if
656 * the pages are mapped, the processing is slow (page_referenced()) so we
657 * should drop zone->lru_lock around each page. It's impossible to balance
658 * this, so instead we remove the pages from the LRU while processing them.
659 * It is safe to rely on PG_active against the non-LRU pages in here because
660 * nobody will play with that bit on a non-LRU page.
662 * The downside is that we have to touch page->_count against each page.
663 * But we had to alter page->flags anyway.
666 refill_inactive_zone(struct zone *zone, struct scan_control *sc)
669 int pgdeactivate = 0;
671 int nr_pages = sc->nr_to_scan;
672 LIST_HEAD(l_hold); /* The pages which were snipped off */
673 LIST_HEAD(l_inactive); /* Pages to go onto the inactive_list */
674 LIST_HEAD(l_active); /* Pages to go onto the active_list */
677 int reclaim_mapped = 0;
681 unsigned int ckrm_flags = sc->ckrm_flags, bit_flag;
686 spin_lock_irq(&zone->lru_lock);
688 ckrm_get_reclaim_bits(&ckrm_flags, &bit_flag);
689 nr_pass = zone->nr_active;
690 while (pgscanned < nr_pages && !list_empty(&zone->active_list) &&
692 page = lru_to_page(&zone->active_list);
693 prefetchw_prev_lru_page(page, &zone->active_list, flags);
694 if (!TestClearPageLRU(page))
696 list_del(&page->lru);
697 if (get_page_testone(page)) {
699 * It was already free! release_pages() or put_page()
700 * are about to remove it from the LRU and free it. So
701 * put the refcount back and put the page back on the
706 list_add(&page->lru, &zone->active_list);
708 } else if (bit_flag && !ckrm_kick_page(page, bit_flag)) {
711 #ifdef CONFIG_CKRM_MEM_LRUORDER_CHANGE
712 list_add_tail(&page->lru, &zone->active_list);
714 list_add(&page->lru, &zone->active_list);
717 list_add(&page->lru, &l_hold);
718 ckrm_mem_dec_active(page);
722 if (!--nr_pass && ckrm_flags) {
726 zone->nr_active -= pgmoved;
727 spin_unlock_irq(&zone->lru_lock);
730 * `distress' is a measure of how much trouble we're having reclaiming
731 * pages. 0 -> no problems. 100 -> great trouble.
733 distress = 100 >> zone->prev_priority;
736 * The point of this algorithm is to decide when to start reclaiming
737 * mapped memory instead of just pagecache. Work out how much memory
740 mapped_ratio = (sc->nr_mapped * 100) / total_memory;
743 * Now decide how much we really want to unmap some pages. The mapped
744 * ratio is downgraded - just because there's a lot of mapped memory
745 * doesn't necessarily mean that page reclaim isn't succeeding.
747 * The distress ratio is important - we don't want to start going oom.
749 * A 100% value of vm_swappiness overrides this algorithm altogether.
751 swap_tendency = mapped_ratio / 2 + distress + vm_swappiness;
754 * Now use this metric to decide whether to start moving mapped memory
755 * onto the inactive list.
757 if (swap_tendency >= 100)
760 while (!list_empty(&l_hold)) {
762 page = lru_to_page(&l_hold);
763 list_del(&page->lru);
764 if (page_mapped(page)) {
765 if (!reclaim_mapped ||
766 (total_swap_pages == 0 && PageAnon(page)) ||
767 page_referenced(page, 0, sc->priority <= 0)) {
768 list_add(&page->lru, &l_active);
772 list_add(&page->lru, &l_inactive);
775 pagevec_init(&pvec, 1);
777 spin_lock_irq(&zone->lru_lock);
778 while (!list_empty(&l_inactive)) {
779 page = lru_to_page(&l_inactive);
780 prefetchw_prev_lru_page(page, &l_inactive, flags);
781 if (TestSetPageLRU(page))
783 if (!TestClearPageActive(page))
785 list_move(&page->lru, &zone->inactive_list);
786 ckrm_mem_inc_inactive(page);
788 if (!pagevec_add(&pvec, page)) {
789 zone->nr_inactive += pgmoved;
790 spin_unlock_irq(&zone->lru_lock);
791 pgdeactivate += pgmoved;
793 if (buffer_heads_over_limit)
794 pagevec_strip(&pvec);
795 __pagevec_release(&pvec);
796 spin_lock_irq(&zone->lru_lock);
799 zone->nr_inactive += pgmoved;
800 pgdeactivate += pgmoved;
801 if (buffer_heads_over_limit) {
802 spin_unlock_irq(&zone->lru_lock);
803 pagevec_strip(&pvec);
804 spin_lock_irq(&zone->lru_lock);
808 while (!list_empty(&l_active)) {
809 page = lru_to_page(&l_active);
810 prefetchw_prev_lru_page(page, &l_active, flags);
811 if (TestSetPageLRU(page))
813 BUG_ON(!PageActive(page));
814 list_move(&page->lru, &zone->active_list);
815 ckrm_mem_inc_active(page);
817 if (!pagevec_add(&pvec, page)) {
818 zone->nr_active += pgmoved;
820 spin_unlock_irq(&zone->lru_lock);
821 __pagevec_release(&pvec);
822 spin_lock_irq(&zone->lru_lock);
825 zone->nr_active += pgmoved;
826 spin_unlock_irq(&zone->lru_lock);
827 pagevec_release(&pvec);
829 mod_page_state_zone(zone, pgrefill, pgscanned);
830 mod_page_state(pgdeactivate, pgdeactivate);
834 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
837 shrink_zone(struct zone *zone, struct scan_control *sc)
839 unsigned long nr_active;
840 unsigned long nr_inactive;
843 * Add one to `nr_to_scan' just to make sure that the kernel will
844 * slowly sift through the active list.
846 zone->nr_scan_active += (zone->nr_active >> sc->priority) + 1;
847 nr_active = zone->nr_scan_active;
848 if (nr_active >= SWAP_CLUSTER_MAX)
849 zone->nr_scan_active = 0;
853 zone->nr_scan_inactive += (zone->nr_inactive >> sc->priority) + 1;
854 nr_inactive = zone->nr_scan_inactive;
855 if (nr_inactive >= SWAP_CLUSTER_MAX)
856 zone->nr_scan_inactive = 0;
860 sc->nr_to_reclaim = SWAP_CLUSTER_MAX;
862 while (nr_active || nr_inactive) {
863 sc->ckrm_flags = ckrm_setup_reclamation();
865 sc->nr_to_scan = min(nr_active,
866 (unsigned long)SWAP_CLUSTER_MAX);
867 nr_active -= sc->nr_to_scan;
868 refill_inactive_zone(zone, sc);
872 sc->nr_to_scan = min(nr_inactive,
873 (unsigned long)SWAP_CLUSTER_MAX);
874 nr_inactive -= sc->nr_to_scan;
875 shrink_cache(zone, sc);
876 if (sc->nr_to_reclaim <= 0)
879 ckrm_teardown_reclamation();
883 #if defined(CONFIG_CKRM_RES_MEM) && defined(AT_LIMIT_SUPPORT)
884 // This function needs to be given more thought.
885 // Shrink the class to be at 90% of its limit
887 ckrm_shrink_class(ckrm_mem_res_t *cls)
889 struct scan_control sc;
891 int zindex = 0, active_credit = 0, inactive_credit = 0;
893 if (ckrm_test_set_shrink(cls)) { // set the SHRINK bit atomically
894 // if it is already set somebody is working on it. so... leave
897 sc.nr_mapped = read_page_state(nr_mapped);
899 sc.ckrm_flags = ckrm_get_reclaim_flags(cls);
901 sc.priority = 0; // always very high priority
903 for_each_zone(zone) {
904 int zone_total, zone_limit, active_limit, inactive_limit;
905 int active_over, inactive_over;
906 unsigned long nr_active, nr_inactive;
909 zone->temp_priority = zone->prev_priority;
910 zone->prev_priority = sc.priority;
912 zone_total = zone->nr_active + zone->nr_inactive + zone->free_pages;
914 temp = (u64) cls->pg_limit * zone_total;
915 do_div(temp, ckrm_tot_lru_pages);
916 zone_limit = (int) temp;
917 active_limit = (6 * zone_limit) / 10; // 2/3rd in active list
918 inactive_limit = (3 * zone_limit) / 10; // 1/3rd in inactive list
920 active_over = cls->nr_active[zindex] - active_limit + active_credit;
921 inactive_over = active_over +
922 (cls->nr_inactive[zindex] - inactive_limit) + inactive_credit;
924 if (active_over > 0) {
925 zone->nr_scan_active += active_over + 1;
926 nr_active = zone->nr_scan_active;
929 active_credit += active_over;
933 if (inactive_over > 0) {
934 zone->nr_scan_inactive += inactive_over;
935 nr_inactive = zone->nr_scan_inactive;
938 inactive_credit += inactive_over;
941 while (nr_active || nr_inactive) {
943 sc.nr_to_scan = min(nr_active,
944 (unsigned long)SWAP_CLUSTER_MAX);
945 nr_active -= sc.nr_to_scan;
946 refill_inactive_zone(zone, &sc);
950 sc.nr_to_scan = min(nr_inactive,
951 (unsigned long)SWAP_CLUSTER_MAX);
952 nr_inactive -= sc.nr_to_scan;
953 shrink_cache(zone, &sc);
954 if (sc.nr_to_reclaim <= 0)
958 zone->prev_priority = zone->temp_priority;
961 ckrm_clear_shrink(cls);
965 ckrm_shrink_classes(void)
969 spin_lock(&ckrm_mem_lock);
970 while (!ckrm_shrink_list_empty()) {
971 cls = list_entry(ckrm_shrink_list.next, ckrm_mem_res_t,
973 spin_unlock(&ckrm_mem_lock);
974 ckrm_shrink_class(cls);
975 spin_lock(&ckrm_mem_lock);
976 list_del(&cls->shrink_list);
977 cls->flags &= ~MEM_AT_LIMIT;
979 spin_unlock(&ckrm_mem_lock);
980 throttle_vm_writeout();
985 #if defined(CONFIG_CKRM_RES_MEM) && !defined(AT_LIMIT_SUPPORT)
986 #warning "disabling ckrm_at_limit -- setting ckrm_shrink_classes to noop "
989 #define ckrm_shrink_classes() do { } while(0)
993 * This is the direct reclaim path, for page-allocating processes. We only
994 * try to reclaim pages from zones which will satisfy the caller's allocation
997 * We reclaim from a zone even if that zone is over pages_high. Because:
998 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
1000 * b) The zones may be over pages_high but they must go *over* pages_high to
1001 * satisfy the `incremental min' zone defense algorithm.
1003 * Returns the number of reclaimed pages.
1005 * If a zone is deemed to be full of pinned pages then just give it a light
1006 * scan then give up on it.
1009 shrink_caches(struct zone **zones, struct scan_control *sc)
1013 for (i = 0; zones[i] != NULL; i++) {
1014 struct zone *zone = zones[i];
1016 if (zone->present_pages == 0)
1019 zone->temp_priority = sc->priority;
1020 if (zone->prev_priority > sc->priority)
1021 zone->prev_priority = sc->priority;
1023 if (zone->all_unreclaimable && sc->priority != DEF_PRIORITY)
1024 continue; /* Let kswapd poll it */
1026 shrink_zone(zone, sc);
1031 * This is the main entry point to direct page reclaim.
1033 * If a full scan of the inactive list fails to free enough memory then we
1034 * are "out of memory" and something needs to be killed.
1036 * If the caller is !__GFP_FS then the probability of a failure is reasonably
1037 * high - the zone may be full of dirty or under-writeback pages, which this
1038 * caller can't do much about. We kick pdflush and take explicit naps in the
1039 * hope that some of these pages can be written. But if the allocating task
1040 * holds filesystem locks which prevent writeout this might not work, and the
1041 * allocation attempt will fail.
1043 int try_to_free_pages(struct zone **zones,
1044 unsigned int gfp_mask, unsigned int order)
1048 int total_scanned = 0, total_reclaimed = 0;
1049 struct reclaim_state *reclaim_state = current->reclaim_state;
1050 struct scan_control sc;
1051 unsigned long lru_pages = 0;
1054 sc.gfp_mask = gfp_mask;
1055 sc.may_writepage = 0;
1057 inc_page_state(allocstall);
1059 for (i = 0; zones[i] != NULL; i++) {
1060 struct zone *zone = zones[i];
1062 zone->temp_priority = DEF_PRIORITY;
1063 lru_pages += zone->nr_active + zone->nr_inactive;
1066 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1067 sc.nr_mapped = read_page_state(nr_mapped);
1069 sc.nr_reclaimed = 0;
1070 sc.priority = priority;
1071 shrink_caches(zones, &sc);
1072 shrink_slab(sc.nr_scanned, gfp_mask, lru_pages);
1073 if (reclaim_state) {
1074 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
1075 reclaim_state->reclaimed_slab = 0;
1077 if (sc.nr_reclaimed >= SWAP_CLUSTER_MAX) {
1081 total_scanned += sc.nr_scanned;
1082 total_reclaimed += sc.nr_reclaimed;
1085 * Try to write back as many pages as we just scanned. This
1086 * tends to cause slow streaming writers to write data to the
1087 * disk smoothly, at the dirtying rate, which is nice. But
1088 * that's undesirable in laptop mode, where we *want* lumpy
1089 * writeout. So in laptop mode, write out the whole world.
1091 if (total_scanned > SWAP_CLUSTER_MAX + SWAP_CLUSTER_MAX/2) {
1092 wakeup_bdflush(laptop_mode ? 0 : total_scanned);
1093 sc.may_writepage = 1;
1096 /* Take a nap, wait for some writeback to complete */
1097 if (sc.nr_scanned && priority < DEF_PRIORITY - 2)
1098 blk_congestion_wait(WRITE, HZ/10);
1100 if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY))
1101 out_of_memory(gfp_mask);
1103 for (i = 0; zones[i] != 0; i++)
1104 zones[i]->prev_priority = zones[i]->temp_priority;
1109 * For kswapd, balance_pgdat() will work across all this node's zones until
1110 * they are all at pages_high.
1112 * If `nr_pages' is non-zero then it is the number of pages which are to be
1113 * reclaimed, regardless of the zone occupancies. This is a software suspend
1116 * Returns the number of pages which were actually freed.
1118 * There is special handling here for zones which are full of pinned pages.
1119 * This can happen if the pages are all mlocked, or if they are all used by
1120 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
1121 * What we do is to detect the case where all pages in the zone have been
1122 * scanned twice and there has been zero successful reclaim. Mark the zone as
1123 * dead and from now on, only perform a short scan. Basically we're polling
1124 * the zone for when the problem goes away.
1126 * kswapd scans the zones in the highmem->normal->dma direction. It skips
1127 * zones which have free_pages > pages_high, but once a zone is found to have
1128 * free_pages <= pages_high, we scan that zone and the lower zones regardless
1129 * of the number of free pages in the lower zones. This interoperates with
1130 * the page allocator fallback scheme to ensure that aging of pages is balanced
1133 static int balance_pgdat(pg_data_t *pgdat, int nr_pages)
1135 int to_free = nr_pages;
1139 int total_scanned, total_reclaimed;
1140 struct reclaim_state *reclaim_state = current->reclaim_state;
1141 struct scan_control sc;
1145 total_reclaimed = 0;
1146 sc.gfp_mask = GFP_KERNEL;
1147 sc.may_writepage = 0;
1148 sc.nr_mapped = read_page_state(nr_mapped);
1150 inc_page_state(pageoutrun);
1152 for (i = 0; i < pgdat->nr_zones; i++) {
1153 struct zone *zone = pgdat->node_zones + i;
1155 zone->temp_priority = DEF_PRIORITY;
1158 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1159 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
1160 unsigned long lru_pages = 0;
1164 if (nr_pages == 0) {
1166 * Scan in the highmem->dma direction for the highest
1167 * zone which needs scanning
1169 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
1170 struct zone *zone = pgdat->node_zones + i;
1172 if (zone->present_pages == 0)
1175 if (zone->all_unreclaimable &&
1176 priority != DEF_PRIORITY)
1179 if (zone->free_pages <= zone->pages_high) {
1186 end_zone = pgdat->nr_zones - 1;
1189 for (i = 0; i <= end_zone; i++) {
1190 struct zone *zone = pgdat->node_zones + i;
1192 lru_pages += zone->nr_active + zone->nr_inactive;
1196 * Now scan the zone in the dma->highmem direction, stopping
1197 * at the last zone which needs scanning.
1199 * We do this because the page allocator works in the opposite
1200 * direction. This prevents the page allocator from allocating
1201 * pages behind kswapd's direction of progress, which would
1202 * cause too much scanning of the lower zones.
1204 for (i = 0; i <= end_zone; i++) {
1205 struct zone *zone = pgdat->node_zones + i;
1207 if (zone->present_pages == 0)
1210 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1213 if (nr_pages == 0) { /* Not software suspend */
1214 if (zone->free_pages <= zone->pages_high)
1217 zone->temp_priority = priority;
1218 if (zone->prev_priority > priority)
1219 zone->prev_priority = priority;
1221 sc.nr_reclaimed = 0;
1222 sc.priority = priority;
1223 shrink_zone(zone, &sc);
1224 reclaim_state->reclaimed_slab = 0;
1225 shrink_slab(sc.nr_scanned, GFP_KERNEL, lru_pages);
1226 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
1227 total_reclaimed += sc.nr_reclaimed;
1228 if (zone->all_unreclaimable)
1230 if (zone->pages_scanned >= (zone->nr_active +
1231 zone->nr_inactive) * 4)
1232 zone->all_unreclaimable = 1;
1234 * If we've done a decent amount of scanning and
1235 * the reclaim ratio is low, start doing writepage
1236 * even in laptop mode
1238 if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
1239 total_scanned > total_reclaimed+total_reclaimed/2)
1240 sc.may_writepage = 1;
1242 if (nr_pages && to_free > total_reclaimed)
1243 continue; /* swsusp: need to do more work */
1245 break; /* kswapd: all done */
1247 * OK, kswapd is getting into trouble. Take a nap, then take
1248 * another pass across the zones.
1250 if (total_scanned && priority < DEF_PRIORITY - 2)
1251 blk_congestion_wait(WRITE, HZ/10);
1254 * We do this so kswapd doesn't build up large priorities for
1255 * example when it is freeing in parallel with allocators. It
1256 * matches the direct reclaim path behaviour in terms of impact
1257 * on zone->*_priority.
1259 if (total_reclaimed >= SWAP_CLUSTER_MAX)
1263 for (i = 0; i < pgdat->nr_zones; i++) {
1264 struct zone *zone = pgdat->node_zones + i;
1266 zone->prev_priority = zone->temp_priority;
1268 if (!all_zones_ok) {
1273 return total_reclaimed;
1277 * The background pageout daemon, started as a kernel thread
1278 * from the init process.
1280 * This basically trickles out pages so that we have _some_
1281 * free memory available even if there is no other activity
1282 * that frees anything up. This is needed for things like routing
1283 * etc, where we otherwise might have all activity going on in
1284 * asynchronous contexts that cannot page things out.
1286 * If there are applications that are active memory-allocators
1287 * (most normal use), this basically shouldn't matter.
1289 static int kswapd(void *p)
1291 pg_data_t *pgdat = (pg_data_t*)p;
1292 struct task_struct *tsk = current;
1294 struct reclaim_state reclaim_state = {
1295 .reclaimed_slab = 0,
1299 daemonize("kswapd%d", pgdat->node_id);
1300 cpumask = node_to_cpumask(pgdat->node_id);
1301 if (!cpus_empty(cpumask))
1302 set_cpus_allowed(tsk, cpumask);
1303 current->reclaim_state = &reclaim_state;
1306 * Tell the memory management that we're a "memory allocator",
1307 * and that if we need more memory we should get access to it
1308 * regardless (see "__alloc_pages()"). "kswapd" should
1309 * never get caught in the normal page freeing logic.
1311 * (Kswapd normally doesn't need memory anyway, but sometimes
1312 * you need a small amount of memory in order to be able to
1313 * page out something else, and this flag essentially protects
1314 * us from recursively trying to free more memory as we're
1315 * trying to free the first piece of memory in the first place).
1317 tsk->flags |= PF_MEMALLOC|PF_KSWAPD;
1320 if (current->flags & PF_FREEZE)
1321 refrigerator(PF_FREEZE);
1322 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
1324 finish_wait(&pgdat->kswapd_wait, &wait);
1326 if (!ckrm_shrink_list_empty())
1327 ckrm_shrink_classes();
1329 balance_pgdat(pgdat, 0);
1335 * A zone is low on free memory, so wake its kswapd task to service it.
1337 void wakeup_kswapd(struct zone *zone)
1339 if (zone->present_pages == 0)
1341 if ((zone->free_pages > zone->pages_low) && ckrm_shrink_list_empty())
1343 if (!waitqueue_active(&zone->zone_pgdat->kswapd_wait))
1345 wake_up_interruptible(&zone->zone_pgdat->kswapd_wait);
1350 * Try to free `nr_pages' of memory, system-wide. Returns the number of freed
1353 int shrink_all_memory(int nr_pages)
1356 int nr_to_free = nr_pages;
1358 struct reclaim_state reclaim_state = {
1359 .reclaimed_slab = 0,
1362 current->reclaim_state = &reclaim_state;
1363 for_each_pgdat(pgdat) {
1365 freed = balance_pgdat(pgdat, nr_to_free);
1367 nr_to_free -= freed;
1368 if (nr_to_free <= 0)
1371 current->reclaim_state = NULL;
1376 #ifdef CONFIG_HOTPLUG_CPU
1377 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1378 not required for correctness. So if the last cpu in a node goes
1379 away, we get changed to run anywhere: as the first one comes back,
1380 restore their cpu bindings. */
1381 static int __devinit cpu_callback(struct notifier_block *nfb,
1382 unsigned long action,
1388 if (action == CPU_ONLINE) {
1389 for_each_pgdat(pgdat) {
1390 mask = node_to_cpumask(pgdat->node_id);
1391 if (any_online_cpu(mask) != NR_CPUS)
1392 /* One of our CPUs online: restore mask */
1393 set_cpus_allowed(pgdat->kswapd, mask);
1398 #endif /* CONFIG_HOTPLUG_CPU */
1400 static int __init kswapd_init(void)
1404 for_each_pgdat(pgdat)
1406 = find_task_by_real_pid(kernel_thread(kswapd, pgdat, CLONE_KERNEL));
1407 total_memory = nr_free_pagecache_pages();
1408 hotcpu_notifier(cpu_callback, 0);
1412 module_init(kswapd_init)