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 #ifndef AT_LIMIT_SUPPORT
43 #warning "ckrm_at_limit disabled due to problems with memory hog tests -- seting ckrm_shrink_list_empty to true"
44 #undef ckrm_shrink_list_empty
45 #define ckrm_shrink_list_empty() (1)
48 /* possible outcome of pageout() */
50 /* failed to write page out, page is locked */
52 /* move page to the active list, page is locked */
54 /* page has been sent to the disk successfully, page is unlocked */
56 /* page is clean and locked */
61 /* Ask refill_inactive_zone, or shrink_cache to scan this many pages */
62 unsigned long nr_to_scan;
64 /* Incremented by the number of inactive pages that were scanned */
65 unsigned long nr_scanned;
67 /* Incremented by the number of pages reclaimed */
68 unsigned long nr_reclaimed;
70 unsigned long nr_mapped; /* From page_state */
72 /* How many pages shrink_cache() should reclaim */
75 /* Ask shrink_caches, or shrink_zone to scan at this priority */
76 unsigned int priority;
78 /* This context's GFP mask */
79 unsigned int gfp_mask;
81 /* Flag used by CKRM */
82 unsigned int ckrm_flags;
88 * The list of shrinker callbacks used by to apply pressure to
93 struct list_head list;
94 int seeks; /* seeks to recreate an obj */
95 long nr; /* objs pending delete */
100 void try_to_clip_inodes(void);
103 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
105 #ifdef ARCH_HAS_PREFETCH
106 #define prefetch_prev_lru_page(_page, _base, _field) \
108 if ((_page)->lru.prev != _base) { \
111 prev = lru_to_page(&(_page->lru)); \
112 prefetch(&prev->_field); \
116 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
119 #ifdef ARCH_HAS_PREFETCHW
120 #define prefetchw_prev_lru_page(_page, _base, _field) \
122 if ((_page)->lru.prev != _base) { \
125 prev = lru_to_page(&(_page->lru)); \
126 prefetchw(&prev->_field); \
130 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
134 * From 0 .. 100. Higher means more swappy.
136 int vm_swappiness = 60;
137 static long total_memory;
139 static LIST_HEAD(shrinker_list);
140 static DECLARE_MUTEX(shrinker_sem);
143 * Add a shrinker callback to be called from the vm
145 struct shrinker *set_shrinker(int seeks, shrinker_t theshrinker)
147 struct shrinker *shrinker;
149 shrinker = kmalloc(sizeof(*shrinker), GFP_KERNEL);
151 shrinker->shrinker = theshrinker;
152 shrinker->seeks = seeks;
155 list_add(&shrinker->list, &shrinker_list);
160 EXPORT_SYMBOL(set_shrinker);
165 void remove_shrinker(struct shrinker *shrinker)
168 list_del(&shrinker->list);
172 EXPORT_SYMBOL(remove_shrinker);
174 #define SHRINK_BATCH 128
176 * Call the shrink functions to age shrinkable caches
178 * Here we assume it costs one seek to replace a lru page and that it also
179 * takes a seek to recreate a cache object. With this in mind we age equal
180 * percentages of the lru and ageable caches. This should balance the seeks
181 * generated by these structures.
183 * If the vm encounted mapped pages on the LRU it increase the pressure on
184 * slab to avoid swapping.
186 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
188 * `lru_pages' represents the number of on-LRU pages in all the zones which
189 * are eligible for the caller's allocation attempt. It is used for balancing
190 * slab reclaim versus page reclaim.
192 static int shrink_slab(unsigned long scanned, unsigned int gfp_mask,
193 unsigned long lru_pages)
195 struct shrinker *shrinker;
197 if (down_trylock(&shrinker_sem))
200 list_for_each_entry(shrinker, &shrinker_list, list) {
201 unsigned long long delta;
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 if (shrinker->nr <= SHRINK_BATCH)
212 while (shrinker->nr) {
213 long this_scan = shrinker->nr;
218 shrink_ret = (*shrinker->shrinker)(this_scan, gfp_mask);
219 mod_page_state(slabs_scanned, this_scan);
220 shrinker->nr -= this_scan;
221 if (shrink_ret == -1)
230 /* Must be called with page's rmap lock held. */
231 static inline int page_mapping_inuse(struct page *page)
233 struct address_space *mapping;
235 /* Page is in somebody's page tables. */
236 if (page_mapped(page))
239 /* Be more reluctant to reclaim swapcache than pagecache */
240 if (PageSwapCache(page))
243 mapping = page_mapping(page);
247 /* File is mmap'd by somebody? */
248 return mapping_mapped(mapping);
251 static inline int is_page_cache_freeable(struct page *page)
253 return page_count(page) - !!PagePrivate(page) == 2;
256 static int may_write_to_queue(struct backing_dev_info *bdi)
258 if (current_is_kswapd())
260 if (current_is_pdflush()) /* This is unlikely, but why not... */
262 if (!bdi_write_congested(bdi))
264 if (bdi == current->backing_dev_info)
270 * We detected a synchronous write error writing a page out. Probably
271 * -ENOSPC. We need to propagate that into the address_space for a subsequent
272 * fsync(), msync() or close().
274 * The tricky part is that after writepage we cannot touch the mapping: nothing
275 * prevents it from being freed up. But we have a ref on the page and once
276 * that page is locked, the mapping is pinned.
278 * We're allowed to run sleeping lock_page() here because we know the caller has
281 static void handle_write_error(struct address_space *mapping,
282 struct page *page, int error)
285 if (page_mapping(page) == mapping) {
286 if (error == -ENOSPC)
287 set_bit(AS_ENOSPC, &mapping->flags);
289 set_bit(AS_EIO, &mapping->flags);
295 * pageout is called by shrink_list() for each dirty page. Calls ->writepage().
297 static pageout_t pageout(struct page *page, struct address_space *mapping)
300 * If the page is dirty, only perform writeback if that write
301 * will be non-blocking. To prevent this allocation from being
302 * stalled by pagecache activity. But note that there may be
303 * stalls if we need to run get_block(). We could test
304 * PagePrivate for that.
306 * If this process is currently in generic_file_write() against
307 * this page's queue, we can perform writeback even if that
310 * If the page is swapcache, write it back even if that would
311 * block, for some throttling. This happens by accident, because
312 * swap_backing_dev_info is bust: it doesn't reflect the
313 * congestion state of the swapdevs. Easy to fix, if needed.
314 * See swapfile.c:page_queue_congested().
316 if (!is_page_cache_freeable(page))
320 if (mapping->a_ops->writepage == NULL)
321 return PAGE_ACTIVATE;
322 if (!may_write_to_queue(mapping->backing_dev_info))
325 if (clear_page_dirty_for_io(page)) {
327 struct writeback_control wbc = {
328 .sync_mode = WB_SYNC_NONE,
329 .nr_to_write = SWAP_CLUSTER_MAX,
334 SetPageReclaim(page);
335 res = mapping->a_ops->writepage(page, &wbc);
337 handle_write_error(mapping, page, res);
338 if (res == WRITEPAGE_ACTIVATE) {
339 ClearPageReclaim(page);
340 return PAGE_ACTIVATE;
342 if (!PageWriteback(page)) {
343 /* synchronous write or broken a_ops? */
344 ClearPageReclaim(page);
354 * shrink_list adds the number of reclaimed pages to sc->nr_reclaimed
356 static int shrink_list(struct list_head *page_list, struct scan_control *sc)
358 LIST_HEAD(ret_pages);
359 struct pagevec freed_pvec;
365 pagevec_init(&freed_pvec, 1);
366 while (!list_empty(page_list)) {
367 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));
382 if (PageWriteback(page))
386 /* Double the slab pressure for mapped and swapcache pages */
387 if (page_mapped(page) || PageSwapCache(page))
391 referenced = page_referenced(page);
392 if (referenced && page_mapping_inuse(page)) {
393 /* In active use or really unfreeable. Activate it. */
394 page_map_unlock(page);
395 goto activate_locked;
400 * Anonymous process memory has backing store?
401 * Try to allocate it some swap space here.
403 * XXX: implement swap clustering ?
405 if (PageAnon(page) && !PageSwapCache(page)) {
406 page_map_unlock(page);
407 if (!add_to_swap(page))
408 goto activate_locked;
411 #endif /* CONFIG_SWAP */
413 mapping = page_mapping(page);
414 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
415 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
418 * The page is mapped into the page tables of one or more
419 * processes. Try to unmap it here.
421 if (page_mapped(page) && mapping) {
422 switch (try_to_unmap(page)) {
424 page_map_unlock(page);
425 goto activate_locked;
427 page_map_unlock(page);
430 ; /* try to free the page below */
433 page_map_unlock(page);
435 if (PageDirty(page)) {
440 if (laptop_mode && !sc->may_writepage)
443 /* Page is dirty, try to write it out here */
444 switch(pageout(page, mapping)) {
448 goto activate_locked;
450 if (PageWriteback(page) || PageDirty(page))
453 * A synchronous write - probably a ramdisk. Go
454 * ahead and try to reclaim the page.
456 if (TestSetPageLocked(page))
458 if (PageDirty(page) || PageWriteback(page))
460 mapping = page_mapping(page);
462 ; /* try to free the page below */
467 * If the page has buffers, try to free the buffer mappings
468 * associated with this page. If we succeed we try to free
471 * We do this even if the page is PageDirty().
472 * try_to_release_page() does not perform I/O, but it is
473 * possible for a page to have PageDirty set, but it is actually
474 * clean (all its buffers are clean). This happens if the
475 * buffers were written out directly, with submit_bh(). ext3
476 * will do this, as well as the blockdev mapping.
477 * try_to_release_page() will discover that cleanness and will
478 * drop the buffers and mark the page clean - it can be freed.
480 * Rarely, pages can have buffers and no ->mapping. These are
481 * the pages which were not successfully invalidated in
482 * truncate_complete_page(). We try to drop those buffers here
483 * and if that worked, and the page is no longer mapped into
484 * process address space (page_count == 1) it can be freed.
485 * Otherwise, leave the page on the LRU so it is swappable.
487 if (PagePrivate(page)) {
488 if (!try_to_release_page(page, sc->gfp_mask))
489 goto activate_locked;
490 if (!mapping && page_count(page) == 1)
495 goto keep_locked; /* truncate got there first */
497 spin_lock_irq(&mapping->tree_lock);
500 * The non-racy check for busy page. It is critical to check
501 * PageDirty _after_ making sure that the page is freeable and
502 * not in use by anybody. (pagecache + us == 2)
504 if (page_count(page) != 2 || PageDirty(page)) {
505 spin_unlock_irq(&mapping->tree_lock);
510 if (PageSwapCache(page)) {
511 swp_entry_t swap = { .val = page->private };
512 __delete_from_swap_cache(page);
513 spin_unlock_irq(&mapping->tree_lock);
515 __put_page(page); /* The pagecache ref */
518 #endif /* CONFIG_SWAP */
520 __remove_from_page_cache(page);
521 spin_unlock_irq(&mapping->tree_lock);
527 if (!pagevec_add(&freed_pvec, page))
528 __pagevec_release_nonlru(&freed_pvec);
537 list_add(&page->lru, &ret_pages);
538 BUG_ON(PageLRU(page));
540 list_splice(&ret_pages, page_list);
541 if (pagevec_count(&freed_pvec))
542 __pagevec_release_nonlru(&freed_pvec);
543 mod_page_state(pgactivate, pgactivate);
544 sc->nr_reclaimed += reclaimed;
549 * zone->lru_lock is heavily contented. We relieve it by quickly privatising
550 * a batch of pages and working on them outside the lock. Any pages which were
551 * not freed will be added back to the LRU.
553 * shrink_cache() adds the number of pages reclaimed to sc->nr_reclaimed
555 * For pagecache intensive workloads, the first loop here is the hottest spot
556 * in the kernel (apart from the copy_*_user functions).
558 static void shrink_cache(struct zone *zone, struct scan_control *sc)
560 LIST_HEAD(page_list);
562 int max_scan = sc->nr_to_scan, nr_pass;
563 unsigned int ckrm_flags = sc->ckrm_flags, bit_flag;
565 pagevec_init(&pvec, 1);
568 spin_lock_irq(&zone->lru_lock);
570 ckrm_get_reclaim_bits(&ckrm_flags, &bit_flag);
571 nr_pass = zone->nr_inactive;
572 while (max_scan > 0) {
578 while (nr_pass-- && nr_scan++ < SWAP_CLUSTER_MAX &&
579 !list_empty(&zone->inactive_list)) {
580 page = lru_to_page(&zone->inactive_list);
582 prefetchw_prev_lru_page(page,
583 &zone->inactive_list, flags);
585 if (!TestClearPageLRU(page))
587 list_del(&page->lru);
588 if (get_page_testone(page)) {
590 * It is being freed elsewhere
594 list_add(&page->lru, &zone->inactive_list);
596 } else if (bit_flag && !ckrm_kick_page(page, bit_flag)) {
599 #ifdef CONFIG_CKRM_MEM_LRUORDER_CHANGE
600 list_add_tail(&page->lru, &zone->inactive_list);
602 list_add(&page->lru, &zone->inactive_list);
606 list_add(&page->lru, &page_list);
607 ckrm_mem_dec_inactive(page);
610 zone->nr_inactive -= nr_taken;
611 zone->pages_scanned += nr_taken;
612 spin_unlock_irq(&zone->lru_lock);
614 if ((bit_flag == 0) && (nr_taken == 0))
618 if (current_is_kswapd())
619 mod_page_state_zone(zone, pgscan_kswapd, nr_scan);
621 mod_page_state_zone(zone, pgscan_direct, nr_scan);
622 nr_freed = shrink_list(&page_list, sc);
623 if (current_is_kswapd())
624 mod_page_state(kswapd_steal, nr_freed);
625 mod_page_state_zone(zone, pgsteal, nr_freed);
626 sc->nr_to_reclaim -= nr_freed;
628 spin_lock_irq(&zone->lru_lock);
630 * Put back any unfreeable pages.
632 while (!list_empty(&page_list)) {
633 page = lru_to_page(&page_list);
634 if (TestSetPageLRU(page))
636 list_del(&page->lru);
637 if (PageActive(page))
638 add_page_to_active_list(zone, page);
640 add_page_to_inactive_list(zone, page);
641 if (!pagevec_add(&pvec, page)) {
642 spin_unlock_irq(&zone->lru_lock);
643 __pagevec_release(&pvec);
644 spin_lock_irq(&zone->lru_lock);
647 if (ckrm_flags && (nr_pass <= 0)) {
651 spin_unlock_irq(&zone->lru_lock);
653 pagevec_release(&pvec);
657 * This moves pages from the active list to the inactive list.
659 * We move them the other way if the page is referenced by one or more
660 * processes, from rmap.
662 * If the pages are mostly unmapped, the processing is fast and it is
663 * appropriate to hold zone->lru_lock across the whole operation. But if
664 * the pages are mapped, the processing is slow (page_referenced()) so we
665 * should drop zone->lru_lock around each page. It's impossible to balance
666 * this, so instead we remove the pages from the LRU while processing them.
667 * It is safe to rely on PG_active against the non-LRU pages in here because
668 * nobody will play with that bit on a non-LRU page.
670 * The downside is that we have to touch page->_count against each page.
671 * But we had to alter page->flags anyway.
674 refill_inactive_zone(struct zone *zone, struct scan_control *sc)
677 int pgdeactivate = 0;
679 int nr_pages = sc->nr_to_scan;
680 LIST_HEAD(l_hold); /* The pages which were snipped off */
681 LIST_HEAD(l_inactive); /* Pages to go onto the inactive_list */
682 LIST_HEAD(l_active); /* Pages to go onto the active_list */
685 int reclaim_mapped = 0;
689 unsigned int ckrm_flags = sc->ckrm_flags, bit_flag;
694 spin_lock_irq(&zone->lru_lock);
696 ckrm_get_reclaim_bits(&ckrm_flags, &bit_flag);
697 nr_pass = zone->nr_active;
698 while (pgscanned < nr_pages && !list_empty(&zone->active_list) &&
700 page = lru_to_page(&zone->active_list);
701 prefetchw_prev_lru_page(page, &zone->active_list, flags);
702 if (!TestClearPageLRU(page))
704 list_del(&page->lru);
705 if (get_page_testone(page)) {
707 * It was already free! release_pages() or put_page()
708 * are about to remove it from the LRU and free it. So
709 * put the refcount back and put the page back on the
714 list_add(&page->lru, &zone->active_list);
716 } else if (bit_flag && !ckrm_kick_page(page, bit_flag)) {
719 #ifdef CONFIG_CKRM_MEM_LRUORDER_CHANGE
720 list_add_tail(&page->lru, &zone->active_list);
722 list_add(&page->lru, &zone->active_list);
725 list_add(&page->lru, &l_hold);
726 ckrm_mem_dec_active(page);
730 if (!--nr_pass && ckrm_flags) {
734 zone->nr_active -= pgmoved;
735 spin_unlock_irq(&zone->lru_lock);
738 * `distress' is a measure of how much trouble we're having reclaiming
739 * pages. 0 -> no problems. 100 -> great trouble.
741 distress = 100 >> zone->prev_priority;
744 * The point of this algorithm is to decide when to start reclaiming
745 * mapped memory instead of just pagecache. Work out how much memory
748 mapped_ratio = (sc->nr_mapped * 100) / total_memory;
751 * Now decide how much we really want to unmap some pages. The mapped
752 * ratio is downgraded - just because there's a lot of mapped memory
753 * doesn't necessarily mean that page reclaim isn't succeeding.
755 * The distress ratio is important - we don't want to start going oom.
757 * A 100% value of vm_swappiness overrides this algorithm altogether.
759 swap_tendency = mapped_ratio / 2 + distress + vm_swappiness;
762 * Now use this metric to decide whether to start moving mapped memory
763 * onto the inactive list.
765 if (swap_tendency >= 100)
768 while (!list_empty(&l_hold)) {
770 page = lru_to_page(&l_hold);
771 list_del(&page->lru);
772 if (page_mapped(page)) {
773 if (!reclaim_mapped) {
774 list_add(&page->lru, &l_active);
778 if (page_referenced(page)) {
779 page_map_unlock(page);
780 list_add(&page->lru, &l_active);
783 page_map_unlock(page);
786 * FIXME: need to consider page_count(page) here if/when we
787 * reap orphaned pages via the LRU (Daniel's locking stuff)
789 if (total_swap_pages == 0 && PageAnon(page)) {
790 list_add(&page->lru, &l_active);
793 list_add(&page->lru, &l_inactive);
796 pagevec_init(&pvec, 1);
798 spin_lock_irq(&zone->lru_lock);
799 while (!list_empty(&l_inactive)) {
800 page = lru_to_page(&l_inactive);
801 prefetchw_prev_lru_page(page, &l_inactive, flags);
802 if (TestSetPageLRU(page))
804 if (!TestClearPageActive(page))
806 list_move(&page->lru, &zone->inactive_list);
807 ckrm_mem_inc_inactive(page);
809 if (!pagevec_add(&pvec, page)) {
810 zone->nr_inactive += pgmoved;
811 spin_unlock_irq(&zone->lru_lock);
812 pgdeactivate += pgmoved;
814 if (buffer_heads_over_limit)
815 pagevec_strip(&pvec);
816 __pagevec_release(&pvec);
817 spin_lock_irq(&zone->lru_lock);
820 zone->nr_inactive += pgmoved;
821 pgdeactivate += pgmoved;
822 if (buffer_heads_over_limit) {
823 spin_unlock_irq(&zone->lru_lock);
824 pagevec_strip(&pvec);
825 spin_lock_irq(&zone->lru_lock);
829 while (!list_empty(&l_active)) {
830 page = lru_to_page(&l_active);
831 prefetchw_prev_lru_page(page, &l_active, flags);
832 if (TestSetPageLRU(page))
834 BUG_ON(!PageActive(page));
835 list_move(&page->lru, &zone->active_list);
836 ckrm_mem_inc_active(page);
838 if (!pagevec_add(&pvec, page)) {
839 zone->nr_active += pgmoved;
841 spin_unlock_irq(&zone->lru_lock);
842 __pagevec_release(&pvec);
843 spin_lock_irq(&zone->lru_lock);
846 zone->nr_active += pgmoved;
847 spin_unlock_irq(&zone->lru_lock);
848 pagevec_release(&pvec);
850 mod_page_state_zone(zone, pgrefill, pgscanned);
851 mod_page_state(pgdeactivate, pgdeactivate);
855 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
858 shrink_zone(struct zone *zone, struct scan_control *sc)
860 unsigned long nr_active;
861 unsigned long nr_inactive;
864 * Add one to `nr_to_scan' just to make sure that the kernel will
865 * slowly sift through the active list.
867 zone->nr_scan_active += (zone->nr_active >> sc->priority) + 1;
868 nr_active = zone->nr_scan_active;
869 if (nr_active >= SWAP_CLUSTER_MAX)
870 zone->nr_scan_active = 0;
874 zone->nr_scan_inactive += (zone->nr_inactive >> sc->priority) + 1;
875 nr_inactive = zone->nr_scan_inactive;
876 if (nr_inactive >= SWAP_CLUSTER_MAX)
877 zone->nr_scan_inactive = 0;
881 sc->nr_to_reclaim = SWAP_CLUSTER_MAX;
883 while (nr_active || nr_inactive) {
884 sc->ckrm_flags = ckrm_setup_reclamation();
886 sc->nr_to_scan = min(nr_active,
887 (unsigned long)SWAP_CLUSTER_MAX);
888 nr_active -= sc->nr_to_scan;
889 refill_inactive_zone(zone, sc);
893 sc->nr_to_scan = min(nr_inactive,
894 (unsigned long)SWAP_CLUSTER_MAX);
895 nr_inactive -= sc->nr_to_scan;
896 shrink_cache(zone, sc);
897 if (sc->nr_to_reclaim <= 0)
900 ckrm_teardown_reclamation();
904 #if defined(CONFIG_CKRM_RES_MEM) && defined(AT_LIMIT_SUPPORT)
905 // This function needs to be given more thought.
906 // Shrink the class to be at 90% of its limit
908 ckrm_shrink_class(ckrm_mem_res_t *cls)
910 struct scan_control sc;
912 int zindex = 0, active_credit = 0, inactive_credit = 0;
914 if (ckrm_test_set_shrink(cls)) { // set the SHRINK bit atomically
915 // if it is already set somebody is working on it. so... leave
918 sc.nr_mapped = read_page_state(nr_mapped);
920 sc.ckrm_flags = ckrm_get_reclaim_flags(cls);
922 sc.priority = 0; // always very high priority
924 for_each_zone(zone) {
925 int zone_total, zone_limit, active_limit, inactive_limit;
926 int active_over, inactive_over;
927 unsigned long nr_active, nr_inactive;
930 zone->temp_priority = zone->prev_priority;
931 zone->prev_priority = sc.priority;
933 zone_total = zone->nr_active + zone->nr_inactive + zone->free_pages;
935 temp = (u64) cls->pg_limit * zone_total;
936 do_div(temp, ckrm_tot_lru_pages);
937 zone_limit = (int) temp;
938 active_limit = (6 * zone_limit) / 10; // 2/3rd in active list
939 inactive_limit = (3 * zone_limit) / 10; // 1/3rd in inactive list
941 active_over = cls->nr_active[zindex] - active_limit + active_credit;
942 inactive_over = active_over +
943 (cls->nr_inactive[zindex] - inactive_limit) + inactive_credit;
945 if (active_over > 0) {
946 zone->nr_scan_active += active_over + 1;
947 nr_active = zone->nr_scan_active;
950 active_credit += active_over;
954 if (inactive_over > 0) {
955 zone->nr_scan_inactive += inactive_over;
956 nr_inactive = zone->nr_scan_inactive;
959 inactive_credit += inactive_over;
962 while (nr_active || nr_inactive) {
964 sc.nr_to_scan = min(nr_active,
965 (unsigned long)SWAP_CLUSTER_MAX);
966 nr_active -= sc.nr_to_scan;
967 refill_inactive_zone(zone, &sc);
971 sc.nr_to_scan = min(nr_inactive,
972 (unsigned long)SWAP_CLUSTER_MAX);
973 nr_inactive -= sc.nr_to_scan;
974 shrink_cache(zone, &sc);
975 if (sc.nr_to_reclaim <= 0)
979 zone->prev_priority = zone->temp_priority;
982 ckrm_clear_shrink(cls);
986 ckrm_shrink_classes(void)
990 spin_lock(&ckrm_mem_lock);
991 while (!ckrm_shrink_list_empty()) {
992 cls = list_entry(ckrm_shrink_list.next, ckrm_mem_res_t,
994 spin_unlock(&ckrm_mem_lock);
995 ckrm_shrink_class(cls);
996 spin_lock(&ckrm_mem_lock);
997 list_del(&cls->shrink_list);
998 cls->flags &= ~MEM_AT_LIMIT;
1000 spin_unlock(&ckrm_mem_lock);
1005 #if defined(CONFIG_CKRM_RES_MEM) && !defined(AT_LIMIT_SUPPORT)
1006 #warning "disabling ckrm_at_limit -- setting ckrm_shrink_classes to noop "
1009 #define ckrm_shrink_classes() do { } while(0)
1013 * This is the direct reclaim path, for page-allocating processes. We only
1014 * try to reclaim pages from zones which will satisfy the caller's allocation
1017 * We reclaim from a zone even if that zone is over pages_high. Because:
1018 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
1020 * b) The zones may be over pages_high but they must go *over* pages_high to
1021 * satisfy the `incremental min' zone defense algorithm.
1023 * Returns the number of reclaimed pages.
1025 * If a zone is deemed to be full of pinned pages then just give it a light
1026 * scan then give up on it.
1029 shrink_caches(struct zone **zones, struct scan_control *sc)
1033 for (i = 0; zones[i] != NULL; i++) {
1034 struct zone *zone = zones[i];
1036 zone->temp_priority = sc->priority;
1037 if (zone->prev_priority > sc->priority)
1038 zone->prev_priority = sc->priority;
1040 if (zone->all_unreclaimable && sc->priority != DEF_PRIORITY)
1041 continue; /* Let kswapd poll it */
1043 shrink_zone(zone, sc);
1048 * This is the main entry point to direct page reclaim.
1050 * If a full scan of the inactive list fails to free enough memory then we
1051 * are "out of memory" and something needs to be killed.
1053 * If the caller is !__GFP_FS then the probability of a failure is reasonably
1054 * high - the zone may be full of dirty or under-writeback pages, which this
1055 * caller can't do much about. We kick pdflush and take explicit naps in the
1056 * hope that some of these pages can be written. But if the allocating task
1057 * holds filesystem locks which prevent writeout this might not work, and the
1058 * allocation attempt will fail.
1060 int try_to_free_pages(struct zone **zones,
1061 unsigned int gfp_mask, unsigned int order)
1065 int total_scanned = 0, total_reclaimed = 0;
1066 struct reclaim_state *reclaim_state = current->reclaim_state;
1067 struct scan_control sc;
1068 unsigned long lru_pages = 0;
1071 sc.gfp_mask = gfp_mask;
1072 sc.may_writepage = 0;
1074 inc_page_state(allocstall);
1076 for (i = 0; zones[i] != NULL; i++) {
1077 struct zone *zone = zones[i];
1079 zone->temp_priority = DEF_PRIORITY;
1080 lru_pages += zone->nr_active + zone->nr_inactive;
1083 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1084 sc.nr_mapped = read_page_state(nr_mapped);
1086 sc.nr_reclaimed = 0;
1087 sc.priority = priority;
1088 shrink_caches(zones, &sc);
1089 shrink_slab(sc.nr_scanned, gfp_mask, lru_pages);
1090 if (reclaim_state) {
1091 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
1092 reclaim_state->reclaimed_slab = 0;
1094 if (sc.nr_reclaimed >= SWAP_CLUSTER_MAX) {
1098 total_scanned += sc.nr_scanned;
1099 total_reclaimed += sc.nr_reclaimed;
1102 * Try to write back as many pages as we just scanned. This
1103 * tends to cause slow streaming writers to write data to the
1104 * disk smoothly, at the dirtying rate, which is nice. But
1105 * that's undesirable in laptop mode, where we *want* lumpy
1106 * writeout. So in laptop mode, write out the whole world.
1108 if (total_scanned > SWAP_CLUSTER_MAX + SWAP_CLUSTER_MAX/2) {
1109 wakeup_bdflush(laptop_mode ? 0 : total_scanned);
1110 sc.may_writepage = 1;
1113 /* Take a nap, wait for some writeback to complete */
1114 if (sc.nr_scanned && priority < DEF_PRIORITY - 2)
1115 blk_congestion_wait(WRITE, HZ/10);
1117 if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY))
1118 out_of_memory(gfp_mask);
1120 for (i = 0; zones[i] != 0; i++)
1121 zones[i]->prev_priority = zones[i]->temp_priority;
1126 * For kswapd, balance_pgdat() will work across all this node's zones until
1127 * they are all at pages_high.
1129 * If `nr_pages' is non-zero then it is the number of pages which are to be
1130 * reclaimed, regardless of the zone occupancies. This is a software suspend
1133 * Returns the number of pages which were actually freed.
1135 * There is special handling here for zones which are full of pinned pages.
1136 * This can happen if the pages are all mlocked, or if they are all used by
1137 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
1138 * What we do is to detect the case where all pages in the zone have been
1139 * scanned twice and there has been zero successful reclaim. Mark the zone as
1140 * dead and from now on, only perform a short scan. Basically we're polling
1141 * the zone for when the problem goes away.
1143 * kswapd scans the zones in the highmem->normal->dma direction. It skips
1144 * zones which have free_pages > pages_high, but once a zone is found to have
1145 * free_pages <= pages_high, we scan that zone and the lower zones regardless
1146 * of the number of free pages in the lower zones. This interoperates with
1147 * the page allocator fallback scheme to ensure that aging of pages is balanced
1150 static int balance_pgdat(pg_data_t *pgdat, int nr_pages)
1152 int to_free = nr_pages;
1155 int total_scanned = 0, total_reclaimed = 0;
1156 struct reclaim_state *reclaim_state = current->reclaim_state;
1157 struct scan_control sc;
1159 sc.gfp_mask = GFP_KERNEL;
1160 sc.may_writepage = 0;
1161 sc.nr_mapped = read_page_state(nr_mapped);
1163 inc_page_state(pageoutrun);
1165 for (i = 0; i < pgdat->nr_zones; i++) {
1166 struct zone *zone = pgdat->node_zones + i;
1168 zone->temp_priority = DEF_PRIORITY;
1171 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1172 int all_zones_ok = 1;
1173 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
1174 unsigned long lru_pages = 0;
1176 if (nr_pages == 0) {
1178 * Scan in the highmem->dma direction for the highest
1179 * zone which needs scanning
1181 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
1182 struct zone *zone = pgdat->node_zones + i;
1184 if (zone->all_unreclaimable &&
1185 priority != DEF_PRIORITY)
1188 if (zone->free_pages <= zone->pages_high) {
1195 end_zone = pgdat->nr_zones - 1;
1198 for (i = 0; i <= end_zone; i++) {
1199 struct zone *zone = pgdat->node_zones + i;
1201 lru_pages += zone->nr_active + zone->nr_inactive;
1205 * Now scan the zone in the dma->highmem direction, stopping
1206 * at the last zone which needs scanning.
1208 * We do this because the page allocator works in the opposite
1209 * direction. This prevents the page allocator from allocating
1210 * pages behind kswapd's direction of progress, which would
1211 * cause too much scanning of the lower zones.
1213 for (i = 0; i <= end_zone; i++) {
1214 struct zone *zone = pgdat->node_zones + i;
1216 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1219 if (nr_pages == 0) { /* Not software suspend */
1220 if (zone->free_pages <= zone->pages_high)
1223 zone->temp_priority = priority;
1224 if (zone->prev_priority > priority)
1225 zone->prev_priority = priority;
1227 sc.nr_reclaimed = 0;
1228 sc.priority = priority;
1229 shrink_zone(zone, &sc);
1230 reclaim_state->reclaimed_slab = 0;
1231 shrink_slab(sc.nr_scanned, GFP_KERNEL, lru_pages);
1232 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
1233 total_reclaimed += sc.nr_reclaimed;
1234 if (zone->all_unreclaimable)
1236 if (zone->pages_scanned > zone->present_pages * 2)
1237 zone->all_unreclaimable = 1;
1239 * If we've done a decent amount of scanning and
1240 * the reclaim ratio is low, start doing writepage
1241 * even in laptop mode
1243 if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
1244 total_scanned > total_reclaimed+total_reclaimed/2)
1245 sc.may_writepage = 1;
1247 if (nr_pages && to_free > total_reclaimed)
1248 continue; /* swsusp: need to do more work */
1250 break; /* kswapd: all done */
1252 * OK, kswapd is getting into trouble. Take a nap, then take
1253 * another pass across the zones.
1255 if (total_scanned && priority < DEF_PRIORITY - 2)
1256 blk_congestion_wait(WRITE, HZ/10);
1259 for (i = 0; i < pgdat->nr_zones; i++) {
1260 struct zone *zone = pgdat->node_zones + i;
1262 zone->prev_priority = zone->temp_priority;
1264 return total_reclaimed;
1268 * The background pageout daemon, started as a kernel thread
1269 * from the init process.
1271 * This basically trickles out pages so that we have _some_
1272 * free memory available even if there is no other activity
1273 * that frees anything up. This is needed for things like routing
1274 * etc, where we otherwise might have all activity going on in
1275 * asynchronous contexts that cannot page things out.
1277 * If there are applications that are active memory-allocators
1278 * (most normal use), this basically shouldn't matter.
1280 static int kswapd(void *p)
1282 pg_data_t *pgdat = (pg_data_t*)p;
1283 struct task_struct *tsk = current;
1285 struct reclaim_state reclaim_state = {
1286 .reclaimed_slab = 0,
1290 daemonize("kswapd%d", pgdat->node_id);
1291 cpumask = node_to_cpumask(pgdat->node_id);
1292 if (!cpus_empty(cpumask))
1293 set_cpus_allowed(tsk, cpumask);
1294 current->reclaim_state = &reclaim_state;
1297 * Tell the memory management that we're a "memory allocator",
1298 * and that if we need more memory we should get access to it
1299 * regardless (see "__alloc_pages()"). "kswapd" should
1300 * never get caught in the normal page freeing logic.
1302 * (Kswapd normally doesn't need memory anyway, but sometimes
1303 * you need a small amount of memory in order to be able to
1304 * page out something else, and this flag essentially protects
1305 * us from recursively trying to free more memory as we're
1306 * trying to free the first piece of memory in the first place).
1308 tsk->flags |= PF_MEMALLOC|PF_KSWAPD;
1311 if (current->flags & PF_FREEZE)
1312 refrigerator(PF_FREEZE);
1313 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
1315 finish_wait(&pgdat->kswapd_wait, &wait);
1316 try_to_clip_inodes();
1318 if (!ckrm_shrink_list_empty())
1319 ckrm_shrink_classes();
1321 balance_pgdat(pgdat, 0);
1327 * A zone is low on free memory, so wake its kswapd task to service it.
1329 void wakeup_kswapd(struct zone *zone)
1331 if ((zone->free_pages > zone->pages_low) && ckrm_shrink_list_empty())
1333 if (!waitqueue_active(&zone->zone_pgdat->kswapd_wait))
1335 wake_up_interruptible(&zone->zone_pgdat->kswapd_wait);
1340 * Try to free `nr_pages' of memory, system-wide. Returns the number of freed
1343 int shrink_all_memory(int nr_pages)
1346 int nr_to_free = nr_pages;
1348 struct reclaim_state reclaim_state = {
1349 .reclaimed_slab = 0,
1352 current->reclaim_state = &reclaim_state;
1353 for_each_pgdat(pgdat) {
1355 freed = balance_pgdat(pgdat, nr_to_free);
1357 nr_to_free -= freed;
1358 if (nr_to_free <= 0)
1361 current->reclaim_state = NULL;
1366 #ifdef CONFIG_HOTPLUG_CPU
1367 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1368 not required for correctness. So if the last cpu in a node goes
1369 away, we get changed to run anywhere: as the first one comes back,
1370 restore their cpu bindings. */
1371 static int __devinit cpu_callback(struct notifier_block *nfb,
1372 unsigned long action,
1378 if (action == CPU_ONLINE) {
1379 for_each_pgdat(pgdat) {
1380 mask = node_to_cpumask(pgdat->node_id);
1381 if (any_online_cpu(mask) != NR_CPUS)
1382 /* One of our CPUs online: restore mask */
1383 set_cpus_allowed(pgdat->kswapd, mask);
1388 #endif /* CONFIG_HOTPLUG_CPU */
1390 static int __init kswapd_init(void)
1394 for_each_pgdat(pgdat)
1396 = find_task_by_pid(kernel_thread(kswapd, pgdat, CLONE_KERNEL));
1397 total_memory = nr_free_pagecache_pages();
1398 hotcpu_notifier(cpu_callback, 0);
1402 module_init(kswapd_init)