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>
36 #include <linux/ckrm_mem.h>
38 #include <asm/tlbflush.h>
39 #include <asm/div64.h>
41 #include <linux/swapops.h>
43 /* possible outcome of pageout() */
45 /* failed to write page out, page is locked */
47 /* move page to the active list, page is locked */
49 /* page has been sent to the disk successfully, page is unlocked */
51 /* page is clean and locked */
56 /* Ask refill_inactive_zone, or shrink_cache to scan this many pages */
57 unsigned long nr_to_scan;
59 /* Incremented by the number of inactive pages that were scanned */
60 unsigned long nr_scanned;
62 /* Incremented by the number of pages reclaimed */
63 unsigned long nr_reclaimed;
65 unsigned long nr_mapped; /* From page_state */
67 /* How many pages shrink_cache() should reclaim */
70 /* Ask shrink_caches, or shrink_zone to scan at this priority */
71 unsigned int priority;
73 /* This context's GFP mask */
74 unsigned int gfp_mask;
80 * The list of shrinker callbacks used by to apply pressure to
85 struct list_head list;
86 int seeks; /* seeks to recreate an obj */
87 long nr; /* objs pending delete */
90 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
92 #ifdef ARCH_HAS_PREFETCH
93 #define prefetch_prev_lru_page(_page, _base, _field) \
95 if ((_page)->lru.prev != _base) { \
98 prev = lru_to_page(&(_page->lru)); \
99 prefetch(&prev->_field); \
103 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
106 #ifdef ARCH_HAS_PREFETCHW
107 #define prefetchw_prev_lru_page(_page, _base, _field) \
109 if ((_page)->lru.prev != _base) { \
112 prev = lru_to_page(&(_page->lru)); \
113 prefetchw(&prev->_field); \
117 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
121 * From 0 .. 100. Higher means more swappy.
123 int vm_swappiness = 60;
124 static long total_memory;
126 static LIST_HEAD(shrinker_list);
127 static DECLARE_RWSEM(shrinker_rwsem);
130 * Add a shrinker callback to be called from the vm
132 struct shrinker *set_shrinker(int seeks, shrinker_t theshrinker)
134 struct shrinker *shrinker;
136 shrinker = kmalloc(sizeof(*shrinker), GFP_KERNEL);
138 shrinker->shrinker = theshrinker;
139 shrinker->seeks = seeks;
141 down_write(&shrinker_rwsem);
142 list_add(&shrinker->list, &shrinker_list);
143 up_write(&shrinker_rwsem);
147 EXPORT_SYMBOL(set_shrinker);
152 void remove_shrinker(struct shrinker *shrinker)
154 down_write(&shrinker_rwsem);
155 list_del(&shrinker->list);
156 up_write(&shrinker_rwsem);
159 EXPORT_SYMBOL(remove_shrinker);
161 #define SHRINK_BATCH 128
163 * Call the shrink functions to age shrinkable caches
165 * Here we assume it costs one seek to replace a lru page and that it also
166 * takes a seek to recreate a cache object. With this in mind we age equal
167 * percentages of the lru and ageable caches. This should balance the seeks
168 * generated by these structures.
170 * If the vm encounted mapped pages on the LRU it increase the pressure on
171 * slab to avoid swapping.
173 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
175 * `lru_pages' represents the number of on-LRU pages in all the zones which
176 * are eligible for the caller's allocation attempt. It is used for balancing
177 * slab reclaim versus page reclaim.
179 static int shrink_slab(unsigned long scanned, unsigned int gfp_mask,
180 unsigned long lru_pages)
182 struct shrinker *shrinker;
185 scanned = SWAP_CLUSTER_MAX;
187 if (!down_read_trylock(&shrinker_rwsem))
190 list_for_each_entry(shrinker, &shrinker_list, list) {
191 unsigned long long delta;
192 unsigned long total_scan;
194 delta = (4 * scanned) / shrinker->seeks;
195 delta *= (*shrinker->shrinker)(0, gfp_mask);
196 do_div(delta, lru_pages + 1);
197 shrinker->nr += delta;
198 if (shrinker->nr < 0)
199 shrinker->nr = LONG_MAX; /* It wrapped! */
201 total_scan = shrinker->nr;
204 while (total_scan >= SHRINK_BATCH) {
205 long this_scan = SHRINK_BATCH;
208 shrink_ret = (*shrinker->shrinker)(this_scan, gfp_mask);
209 if (shrink_ret == -1)
211 mod_page_state(slabs_scanned, this_scan);
212 total_scan -= this_scan;
217 shrinker->nr += total_scan;
219 up_read(&shrinker_rwsem);
223 /* Called without lock on whether page is mapped, so answer is unstable */
224 static inline int page_mapping_inuse(struct page *page)
226 struct address_space *mapping;
228 /* Page is in somebody's page tables. */
229 if (page_mapped(page))
232 /* Be more reluctant to reclaim swapcache than pagecache */
233 if (PageSwapCache(page))
236 mapping = page_mapping(page);
240 /* File is mmap'd by somebody? */
241 return mapping_mapped(mapping);
244 static inline int is_page_cache_freeable(struct page *page)
246 return page_count(page) - !!PagePrivate(page) == 2;
249 static int may_write_to_queue(struct backing_dev_info *bdi)
251 if (current_is_kswapd())
253 if (current_is_pdflush()) /* This is unlikely, but why not... */
255 if (!bdi_write_congested(bdi))
257 if (bdi == current->backing_dev_info)
263 * We detected a synchronous write error writing a page out. Probably
264 * -ENOSPC. We need to propagate that into the address_space for a subsequent
265 * fsync(), msync() or close().
267 * The tricky part is that after writepage we cannot touch the mapping: nothing
268 * prevents it from being freed up. But we have a ref on the page and once
269 * that page is locked, the mapping is pinned.
271 * We're allowed to run sleeping lock_page() here because we know the caller has
274 static void handle_write_error(struct address_space *mapping,
275 struct page *page, int error)
278 if (page_mapping(page) == mapping) {
279 if (error == -ENOSPC)
280 set_bit(AS_ENOSPC, &mapping->flags);
282 set_bit(AS_EIO, &mapping->flags);
288 * pageout is called by shrink_list() for each dirty page. Calls ->writepage().
290 static pageout_t pageout(struct page *page, struct address_space *mapping)
293 * If the page is dirty, only perform writeback if that write
294 * will be non-blocking. To prevent this allocation from being
295 * stalled by pagecache activity. But note that there may be
296 * stalls if we need to run get_block(). We could test
297 * PagePrivate for that.
299 * If this process is currently in generic_file_write() against
300 * this page's queue, we can perform writeback even if that
303 * If the page is swapcache, write it back even if that would
304 * block, for some throttling. This happens by accident, because
305 * swap_backing_dev_info is bust: it doesn't reflect the
306 * congestion state of the swapdevs. Easy to fix, if needed.
307 * See swapfile.c:page_queue_congested().
309 if (!is_page_cache_freeable(page))
313 if (mapping->a_ops->writepage == NULL)
314 return PAGE_ACTIVATE;
315 if (!may_write_to_queue(mapping->backing_dev_info))
318 if (clear_page_dirty_for_io(page)) {
320 struct writeback_control wbc = {
321 .sync_mode = WB_SYNC_NONE,
322 .nr_to_write = SWAP_CLUSTER_MAX,
327 SetPageReclaim(page);
328 res = mapping->a_ops->writepage(page, &wbc);
330 handle_write_error(mapping, page, res);
331 if (res == WRITEPAGE_ACTIVATE) {
332 ClearPageReclaim(page);
333 return PAGE_ACTIVATE;
335 if (!PageWriteback(page)) {
336 /* synchronous write or broken a_ops? */
337 ClearPageReclaim(page);
347 * shrink_list adds the number of reclaimed pages to sc->nr_reclaimed
349 static int shrink_list(struct list_head *page_list, struct scan_control *sc)
351 LIST_HEAD(ret_pages);
352 struct pagevec freed_pvec;
358 pagevec_init(&freed_pvec, 1);
359 while (!list_empty(page_list)) {
360 struct address_space *mapping;
365 page = lru_to_page(page_list);
366 list_del(&page->lru);
368 if (TestSetPageLocked(page))
371 BUG_ON(PageActive(page));
373 if (PageWriteback(page))
377 /* Double the slab pressure for mapped and swapcache pages */
378 if (page_mapped(page) || PageSwapCache(page))
381 referenced = page_referenced(page, 1, sc->priority <= 0);
382 /* In active use or really unfreeable? Activate it. */
383 if (referenced && page_mapping_inuse(page))
384 goto activate_locked;
388 * Anonymous process memory has backing store?
389 * Try to allocate it some swap space here.
391 if (PageAnon(page) && !PageSwapCache(page)) {
392 if (!add_to_swap(page))
393 goto activate_locked;
395 #endif /* CONFIG_SWAP */
397 mapping = page_mapping(page);
398 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
399 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
402 * The page is mapped into the page tables of one or more
403 * processes. Try to unmap it here.
405 if (page_mapped(page) && mapping) {
406 switch (try_to_unmap(page)) {
408 goto activate_locked;
412 ; /* try to free the page below */
416 if (PageDirty(page)) {
421 if (laptop_mode && !sc->may_writepage)
424 /* Page is dirty, try to write it out here */
425 switch(pageout(page, mapping)) {
429 goto activate_locked;
431 if (PageWriteback(page) || PageDirty(page))
434 * A synchronous write - probably a ramdisk. Go
435 * ahead and try to reclaim the page.
437 if (TestSetPageLocked(page))
439 if (PageDirty(page) || PageWriteback(page))
441 mapping = page_mapping(page);
443 ; /* try to free the page below */
448 * If the page has buffers, try to free the buffer mappings
449 * associated with this page. If we succeed we try to free
452 * We do this even if the page is PageDirty().
453 * try_to_release_page() does not perform I/O, but it is
454 * possible for a page to have PageDirty set, but it is actually
455 * clean (all its buffers are clean). This happens if the
456 * buffers were written out directly, with submit_bh(). ext3
457 * will do this, as well as the blockdev mapping.
458 * try_to_release_page() will discover that cleanness and will
459 * drop the buffers and mark the page clean - it can be freed.
461 * Rarely, pages can have buffers and no ->mapping. These are
462 * the pages which were not successfully invalidated in
463 * truncate_complete_page(). We try to drop those buffers here
464 * and if that worked, and the page is no longer mapped into
465 * process address space (page_count == 1) it can be freed.
466 * Otherwise, leave the page on the LRU so it is swappable.
468 if (PagePrivate(page)) {
469 if (!try_to_release_page(page, sc->gfp_mask))
470 goto activate_locked;
471 if (!mapping && page_count(page) == 1)
476 goto keep_locked; /* truncate got there first */
478 spin_lock_irq(&mapping->tree_lock);
481 * The non-racy check for busy page. It is critical to check
482 * PageDirty _after_ making sure that the page is freeable and
483 * not in use by anybody. (pagecache + us == 2)
485 if (page_count(page) != 2 || PageDirty(page)) {
486 spin_unlock_irq(&mapping->tree_lock);
491 if (PageSwapCache(page)) {
492 swp_entry_t swap = { .val = page->private };
493 __delete_from_swap_cache(page);
494 spin_unlock_irq(&mapping->tree_lock);
496 __put_page(page); /* The pagecache ref */
499 #endif /* CONFIG_SWAP */
501 __remove_from_page_cache(page);
502 spin_unlock_irq(&mapping->tree_lock);
508 if (!pagevec_add(&freed_pvec, page))
509 __pagevec_release_nonlru(&freed_pvec);
518 list_add(&page->lru, &ret_pages);
519 BUG_ON(PageLRU(page));
521 list_splice(&ret_pages, page_list);
522 if (pagevec_count(&freed_pvec))
523 __pagevec_release_nonlru(&freed_pvec);
524 mod_page_state(pgactivate, pgactivate);
525 sc->nr_reclaimed += reclaimed;
530 * zone->lru_lock is heavily contented. We relieve it by quickly privatising
531 * a batch of pages and working on them outside the lock. Any pages which were
532 * not freed will be added back to the LRU.
534 * shrink_cache() adds the number of pages reclaimed to sc->nr_reclaimed
536 * For pagecache intensive workloads, the first loop here is the hottest spot
537 * in the kernel (apart from the copy_*_user functions).
539 #ifdef CONFIG_CKRM_RES_MEM
540 static void shrink_cache(struct ckrm_zone *ckrm_zone, struct scan_control *sc)
542 static void shrink_cache(struct zone *zone, struct scan_control *sc)
545 LIST_HEAD(page_list);
547 int max_scan = sc->nr_to_scan;
548 #ifdef CONFIG_CKRM_RES_MEM
549 struct zone *zone = ckrm_zone->zone;
550 struct list_head *inactive_list = &ckrm_zone->inactive_list;
551 struct list_head *active_list = &ckrm_zone->active_list;
553 struct list_head *inactive_list = &zone->inactive_list;
554 struct list_head *active_list = &zone->active_list;
557 pagevec_init(&pvec, 1);
560 spin_lock_irq(&zone->lru_lock);
561 while (max_scan > 0) {
567 while (nr_scan++ < SWAP_CLUSTER_MAX &&
568 !list_empty(inactive_list)) {
569 page = lru_to_page(inactive_list);
571 prefetchw_prev_lru_page(page,
572 inactive_list, flags);
574 if (!TestClearPageLRU(page))
576 list_del(&page->lru);
577 if (get_page_testone(page)) {
579 * It is being freed elsewhere
583 list_add(&page->lru, inactive_list);
586 list_add(&page->lru, &page_list);
589 zone->nr_inactive -= nr_taken;
590 ckrm_zone_sub_inactive(ckrm_zone, nr_taken);
591 spin_unlock_irq(&zone->lru_lock);
597 if (current_is_kswapd())
598 mod_page_state_zone(zone, pgscan_kswapd, nr_scan);
600 mod_page_state_zone(zone, pgscan_direct, nr_scan);
601 nr_freed = shrink_list(&page_list, sc);
602 if (current_is_kswapd())
603 mod_page_state(kswapd_steal, nr_freed);
604 mod_page_state_zone(zone, pgsteal, nr_freed);
605 sc->nr_to_reclaim -= nr_freed;
607 spin_lock_irq(&zone->lru_lock);
609 * Put back any unfreeable pages.
611 while (!list_empty(&page_list)) {
612 page = lru_to_page(&page_list);
613 if (TestSetPageLRU(page))
615 list_del(&page->lru);
616 if (PageActive(page)) {
617 ckrm_zone_add_active(ckrm_zone, 1);
619 list_add(&page->lru, active_list);
621 ckrm_zone_add_inactive(ckrm_zone, 1);
623 list_add(&page->lru, inactive_list);
625 if (!pagevec_add(&pvec, page)) {
626 spin_unlock_irq(&zone->lru_lock);
627 __pagevec_release(&pvec);
628 spin_lock_irq(&zone->lru_lock);
632 spin_unlock_irq(&zone->lru_lock);
634 pagevec_release(&pvec);
638 * This moves pages from the active list to the inactive list.
640 * We move them the other way if the page is referenced by one or more
641 * processes, from rmap.
643 * If the pages are mostly unmapped, the processing is fast and it is
644 * appropriate to hold zone->lru_lock across the whole operation. But if
645 * the pages are mapped, the processing is slow (page_referenced()) so we
646 * should drop zone->lru_lock around each page. It's impossible to balance
647 * this, so instead we remove the pages from the LRU while processing them.
648 * It is safe to rely on PG_active against the non-LRU pages in here because
649 * nobody will play with that bit on a non-LRU page.
651 * The downside is that we have to touch page->_count against each page.
652 * But we had to alter page->flags anyway.
655 #ifdef CONFIG_CKRM_RES_MEM
656 refill_inactive_zone(struct ckrm_zone *ckrm_zone, struct scan_control *sc)
658 refill_inactive_zone(struct zone *zone, struct scan_control *sc)
662 int pgdeactivate = 0;
664 int nr_pages = sc->nr_to_scan;
665 LIST_HEAD(l_hold); /* The pages which were snipped off */
666 LIST_HEAD(l_inactive); /* Pages to go onto the inactive_list */
667 LIST_HEAD(l_active); /* Pages to go onto the active_list */
670 int reclaim_mapped = 0;
674 #ifdef CONFIG_CKRM_RES_MEM
675 struct zone *zone = ckrm_zone->zone;
676 struct list_head *active_list = &ckrm_zone->active_list;
677 struct list_head *inactive_list = &ckrm_zone->inactive_list;
679 struct list_head *active_list = &zone->active_list;
680 struct list_head *inactive_list = &zone->inactive_list;
685 spin_lock_irq(&zone->lru_lock);
686 while (pgscanned < nr_pages && !list_empty(active_list)) {
687 page = lru_to_page(active_list);
688 prefetchw_prev_lru_page(page, active_list, flags);
689 if (!TestClearPageLRU(page))
691 list_del(&page->lru);
692 if (get_page_testone(page)) {
694 * It was already free! release_pages() or put_page()
695 * are about to remove it from the LRU and free it. So
696 * put the refcount back and put the page back on the
701 list_add(&page->lru, active_list);
703 list_add(&page->lru, &l_hold);
708 zone->pages_scanned += pgscanned;
709 zone->nr_active -= pgmoved;
710 ckrm_zone_sub_active(ckrm_zone, pgmoved);
711 spin_unlock_irq(&zone->lru_lock);
714 * `distress' is a measure of how much trouble we're having reclaiming
715 * pages. 0 -> no problems. 100 -> great trouble.
717 distress = 100 >> zone->prev_priority;
720 * The point of this algorithm is to decide when to start reclaiming
721 * mapped memory instead of just pagecache. Work out how much memory
724 mapped_ratio = (sc->nr_mapped * 100) / total_memory;
727 * Now decide how much we really want to unmap some pages. The mapped
728 * ratio is downgraded - just because there's a lot of mapped memory
729 * doesn't necessarily mean that page reclaim isn't succeeding.
731 * The distress ratio is important - we don't want to start going oom.
733 * A 100% value of vm_swappiness overrides this algorithm altogether.
735 swap_tendency = mapped_ratio / 2 + distress + vm_swappiness;
738 * Now use this metric to decide whether to start moving mapped memory
739 * onto the inactive list.
741 if (swap_tendency >= 100)
744 while (!list_empty(&l_hold)) {
745 page = lru_to_page(&l_hold);
746 list_del(&page->lru);
747 if (page_mapped(page)) {
748 if (!reclaim_mapped ||
749 (total_swap_pages == 0 && PageAnon(page)) ||
750 page_referenced(page, 0, sc->priority <= 0)) {
751 list_add(&page->lru, &l_active);
755 list_add(&page->lru, &l_inactive);
758 pagevec_init(&pvec, 1);
760 spin_lock_irq(&zone->lru_lock);
761 while (!list_empty(&l_inactive)) {
762 page = lru_to_page(&l_inactive);
763 prefetchw_prev_lru_page(page, &l_inactive, flags);
764 if (TestSetPageLRU(page))
766 if (!TestClearPageActive(page))
768 list_move(&page->lru, inactive_list);
770 if (!pagevec_add(&pvec, page)) {
771 zone->nr_inactive += pgmoved;
772 ckrm_zone_add_inactive(ckrm_zone, pgmoved);
773 spin_unlock_irq(&zone->lru_lock);
774 pgdeactivate += pgmoved;
776 if (buffer_heads_over_limit)
777 pagevec_strip(&pvec);
778 __pagevec_release(&pvec);
779 spin_lock_irq(&zone->lru_lock);
782 zone->nr_inactive += pgmoved;
783 ckrm_zone_add_inactive(ckrm_zone, pgmoved);
784 pgdeactivate += pgmoved;
785 if (buffer_heads_over_limit) {
786 spin_unlock_irq(&zone->lru_lock);
787 pagevec_strip(&pvec);
788 spin_lock_irq(&zone->lru_lock);
792 while (!list_empty(&l_active)) {
793 page = lru_to_page(&l_active);
794 prefetchw_prev_lru_page(page, &l_active, flags);
795 if (TestSetPageLRU(page))
797 BUG_ON(!PageActive(page));
798 list_move(&page->lru, active_list);
800 if (!pagevec_add(&pvec, page)) {
801 zone->nr_active += pgmoved;
802 ckrm_zone_add_active(ckrm_zone, pgmoved);
804 spin_unlock_irq(&zone->lru_lock);
805 __pagevec_release(&pvec);
806 spin_lock_irq(&zone->lru_lock);
809 zone->nr_active += pgmoved;
810 ckrm_zone_add_active(ckrm_zone, pgmoved);
811 spin_unlock_irq(&zone->lru_lock);
812 pagevec_release(&pvec);
814 mod_page_state_zone(zone, pgrefill, pgscanned);
815 mod_page_state(pgdeactivate, pgdeactivate);
818 #ifdef CONFIG_CKRM_RES_MEM
820 shrink_ckrmzone(struct ckrm_zone *czone, struct scan_control *sc)
822 while (czone->shrink_active || czone->shrink_inactive) {
823 if (czone->shrink_active) {
824 sc->nr_to_scan = min(czone->shrink_active,
825 (unsigned long)SWAP_CLUSTER_MAX);
826 czone->shrink_active -= sc->nr_to_scan;
827 refill_inactive_zone(czone, sc);
829 if (czone->shrink_inactive) {
830 sc->nr_to_scan = min(czone->shrink_inactive,
831 (unsigned long)SWAP_CLUSTER_MAX);
832 czone->shrink_inactive -= sc->nr_to_scan;
833 shrink_cache(czone, sc);
834 if (sc->nr_to_reclaim <= 0) {
835 czone->shrink_active = 0;
836 czone->shrink_inactive = 0;
843 /* FIXME: This function needs to be given more thought. */
845 ckrm_shrink_class(struct ckrm_mem_res *cls)
847 struct scan_control sc;
849 int zindex = 0, cnt, act_credit = 0, inact_credit = 0;
851 sc.nr_mapped = read_page_state(nr_mapped);
854 sc.priority = 0; // always very high priority
856 for_each_zone(zone) {
857 int zone_total, zone_limit, active_limit,
858 inactive_limit, clszone_limit;
859 struct ckrm_zone *czone;
862 czone = &cls->ckrm_zone[zindex];
863 if (ckrm_test_set_shrink(czone))
866 zone->temp_priority = zone->prev_priority;
867 zone->prev_priority = sc.priority;
869 zone_total = zone->nr_active + zone->nr_inactive
872 temp = (u64) cls->pg_limit * zone_total;
873 do_div(temp, ckrm_tot_lru_pages);
874 zone_limit = (int) temp;
875 clszone_limit = (ckrm_mem_shrink_to * zone_limit) / 100;
876 active_limit = (2 * clszone_limit) / 3; // 2/3rd in active list
877 inactive_limit = clszone_limit / 3; // 1/3rd in inactive list
879 czone->shrink_active = 0;
880 cnt = czone->nr_active + act_credit - active_limit;
882 czone->shrink_active = (unsigned long) cnt;
888 czone->shrink_inactive = 0;
889 cnt = czone->shrink_active + inact_credit +
890 (czone->nr_inactive - inactive_limit);
892 czone->shrink_inactive = (unsigned long) cnt;
899 if (czone->shrink_active || czone->shrink_inactive) {
900 sc.nr_to_reclaim = czone->shrink_inactive;
901 shrink_ckrmzone(czone, &sc);
903 zone->prev_priority = zone->temp_priority;
905 ckrm_clear_shrink(czone);
910 ckrm_shrink_classes(void)
912 struct ckrm_mem_res *cls;
914 spin_lock(&ckrm_mem_lock);
915 while (!ckrm_shrink_list_empty()) {
916 cls = list_entry(ckrm_shrink_list.next, struct ckrm_mem_res,
918 list_del(&cls->shrink_list);
919 cls->flags &= ~CLS_AT_LIMIT;
920 spin_unlock(&ckrm_mem_lock);
921 ckrm_shrink_class(cls);
922 spin_lock(&ckrm_mem_lock);
924 spin_unlock(&ckrm_mem_lock);
928 #define ckrm_shrink_classes() do { } while(0)
932 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
935 shrink_zone(struct zone *zone, struct scan_control *sc)
937 unsigned long nr_active;
938 unsigned long nr_inactive;
939 #ifdef CONFIG_CKRM_RES_MEM
940 struct ckrm_zone *czone;
945 * Add one to `nr_to_scan' just to make sure that the kernel will
946 * slowly sift through the active list.
948 zone->nr_scan_active += (zone->nr_active >> sc->priority) + 1;
949 nr_active = zone->nr_scan_active;
950 if (nr_active >= SWAP_CLUSTER_MAX)
951 zone->nr_scan_active = 0;
955 zone->nr_scan_inactive += (zone->nr_inactive >> sc->priority) + 1;
956 nr_inactive = zone->nr_scan_inactive;
957 if (nr_inactive >= SWAP_CLUSTER_MAX)
958 zone->nr_scan_inactive = 0;
962 sc->nr_to_reclaim = SWAP_CLUSTER_MAX;
964 #ifdef CONFIG_CKRM_RES_MEM
965 if (nr_active || nr_inactive) {
966 struct list_head *pos, *next;
969 shrink_get_victims(zone, nr_active, nr_inactive, &victims);
971 while (pos != &victims) {
972 czone = list_entry(pos, struct ckrm_zone, victim_list);
975 sc->nr_to_reclaim = czone->shrink_inactive;
976 shrink_ckrmzone(czone, sc);
977 ckrm_clear_shrink(czone);
982 while (nr_active || nr_inactive) {
984 sc->nr_to_scan = min(nr_active,
985 (unsigned long)SWAP_CLUSTER_MAX);
986 nr_active -= sc->nr_to_scan;
987 refill_inactive_zone(zone, sc);
991 sc->nr_to_scan = min(nr_inactive,
992 (unsigned long)SWAP_CLUSTER_MAX);
993 nr_inactive -= sc->nr_to_scan;
994 shrink_cache(zone, sc);
995 if (sc->nr_to_reclaim <= 0)
1003 * This is the direct reclaim path, for page-allocating processes. We only
1004 * try to reclaim pages from zones which will satisfy the caller's allocation
1007 * We reclaim from a zone even if that zone is over pages_high. Because:
1008 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
1010 * b) The zones may be over pages_high but they must go *over* pages_high to
1011 * satisfy the `incremental min' zone defense algorithm.
1013 * Returns the number of reclaimed pages.
1015 * If a zone is deemed to be full of pinned pages then just give it a light
1016 * scan then give up on it.
1019 shrink_caches(struct zone **zones, struct scan_control *sc)
1023 for (i = 0; zones[i] != NULL; i++) {
1024 struct zone *zone = zones[i];
1026 if (zone->present_pages == 0)
1029 zone->temp_priority = sc->priority;
1030 if (zone->prev_priority > sc->priority)
1031 zone->prev_priority = sc->priority;
1033 if (zone->all_unreclaimable && sc->priority != DEF_PRIORITY)
1034 continue; /* Let kswapd poll it */
1036 shrink_zone(zone, sc);
1041 * This is the main entry point to direct page reclaim.
1043 * If a full scan of the inactive list fails to free enough memory then we
1044 * are "out of memory" and something needs to be killed.
1046 * If the caller is !__GFP_FS then the probability of a failure is reasonably
1047 * high - the zone may be full of dirty or under-writeback pages, which this
1048 * caller can't do much about. We kick pdflush and take explicit naps in the
1049 * hope that some of these pages can be written. But if the allocating task
1050 * holds filesystem locks which prevent writeout this might not work, and the
1051 * allocation attempt will fail.
1053 int try_to_free_pages(struct zone **zones,
1054 unsigned int gfp_mask, unsigned int order)
1058 int total_scanned = 0, total_reclaimed = 0;
1059 struct reclaim_state *reclaim_state = current->reclaim_state;
1060 struct scan_control sc;
1061 unsigned long lru_pages = 0;
1064 sc.gfp_mask = gfp_mask;
1065 sc.may_writepage = 0;
1067 inc_page_state(allocstall);
1069 for (i = 0; zones[i] != NULL; i++) {
1070 struct zone *zone = zones[i];
1072 zone->temp_priority = DEF_PRIORITY;
1073 lru_pages += zone->nr_active + zone->nr_inactive;
1076 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1077 sc.nr_mapped = read_page_state(nr_mapped);
1079 sc.nr_reclaimed = 0;
1080 sc.priority = priority;
1081 shrink_caches(zones, &sc);
1082 shrink_slab(sc.nr_scanned, gfp_mask, lru_pages);
1083 if (reclaim_state) {
1084 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
1085 reclaim_state->reclaimed_slab = 0;
1087 if (sc.nr_reclaimed >= SWAP_CLUSTER_MAX) {
1091 total_scanned += sc.nr_scanned;
1092 total_reclaimed += sc.nr_reclaimed;
1095 * Try to write back as many pages as we just scanned. This
1096 * tends to cause slow streaming writers to write data to the
1097 * disk smoothly, at the dirtying rate, which is nice. But
1098 * that's undesirable in laptop mode, where we *want* lumpy
1099 * writeout. So in laptop mode, write out the whole world.
1101 if (total_scanned > SWAP_CLUSTER_MAX + SWAP_CLUSTER_MAX/2) {
1102 wakeup_bdflush(laptop_mode ? 0 : total_scanned);
1103 sc.may_writepage = 1;
1106 /* Take a nap, wait for some writeback to complete */
1107 if (sc.nr_scanned && priority < DEF_PRIORITY - 2)
1108 blk_congestion_wait(WRITE, HZ/10);
1110 if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY))
1111 out_of_memory(gfp_mask);
1113 for (i = 0; zones[i] != 0; i++)
1114 zones[i]->prev_priority = zones[i]->temp_priority;
1119 * For kswapd, balance_pgdat() will work across all this node's zones until
1120 * they are all at pages_high.
1122 * If `nr_pages' is non-zero then it is the number of pages which are to be
1123 * reclaimed, regardless of the zone occupancies. This is a software suspend
1126 * Returns the number of pages which were actually freed.
1128 * There is special handling here for zones which are full of pinned pages.
1129 * This can happen if the pages are all mlocked, or if they are all used by
1130 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
1131 * What we do is to detect the case where all pages in the zone have been
1132 * scanned twice and there has been zero successful reclaim. Mark the zone as
1133 * dead and from now on, only perform a short scan. Basically we're polling
1134 * the zone for when the problem goes away.
1136 * kswapd scans the zones in the highmem->normal->dma direction. It skips
1137 * zones which have free_pages > pages_high, but once a zone is found to have
1138 * free_pages <= pages_high, we scan that zone and the lower zones regardless
1139 * of the number of free pages in the lower zones. This interoperates with
1140 * the page allocator fallback scheme to ensure that aging of pages is balanced
1143 static int balance_pgdat(pg_data_t *pgdat, int nr_pages)
1145 int to_free = nr_pages;
1149 int total_scanned, total_reclaimed;
1150 struct reclaim_state *reclaim_state = current->reclaim_state;
1151 struct scan_control sc;
1155 total_reclaimed = 0;
1156 sc.gfp_mask = GFP_KERNEL;
1157 sc.may_writepage = 0;
1158 sc.nr_mapped = read_page_state(nr_mapped);
1160 inc_page_state(pageoutrun);
1162 for (i = 0; i < pgdat->nr_zones; i++) {
1163 struct zone *zone = pgdat->node_zones + i;
1165 zone->temp_priority = DEF_PRIORITY;
1168 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1169 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
1170 unsigned long lru_pages = 0;
1174 if (nr_pages == 0) {
1176 * Scan in the highmem->dma direction for the highest
1177 * zone which needs scanning
1179 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
1180 struct zone *zone = pgdat->node_zones + i;
1182 if (zone->present_pages == 0)
1185 if (zone->all_unreclaimable &&
1186 priority != DEF_PRIORITY)
1189 if (zone->free_pages <= zone->pages_high) {
1196 end_zone = pgdat->nr_zones - 1;
1199 for (i = 0; i <= end_zone; i++) {
1200 struct zone *zone = pgdat->node_zones + i;
1202 lru_pages += zone->nr_active + zone->nr_inactive;
1206 * Now scan the zone in the dma->highmem direction, stopping
1207 * at the last zone which needs scanning.
1209 * We do this because the page allocator works in the opposite
1210 * direction. This prevents the page allocator from allocating
1211 * pages behind kswapd's direction of progress, which would
1212 * cause too much scanning of the lower zones.
1214 for (i = 0; i <= end_zone; i++) {
1215 struct zone *zone = pgdat->node_zones + i;
1217 if (zone->present_pages == 0)
1220 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1223 if (nr_pages == 0) { /* Not software suspend */
1224 if (zone->free_pages <= zone->pages_high)
1227 zone->temp_priority = priority;
1228 if (zone->prev_priority > priority)
1229 zone->prev_priority = priority;
1231 sc.nr_reclaimed = 0;
1232 sc.priority = priority;
1233 shrink_zone(zone, &sc);
1234 reclaim_state->reclaimed_slab = 0;
1235 shrink_slab(sc.nr_scanned, GFP_KERNEL, lru_pages);
1236 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
1237 total_reclaimed += sc.nr_reclaimed;
1238 if (zone->all_unreclaimable)
1240 if (zone->pages_scanned >= (zone->nr_active +
1241 zone->nr_inactive) * 4)
1242 zone->all_unreclaimable = 1;
1244 * If we've done a decent amount of scanning and
1245 * the reclaim ratio is low, start doing writepage
1246 * even in laptop mode
1248 if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
1249 total_scanned > total_reclaimed+total_reclaimed/2)
1250 sc.may_writepage = 1;
1252 if (nr_pages && to_free > total_reclaimed)
1253 continue; /* swsusp: need to do more work */
1255 break; /* kswapd: all done */
1257 * OK, kswapd is getting into trouble. Take a nap, then take
1258 * another pass across the zones.
1260 if (total_scanned && priority < DEF_PRIORITY - 2)
1261 blk_congestion_wait(WRITE, HZ/10);
1264 * We do this so kswapd doesn't build up large priorities for
1265 * example when it is freeing in parallel with allocators. It
1266 * matches the direct reclaim path behaviour in terms of impact
1267 * on zone->*_priority.
1269 if (total_reclaimed >= SWAP_CLUSTER_MAX)
1273 for (i = 0; i < pgdat->nr_zones; i++) {
1274 struct zone *zone = pgdat->node_zones + i;
1276 zone->prev_priority = zone->temp_priority;
1278 if (!all_zones_ok) {
1283 return total_reclaimed;
1287 * The background pageout daemon, started as a kernel thread
1288 * from the init process.
1290 * This basically trickles out pages so that we have _some_
1291 * free memory available even if there is no other activity
1292 * that frees anything up. This is needed for things like routing
1293 * etc, where we otherwise might have all activity going on in
1294 * asynchronous contexts that cannot page things out.
1296 * If there are applications that are active memory-allocators
1297 * (most normal use), this basically shouldn't matter.
1299 static int kswapd(void *p)
1301 pg_data_t *pgdat = (pg_data_t*)p;
1302 struct task_struct *tsk = current;
1304 struct reclaim_state reclaim_state = {
1305 .reclaimed_slab = 0,
1309 daemonize("kswapd%d", pgdat->node_id);
1310 cpumask = node_to_cpumask(pgdat->node_id);
1311 if (!cpus_empty(cpumask))
1312 set_cpus_allowed(tsk, cpumask);
1313 current->reclaim_state = &reclaim_state;
1316 * Tell the memory management that we're a "memory allocator",
1317 * and that if we need more memory we should get access to it
1318 * regardless (see "__alloc_pages()"). "kswapd" should
1319 * never get caught in the normal page freeing logic.
1321 * (Kswapd normally doesn't need memory anyway, but sometimes
1322 * you need a small amount of memory in order to be able to
1323 * page out something else, and this flag essentially protects
1324 * us from recursively trying to free more memory as we're
1325 * trying to free the first piece of memory in the first place).
1327 tsk->flags |= PF_MEMALLOC|PF_KSWAPD;
1330 if (current->flags & PF_FREEZE)
1331 refrigerator(PF_FREEZE);
1332 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
1334 finish_wait(&pgdat->kswapd_wait, &wait);
1336 if (!ckrm_shrink_list_empty())
1337 ckrm_shrink_classes();
1339 balance_pgdat(pgdat, 0);
1345 * A zone is low on free memory, so wake its kswapd task to service it.
1347 void wakeup_kswapd(struct zone *zone)
1349 if (zone->present_pages == 0)
1351 if (zone->free_pages > zone->pages_low)
1353 if (!waitqueue_active(&zone->zone_pgdat->kswapd_wait))
1355 wake_up_interruptible(&zone->zone_pgdat->kswapd_wait);
1360 * Try to free `nr_pages' of memory, system-wide. Returns the number of freed
1363 int shrink_all_memory(int nr_pages)
1366 int nr_to_free = nr_pages;
1368 struct reclaim_state reclaim_state = {
1369 .reclaimed_slab = 0,
1372 current->reclaim_state = &reclaim_state;
1373 for_each_pgdat(pgdat) {
1375 freed = balance_pgdat(pgdat, nr_to_free);
1377 nr_to_free -= freed;
1378 if (nr_to_free <= 0)
1381 current->reclaim_state = NULL;
1386 #ifdef CONFIG_HOTPLUG_CPU
1387 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1388 not required for correctness. So if the last cpu in a node goes
1389 away, we get changed to run anywhere: as the first one comes back,
1390 restore their cpu bindings. */
1391 static int __devinit cpu_callback(struct notifier_block *nfb,
1392 unsigned long action,
1398 if (action == CPU_ONLINE) {
1399 for_each_pgdat(pgdat) {
1400 mask = node_to_cpumask(pgdat->node_id);
1401 if (any_online_cpu(mask) != NR_CPUS)
1402 /* One of our CPUs online: restore mask */
1403 set_cpus_allowed(pgdat->kswapd, mask);
1408 #endif /* CONFIG_HOTPLUG_CPU */
1410 static int __init kswapd_init(void)
1414 for_each_pgdat(pgdat)
1416 = find_task_by_pid(kernel_thread(kswapd, pgdat, CLONE_KERNEL));
1417 total_memory = nr_free_pagecache_pages();
1418 hotcpu_notifier(cpu_callback, 0);
1422 module_init(kswapd_init)