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/blkdev.h>
25 #include <linux/buffer_head.h> /* for try_to_release_page(),
26 buffer_heads_over_limit */
27 #include <linux/mm_inline.h>
28 #include <linux/pagevec.h>
29 #include <linux/backing-dev.h>
30 #include <linux/rmap.h>
31 #include <linux/topology.h>
32 #include <linux/cpu.h>
33 #include <linux/cpuset.h>
34 #include <linux/notifier.h>
35 #include <linux/rwsem.h>
36 #include <linux/delay.h>
38 #include <asm/tlbflush.h>
39 #include <asm/div64.h>
41 #include <linux/swapops.h>
46 /* Incremented by the number of inactive pages that were scanned */
47 unsigned long nr_scanned
;
49 unsigned long nr_mapped
; /* From page_state */
51 /* This context's GFP mask */
56 /* Can pages be swapped as part of reclaim? */
59 /* This context's SWAP_CLUSTER_MAX. If freeing memory for
60 * suspend, we effectively ignore SWAP_CLUSTER_MAX.
61 * In this context, it doesn't matter that we scan the
62 * whole list at once. */
69 * The list of shrinker callbacks used by to apply pressure to
74 struct list_head list
;
75 int seeks
; /* seeks to recreate an obj */
76 long nr
; /* objs pending delete */
79 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
81 #ifdef ARCH_HAS_PREFETCH
82 #define prefetch_prev_lru_page(_page, _base, _field) \
84 if ((_page)->lru.prev != _base) { \
87 prev = lru_to_page(&(_page->lru)); \
88 prefetch(&prev->_field); \
92 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
95 #ifdef ARCH_HAS_PREFETCHW
96 #define prefetchw_prev_lru_page(_page, _base, _field) \
98 if ((_page)->lru.prev != _base) { \
101 prev = lru_to_page(&(_page->lru)); \
102 prefetchw(&prev->_field); \
106 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
110 * From 0 .. 100. Higher means more swappy.
112 int vm_swappiness
= 60;
113 static long total_memory
;
115 static LIST_HEAD(shrinker_list
);
116 static DECLARE_RWSEM(shrinker_rwsem
);
119 * Add a shrinker callback to be called from the vm
121 struct shrinker
*set_shrinker(int seeks
, shrinker_t theshrinker
)
123 struct shrinker
*shrinker
;
125 shrinker
= kmalloc(sizeof(*shrinker
), GFP_KERNEL
);
127 shrinker
->shrinker
= theshrinker
;
128 shrinker
->seeks
= seeks
;
130 down_write(&shrinker_rwsem
);
131 list_add_tail(&shrinker
->list
, &shrinker_list
);
132 up_write(&shrinker_rwsem
);
136 EXPORT_SYMBOL(set_shrinker
);
141 void remove_shrinker(struct shrinker
*shrinker
)
143 down_write(&shrinker_rwsem
);
144 list_del(&shrinker
->list
);
145 up_write(&shrinker_rwsem
);
148 EXPORT_SYMBOL(remove_shrinker
);
150 #define SHRINK_BATCH 128
152 * Call the shrink functions to age shrinkable caches
154 * Here we assume it costs one seek to replace a lru page and that it also
155 * takes a seek to recreate a cache object. With this in mind we age equal
156 * percentages of the lru and ageable caches. This should balance the seeks
157 * generated by these structures.
159 * If the vm encounted mapped pages on the LRU it increase the pressure on
160 * slab to avoid swapping.
162 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
164 * `lru_pages' represents the number of on-LRU pages in all the zones which
165 * are eligible for the caller's allocation attempt. It is used for balancing
166 * slab reclaim versus page reclaim.
168 * Returns the number of slab objects which we shrunk.
170 unsigned long shrink_slab(unsigned long scanned
, gfp_t gfp_mask
,
171 unsigned long lru_pages
)
173 struct shrinker
*shrinker
;
174 unsigned long ret
= 0;
177 scanned
= SWAP_CLUSTER_MAX
;
179 if (!down_read_trylock(&shrinker_rwsem
))
180 return 1; /* Assume we'll be able to shrink next time */
182 list_for_each_entry(shrinker
, &shrinker_list
, list
) {
183 unsigned long long delta
;
184 unsigned long total_scan
;
185 unsigned long max_pass
= (*shrinker
->shrinker
)(0, gfp_mask
);
187 delta
= (4 * scanned
) / shrinker
->seeks
;
189 do_div(delta
, lru_pages
+ 1);
190 shrinker
->nr
+= delta
;
191 if (shrinker
->nr
< 0) {
192 printk(KERN_ERR
"%s: nr=%ld\n",
193 __FUNCTION__
, shrinker
->nr
);
194 shrinker
->nr
= max_pass
;
198 * Avoid risking looping forever due to too large nr value:
199 * never try to free more than twice the estimate number of
202 if (shrinker
->nr
> max_pass
* 2)
203 shrinker
->nr
= max_pass
* 2;
205 total_scan
= shrinker
->nr
;
208 while (total_scan
>= SHRINK_BATCH
) {
209 long this_scan
= SHRINK_BATCH
;
213 nr_before
= (*shrinker
->shrinker
)(0, gfp_mask
);
214 shrink_ret
= (*shrinker
->shrinker
)(this_scan
, gfp_mask
);
215 if (shrink_ret
== -1)
217 if (shrink_ret
< nr_before
)
218 ret
+= nr_before
- shrink_ret
;
219 mod_page_state(slabs_scanned
, this_scan
);
220 total_scan
-= this_scan
;
225 shrinker
->nr
+= total_scan
;
227 up_read(&shrinker_rwsem
);
231 /* Called without lock on whether page is mapped, so answer is unstable */
232 static inline int page_mapping_inuse(struct page
*page
)
234 struct address_space
*mapping
;
236 /* Page is in somebody's page tables. */
237 if (page_mapped(page
))
240 /* Be more reluctant to reclaim swapcache than pagecache */
241 if (PageSwapCache(page
))
244 mapping
= page_mapping(page
);
248 /* File is mmap'd by somebody? */
249 return mapping_mapped(mapping
);
252 static inline int is_page_cache_freeable(struct page
*page
)
254 return page_count(page
) - !!PagePrivate(page
) == 2;
257 static int may_write_to_queue(struct backing_dev_info
*bdi
)
259 if (current
->flags
& PF_SWAPWRITE
)
261 if (!bdi_write_congested(bdi
))
263 if (bdi
== current
->backing_dev_info
)
269 * We detected a synchronous write error writing a page out. Probably
270 * -ENOSPC. We need to propagate that into the address_space for a subsequent
271 * fsync(), msync() or close().
273 * The tricky part is that after writepage we cannot touch the mapping: nothing
274 * prevents it from being freed up. But we have a ref on the page and once
275 * that page is locked, the mapping is pinned.
277 * We're allowed to run sleeping lock_page() here because we know the caller has
280 static void handle_write_error(struct address_space
*mapping
,
281 struct page
*page
, int error
)
284 if (page_mapping(page
) == mapping
) {
285 if (error
== -ENOSPC
)
286 set_bit(AS_ENOSPC
, &mapping
->flags
);
288 set_bit(AS_EIO
, &mapping
->flags
);
294 * pageout is called by shrink_page_list() for each dirty page.
295 * Calls ->writepage().
297 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 * Some data journaling orphaned pages can have
321 * page->mapping == NULL while being dirty with clean buffers.
323 if (PagePrivate(page
)) {
324 if (try_to_free_buffers(page
)) {
325 ClearPageDirty(page
);
326 printk("%s: orphaned page\n", __FUNCTION__
);
332 if (mapping
->a_ops
->writepage
== NULL
)
333 return PAGE_ACTIVATE
;
334 if (!may_write_to_queue(mapping
->backing_dev_info
))
337 if (clear_page_dirty_for_io(page
)) {
339 struct writeback_control wbc
= {
340 .sync_mode
= WB_SYNC_NONE
,
341 .nr_to_write
= SWAP_CLUSTER_MAX
,
343 .range_end
= LLONG_MAX
,
348 SetPageReclaim(page
);
349 res
= mapping
->a_ops
->writepage(page
, &wbc
);
351 handle_write_error(mapping
, page
, res
);
352 if (res
== AOP_WRITEPAGE_ACTIVATE
) {
353 ClearPageReclaim(page
);
354 return PAGE_ACTIVATE
;
356 if (!PageWriteback(page
)) {
357 /* synchronous write or broken a_ops? */
358 ClearPageReclaim(page
);
367 int remove_mapping(struct address_space
*mapping
, struct page
*page
)
370 return 0; /* truncate got there first */
372 write_lock_irq(&mapping
->tree_lock
);
375 * The non-racy check for busy page. It is critical to check
376 * PageDirty _after_ making sure that the page is freeable and
377 * not in use by anybody. (pagecache + us == 2)
379 if (unlikely(page_count(page
) != 2))
382 if (unlikely(PageDirty(page
)))
385 if (PageSwapCache(page
)) {
386 swp_entry_t swap
= { .val
= page_private(page
) };
387 __delete_from_swap_cache(page
);
388 write_unlock_irq(&mapping
->tree_lock
);
390 __put_page(page
); /* The pagecache ref */
394 __remove_from_page_cache(page
);
395 write_unlock_irq(&mapping
->tree_lock
);
400 write_unlock_irq(&mapping
->tree_lock
);
405 * shrink_page_list() returns the number of reclaimed pages
407 static unsigned long shrink_page_list(struct list_head
*page_list
,
408 struct scan_control
*sc
)
410 LIST_HEAD(ret_pages
);
411 struct pagevec freed_pvec
;
413 unsigned long nr_reclaimed
= 0;
417 pagevec_init(&freed_pvec
, 1);
418 while (!list_empty(page_list
)) {
419 struct address_space
*mapping
;
426 page
= lru_to_page(page_list
);
427 list_del(&page
->lru
);
429 if (TestSetPageLocked(page
))
432 BUG_ON(PageActive(page
));
436 if (!sc
->may_swap
&& page_mapped(page
))
439 /* Double the slab pressure for mapped and swapcache pages */
440 if (page_mapped(page
) || PageSwapCache(page
))
443 if (PageWriteback(page
))
446 referenced
= page_referenced(page
, 1);
447 /* In active use or really unfreeable? Activate it. */
448 if (referenced
&& page_mapping_inuse(page
))
449 goto activate_locked
;
453 * Anonymous process memory has backing store?
454 * Try to allocate it some swap space here.
456 if (PageAnon(page
) && !PageSwapCache(page
))
457 if (!add_to_swap(page
, GFP_ATOMIC
))
458 goto activate_locked
;
459 #endif /* CONFIG_SWAP */
461 mapping
= page_mapping(page
);
462 may_enter_fs
= (sc
->gfp_mask
& __GFP_FS
) ||
463 (PageSwapCache(page
) && (sc
->gfp_mask
& __GFP_IO
));
466 * The page is mapped into the page tables of one or more
467 * processes. Try to unmap it here.
469 if (page_mapped(page
) && mapping
) {
470 switch (try_to_unmap(page
, 0)) {
472 goto activate_locked
;
476 ; /* try to free the page below */
480 if (PageDirty(page
)) {
485 if (!sc
->may_writepage
)
488 /* Page is dirty, try to write it out here */
489 switch(pageout(page
, mapping
)) {
493 goto activate_locked
;
495 if (PageWriteback(page
) || PageDirty(page
))
498 * A synchronous write - probably a ramdisk. Go
499 * ahead and try to reclaim the page.
501 if (TestSetPageLocked(page
))
503 if (PageDirty(page
) || PageWriteback(page
))
505 mapping
= page_mapping(page
);
507 ; /* try to free the page below */
512 * If the page has buffers, try to free the buffer mappings
513 * associated with this page. If we succeed we try to free
516 * We do this even if the page is PageDirty().
517 * try_to_release_page() does not perform I/O, but it is
518 * possible for a page to have PageDirty set, but it is actually
519 * clean (all its buffers are clean). This happens if the
520 * buffers were written out directly, with submit_bh(). ext3
521 * will do this, as well as the blockdev mapping.
522 * try_to_release_page() will discover that cleanness and will
523 * drop the buffers and mark the page clean - it can be freed.
525 * Rarely, pages can have buffers and no ->mapping. These are
526 * the pages which were not successfully invalidated in
527 * truncate_complete_page(). We try to drop those buffers here
528 * and if that worked, and the page is no longer mapped into
529 * process address space (page_count == 1) it can be freed.
530 * Otherwise, leave the page on the LRU so it is swappable.
532 if (PagePrivate(page
)) {
533 if (!try_to_release_page(page
, sc
->gfp_mask
))
534 goto activate_locked
;
535 if (!mapping
&& page_count(page
) == 1)
539 if (!remove_mapping(mapping
, page
))
545 if (!pagevec_add(&freed_pvec
, page
))
546 __pagevec_release_nonlru(&freed_pvec
);
555 list_add(&page
->lru
, &ret_pages
);
556 BUG_ON(PageLRU(page
));
558 list_splice(&ret_pages
, page_list
);
559 if (pagevec_count(&freed_pvec
))
560 __pagevec_release_nonlru(&freed_pvec
);
561 mod_page_state(pgactivate
, pgactivate
);
566 * zone->lru_lock is heavily contended. Some of the functions that
567 * shrink the lists perform better by taking out a batch of pages
568 * and working on them outside the LRU lock.
570 * For pagecache intensive workloads, this function is the hottest
571 * spot in the kernel (apart from copy_*_user functions).
573 * Appropriate locks must be held before calling this function.
575 * @nr_to_scan: The number of pages to look through on the list.
576 * @src: The LRU list to pull pages off.
577 * @dst: The temp list to put pages on to.
578 * @scanned: The number of pages that were scanned.
580 * returns how many pages were moved onto *@dst.
582 static unsigned long isolate_lru_pages(unsigned long nr_to_scan
,
583 struct list_head
*src
, struct list_head
*dst
,
584 unsigned long *scanned
)
586 unsigned long nr_taken
= 0;
590 for (scan
= 0; scan
< nr_to_scan
&& !list_empty(src
); scan
++) {
591 struct list_head
*target
;
592 page
= lru_to_page(src
);
593 prefetchw_prev_lru_page(page
, src
, flags
);
595 BUG_ON(!PageLRU(page
));
597 list_del(&page
->lru
);
599 if (likely(get_page_unless_zero(page
))) {
601 * Be careful not to clear PageLRU until after we're
602 * sure the page is not being freed elsewhere -- the
603 * page release code relies on it.
608 } /* else it is being freed elsewhere */
610 list_add(&page
->lru
, target
);
618 * shrink_inactive_list() is a helper for shrink_zone(). It returns the number
621 static unsigned long shrink_inactive_list(unsigned long max_scan
,
622 struct zone
*zone
, struct scan_control
*sc
)
624 LIST_HEAD(page_list
);
626 unsigned long nr_scanned
= 0;
627 unsigned long nr_reclaimed
= 0;
629 pagevec_init(&pvec
, 1);
632 spin_lock_irq(&zone
->lru_lock
);
635 unsigned long nr_taken
;
636 unsigned long nr_scan
;
637 unsigned long nr_freed
;
639 nr_taken
= isolate_lru_pages(sc
->swap_cluster_max
,
640 &zone
->inactive_list
,
641 &page_list
, &nr_scan
);
642 zone
->nr_inactive
-= nr_taken
;
643 zone
->pages_scanned
+= nr_scan
;
644 spin_unlock_irq(&zone
->lru_lock
);
646 nr_scanned
+= nr_scan
;
647 nr_freed
= shrink_page_list(&page_list
, sc
);
648 nr_reclaimed
+= nr_freed
;
650 if (current_is_kswapd()) {
651 __mod_page_state_zone(zone
, pgscan_kswapd
, nr_scan
);
652 __mod_page_state(kswapd_steal
, nr_freed
);
654 __mod_page_state_zone(zone
, pgscan_direct
, nr_scan
);
655 __mod_page_state_zone(zone
, pgsteal
, nr_freed
);
660 spin_lock(&zone
->lru_lock
);
662 * Put back any unfreeable pages.
664 while (!list_empty(&page_list
)) {
665 page
= lru_to_page(&page_list
);
666 BUG_ON(PageLRU(page
));
668 list_del(&page
->lru
);
669 if (PageActive(page
))
670 add_page_to_active_list(zone
, page
);
672 add_page_to_inactive_list(zone
, page
);
673 if (!pagevec_add(&pvec
, page
)) {
674 spin_unlock_irq(&zone
->lru_lock
);
675 __pagevec_release(&pvec
);
676 spin_lock_irq(&zone
->lru_lock
);
679 } while (nr_scanned
< max_scan
);
680 spin_unlock(&zone
->lru_lock
);
683 pagevec_release(&pvec
);
688 * This moves pages from the active list to the inactive list.
690 * We move them the other way if the page is referenced by one or more
691 * processes, from rmap.
693 * If the pages are mostly unmapped, the processing is fast and it is
694 * appropriate to hold zone->lru_lock across the whole operation. But if
695 * the pages are mapped, the processing is slow (page_referenced()) so we
696 * should drop zone->lru_lock around each page. It's impossible to balance
697 * this, so instead we remove the pages from the LRU while processing them.
698 * It is safe to rely on PG_active against the non-LRU pages in here because
699 * nobody will play with that bit on a non-LRU page.
701 * The downside is that we have to touch page->_count against each page.
702 * But we had to alter page->flags anyway.
704 static void shrink_active_list(unsigned long nr_pages
, struct zone
*zone
,
705 struct scan_control
*sc
)
707 unsigned long pgmoved
;
708 int pgdeactivate
= 0;
709 unsigned long pgscanned
;
710 LIST_HEAD(l_hold
); /* The pages which were snipped off */
711 LIST_HEAD(l_inactive
); /* Pages to go onto the inactive_list */
712 LIST_HEAD(l_active
); /* Pages to go onto the active_list */
715 int reclaim_mapped
= 0;
723 * `distress' is a measure of how much trouble we're having
724 * reclaiming pages. 0 -> no problems. 100 -> great trouble.
726 distress
= 100 >> zone
->prev_priority
;
729 * The point of this algorithm is to decide when to start
730 * reclaiming mapped memory instead of just pagecache. Work out
734 mapped_ratio
= (sc
->nr_mapped
* 100) / total_memory
;
737 * Now decide how much we really want to unmap some pages. The
738 * mapped ratio is downgraded - just because there's a lot of
739 * mapped memory doesn't necessarily mean that page reclaim
742 * The distress ratio is important - we don't want to start
745 * A 100% value of vm_swappiness overrides this algorithm
748 swap_tendency
= mapped_ratio
/ 2 + distress
+ sc
->swappiness
;
751 * Now use this metric to decide whether to start moving mapped
752 * memory onto the inactive list.
754 if (swap_tendency
>= 100)
759 spin_lock_irq(&zone
->lru_lock
);
760 pgmoved
= isolate_lru_pages(nr_pages
, &zone
->active_list
,
761 &l_hold
, &pgscanned
);
762 zone
->pages_scanned
+= pgscanned
;
763 zone
->nr_active
-= pgmoved
;
764 spin_unlock_irq(&zone
->lru_lock
);
766 while (!list_empty(&l_hold
)) {
768 page
= lru_to_page(&l_hold
);
769 list_del(&page
->lru
);
770 if (page_mapped(page
)) {
771 if (!reclaim_mapped
||
772 (total_swap_pages
== 0 && PageAnon(page
)) ||
773 page_referenced(page
, 0)) {
774 list_add(&page
->lru
, &l_active
);
778 list_add(&page
->lru
, &l_inactive
);
781 pagevec_init(&pvec
, 1);
783 spin_lock_irq(&zone
->lru_lock
);
784 while (!list_empty(&l_inactive
)) {
785 page
= lru_to_page(&l_inactive
);
786 prefetchw_prev_lru_page(page
, &l_inactive
, flags
);
787 BUG_ON(PageLRU(page
));
789 BUG_ON(!PageActive(page
));
790 ClearPageActive(page
);
792 list_move(&page
->lru
, &zone
->inactive_list
);
794 if (!pagevec_add(&pvec
, page
)) {
795 zone
->nr_inactive
+= pgmoved
;
796 spin_unlock_irq(&zone
->lru_lock
);
797 pgdeactivate
+= pgmoved
;
799 if (buffer_heads_over_limit
)
800 pagevec_strip(&pvec
);
801 __pagevec_release(&pvec
);
802 spin_lock_irq(&zone
->lru_lock
);
805 zone
->nr_inactive
+= pgmoved
;
806 pgdeactivate
+= pgmoved
;
807 if (buffer_heads_over_limit
) {
808 spin_unlock_irq(&zone
->lru_lock
);
809 pagevec_strip(&pvec
);
810 spin_lock_irq(&zone
->lru_lock
);
814 while (!list_empty(&l_active
)) {
815 page
= lru_to_page(&l_active
);
816 prefetchw_prev_lru_page(page
, &l_active
, flags
);
817 BUG_ON(PageLRU(page
));
819 BUG_ON(!PageActive(page
));
820 list_move(&page
->lru
, &zone
->active_list
);
822 if (!pagevec_add(&pvec
, page
)) {
823 zone
->nr_active
+= pgmoved
;
825 spin_unlock_irq(&zone
->lru_lock
);
826 __pagevec_release(&pvec
);
827 spin_lock_irq(&zone
->lru_lock
);
830 zone
->nr_active
+= pgmoved
;
831 spin_unlock(&zone
->lru_lock
);
833 __mod_page_state_zone(zone
, pgrefill
, pgscanned
);
834 __mod_page_state(pgdeactivate
, pgdeactivate
);
837 pagevec_release(&pvec
);
841 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
843 static unsigned long shrink_zone(int priority
, struct zone
*zone
,
844 struct scan_control
*sc
)
846 unsigned long nr_active
;
847 unsigned long nr_inactive
;
848 unsigned long nr_to_scan
;
849 unsigned long nr_reclaimed
= 0;
851 atomic_inc(&zone
->reclaim_in_progress
);
854 * Add one to `nr_to_scan' just to make sure that the kernel will
855 * slowly sift through the active list.
857 zone
->nr_scan_active
+= (zone
->nr_active
>> priority
) + 1;
858 nr_active
= zone
->nr_scan_active
;
859 if (nr_active
>= sc
->swap_cluster_max
)
860 zone
->nr_scan_active
= 0;
864 zone
->nr_scan_inactive
+= (zone
->nr_inactive
>> priority
) + 1;
865 nr_inactive
= zone
->nr_scan_inactive
;
866 if (nr_inactive
>= sc
->swap_cluster_max
)
867 zone
->nr_scan_inactive
= 0;
871 while (nr_active
|| nr_inactive
) {
873 nr_to_scan
= min(nr_active
,
874 (unsigned long)sc
->swap_cluster_max
);
875 nr_active
-= nr_to_scan
;
876 shrink_active_list(nr_to_scan
, zone
, sc
);
880 nr_to_scan
= min(nr_inactive
,
881 (unsigned long)sc
->swap_cluster_max
);
882 nr_inactive
-= nr_to_scan
;
883 nr_reclaimed
+= shrink_inactive_list(nr_to_scan
, zone
,
888 throttle_vm_writeout();
890 atomic_dec(&zone
->reclaim_in_progress
);
895 * This is the direct reclaim path, for page-allocating processes. We only
896 * try to reclaim pages from zones which will satisfy the caller's allocation
899 * We reclaim from a zone even if that zone is over pages_high. Because:
900 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
902 * b) The zones may be over pages_high but they must go *over* pages_high to
903 * satisfy the `incremental min' zone defense algorithm.
905 * Returns the number of reclaimed pages.
907 * If a zone is deemed to be full of pinned pages then just give it a light
908 * scan then give up on it.
910 static unsigned long shrink_zones(int priority
, struct zone
**zones
,
911 struct scan_control
*sc
)
913 unsigned long nr_reclaimed
= 0;
916 for (i
= 0; zones
[i
] != NULL
; i
++) {
917 struct zone
*zone
= zones
[i
];
919 if (!populated_zone(zone
))
922 if (!cpuset_zone_allowed(zone
, __GFP_HARDWALL
))
925 zone
->temp_priority
= priority
;
926 if (zone
->prev_priority
> priority
)
927 zone
->prev_priority
= priority
;
929 if (zone
->all_unreclaimable
&& priority
!= DEF_PRIORITY
)
930 continue; /* Let kswapd poll it */
932 nr_reclaimed
+= shrink_zone(priority
, zone
, sc
);
938 * This is the main entry point to direct page reclaim.
940 * If a full scan of the inactive list fails to free enough memory then we
941 * are "out of memory" and something needs to be killed.
943 * If the caller is !__GFP_FS then the probability of a failure is reasonably
944 * high - the zone may be full of dirty or under-writeback pages, which this
945 * caller can't do much about. We kick pdflush and take explicit naps in the
946 * hope that some of these pages can be written. But if the allocating task
947 * holds filesystem locks which prevent writeout this might not work, and the
948 * allocation attempt will fail.
950 unsigned long try_to_free_pages(struct zone
**zones
, gfp_t gfp_mask
)
954 unsigned long total_scanned
= 0;
955 unsigned long nr_reclaimed
= 0;
956 struct reclaim_state
*reclaim_state
= current
->reclaim_state
;
957 unsigned long lru_pages
= 0;
959 struct scan_control sc
= {
960 .gfp_mask
= gfp_mask
,
961 .may_writepage
= !laptop_mode
,
962 .swap_cluster_max
= SWAP_CLUSTER_MAX
,
964 .swappiness
= vm_swappiness
,
967 inc_page_state(allocstall
);
969 for (i
= 0; zones
[i
] != NULL
; i
++) {
970 struct zone
*zone
= zones
[i
];
972 if (!cpuset_zone_allowed(zone
, __GFP_HARDWALL
))
975 zone
->temp_priority
= DEF_PRIORITY
;
976 lru_pages
+= zone
->nr_active
+ zone
->nr_inactive
;
979 for (priority
= DEF_PRIORITY
; priority
>= 0; priority
--) {
980 sc
.nr_mapped
= read_page_state(nr_mapped
);
983 disable_swap_token();
984 nr_reclaimed
+= shrink_zones(priority
, zones
, &sc
);
985 shrink_slab(sc
.nr_scanned
, gfp_mask
, lru_pages
);
987 nr_reclaimed
+= reclaim_state
->reclaimed_slab
;
988 reclaim_state
->reclaimed_slab
= 0;
990 total_scanned
+= sc
.nr_scanned
;
991 if (nr_reclaimed
>= sc
.swap_cluster_max
) {
997 * Try to write back as many pages as we just scanned. This
998 * tends to cause slow streaming writers to write data to the
999 * disk smoothly, at the dirtying rate, which is nice. But
1000 * that's undesirable in laptop mode, where we *want* lumpy
1001 * writeout. So in laptop mode, write out the whole world.
1003 if (total_scanned
> sc
.swap_cluster_max
+
1004 sc
.swap_cluster_max
/ 2) {
1005 wakeup_pdflush(laptop_mode
? 0 : total_scanned
);
1006 sc
.may_writepage
= 1;
1009 /* Take a nap, wait for some writeback to complete */
1010 if (sc
.nr_scanned
&& priority
< DEF_PRIORITY
- 2)
1011 blk_congestion_wait(WRITE
, HZ
/10);
1014 for (i
= 0; zones
[i
] != 0; i
++) {
1015 struct zone
*zone
= zones
[i
];
1017 if (!cpuset_zone_allowed(zone
, __GFP_HARDWALL
))
1020 zone
->prev_priority
= zone
->temp_priority
;
1026 * For kswapd, balance_pgdat() will work across all this node's zones until
1027 * they are all at pages_high.
1029 * Returns the number of pages which were actually freed.
1031 * There is special handling here for zones which are full of pinned pages.
1032 * This can happen if the pages are all mlocked, or if they are all used by
1033 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
1034 * What we do is to detect the case where all pages in the zone have been
1035 * scanned twice and there has been zero successful reclaim. Mark the zone as
1036 * dead and from now on, only perform a short scan. Basically we're polling
1037 * the zone for when the problem goes away.
1039 * kswapd scans the zones in the highmem->normal->dma direction. It skips
1040 * zones which have free_pages > pages_high, but once a zone is found to have
1041 * free_pages <= pages_high, we scan that zone and the lower zones regardless
1042 * of the number of free pages in the lower zones. This interoperates with
1043 * the page allocator fallback scheme to ensure that aging of pages is balanced
1046 static unsigned long balance_pgdat(pg_data_t
*pgdat
, int order
)
1051 unsigned long total_scanned
;
1052 unsigned long nr_reclaimed
;
1053 struct reclaim_state
*reclaim_state
= current
->reclaim_state
;
1054 struct scan_control sc
= {
1055 .gfp_mask
= GFP_KERNEL
,
1057 .swap_cluster_max
= SWAP_CLUSTER_MAX
,
1058 .swappiness
= vm_swappiness
,
1064 sc
.may_writepage
= !laptop_mode
;
1065 sc
.nr_mapped
= read_page_state(nr_mapped
);
1067 inc_page_state(pageoutrun
);
1069 for (i
= 0; i
< pgdat
->nr_zones
; i
++) {
1070 struct zone
*zone
= pgdat
->node_zones
+ i
;
1072 zone
->temp_priority
= DEF_PRIORITY
;
1075 for (priority
= DEF_PRIORITY
; priority
>= 0; priority
--) {
1076 int end_zone
= 0; /* Inclusive. 0 = ZONE_DMA */
1077 unsigned long lru_pages
= 0;
1079 /* The swap token gets in the way of swapout... */
1081 disable_swap_token();
1086 * Scan in the highmem->dma direction for the highest
1087 * zone which needs scanning
1089 for (i
= pgdat
->nr_zones
- 1; i
>= 0; i
--) {
1090 struct zone
*zone
= pgdat
->node_zones
+ i
;
1092 if (!populated_zone(zone
))
1095 if (zone
->all_unreclaimable
&& priority
!= DEF_PRIORITY
)
1098 if (!zone_watermark_ok(zone
, order
, zone
->pages_high
,
1106 for (i
= 0; i
<= end_zone
; i
++) {
1107 struct zone
*zone
= pgdat
->node_zones
+ i
;
1109 lru_pages
+= zone
->nr_active
+ zone
->nr_inactive
;
1113 * Now scan the zone in the dma->highmem direction, stopping
1114 * at the last zone which needs scanning.
1116 * We do this because the page allocator works in the opposite
1117 * direction. This prevents the page allocator from allocating
1118 * pages behind kswapd's direction of progress, which would
1119 * cause too much scanning of the lower zones.
1121 for (i
= 0; i
<= end_zone
; i
++) {
1122 struct zone
*zone
= pgdat
->node_zones
+ i
;
1125 if (!populated_zone(zone
))
1128 if (zone
->all_unreclaimable
&& priority
!= DEF_PRIORITY
)
1131 if (!zone_watermark_ok(zone
, order
, zone
->pages_high
,
1134 zone
->temp_priority
= priority
;
1135 if (zone
->prev_priority
> priority
)
1136 zone
->prev_priority
= priority
;
1138 nr_reclaimed
+= shrink_zone(priority
, zone
, &sc
);
1139 reclaim_state
->reclaimed_slab
= 0;
1140 nr_slab
= shrink_slab(sc
.nr_scanned
, GFP_KERNEL
,
1142 nr_reclaimed
+= reclaim_state
->reclaimed_slab
;
1143 total_scanned
+= sc
.nr_scanned
;
1144 if (zone
->all_unreclaimable
)
1146 if (nr_slab
== 0 && zone
->pages_scanned
>=
1147 (zone
->nr_active
+ zone
->nr_inactive
) * 4)
1148 zone
->all_unreclaimable
= 1;
1150 * If we've done a decent amount of scanning and
1151 * the reclaim ratio is low, start doing writepage
1152 * even in laptop mode
1154 if (total_scanned
> SWAP_CLUSTER_MAX
* 2 &&
1155 total_scanned
> nr_reclaimed
+ nr_reclaimed
/ 2)
1156 sc
.may_writepage
= 1;
1159 break; /* kswapd: all done */
1161 * OK, kswapd is getting into trouble. Take a nap, then take
1162 * another pass across the zones.
1164 if (total_scanned
&& priority
< DEF_PRIORITY
- 2)
1165 blk_congestion_wait(WRITE
, HZ
/10);
1168 * We do this so kswapd doesn't build up large priorities for
1169 * example when it is freeing in parallel with allocators. It
1170 * matches the direct reclaim path behaviour in terms of impact
1171 * on zone->*_priority.
1173 if (nr_reclaimed
>= SWAP_CLUSTER_MAX
)
1177 for (i
= 0; i
< pgdat
->nr_zones
; i
++) {
1178 struct zone
*zone
= pgdat
->node_zones
+ i
;
1180 zone
->prev_priority
= zone
->temp_priority
;
1182 if (!all_zones_ok
) {
1187 return nr_reclaimed
;
1191 * The background pageout daemon, started as a kernel thread
1192 * from the init process.
1194 * This basically trickles out pages so that we have _some_
1195 * free memory available even if there is no other activity
1196 * that frees anything up. This is needed for things like routing
1197 * etc, where we otherwise might have all activity going on in
1198 * asynchronous contexts that cannot page things out.
1200 * If there are applications that are active memory-allocators
1201 * (most normal use), this basically shouldn't matter.
1203 static int kswapd(void *p
)
1205 unsigned long order
;
1206 pg_data_t
*pgdat
= (pg_data_t
*)p
;
1207 struct task_struct
*tsk
= current
;
1209 struct reclaim_state reclaim_state
= {
1210 .reclaimed_slab
= 0,
1214 daemonize("kswapd%d", pgdat
->node_id
);
1215 cpumask
= node_to_cpumask(pgdat
->node_id
);
1216 if (!cpus_empty(cpumask
))
1217 set_cpus_allowed(tsk
, cpumask
);
1218 current
->reclaim_state
= &reclaim_state
;
1221 * Tell the memory management that we're a "memory allocator",
1222 * and that if we need more memory we should get access to it
1223 * regardless (see "__alloc_pages()"). "kswapd" should
1224 * never get caught in the normal page freeing logic.
1226 * (Kswapd normally doesn't need memory anyway, but sometimes
1227 * you need a small amount of memory in order to be able to
1228 * page out something else, and this flag essentially protects
1229 * us from recursively trying to free more memory as we're
1230 * trying to free the first piece of memory in the first place).
1232 tsk
->flags
|= PF_MEMALLOC
| PF_SWAPWRITE
| PF_KSWAPD
;
1236 unsigned long new_order
;
1240 prepare_to_wait(&pgdat
->kswapd_wait
, &wait
, TASK_INTERRUPTIBLE
);
1241 new_order
= pgdat
->kswapd_max_order
;
1242 pgdat
->kswapd_max_order
= 0;
1243 if (order
< new_order
) {
1245 * Don't sleep if someone wants a larger 'order'
1251 order
= pgdat
->kswapd_max_order
;
1253 finish_wait(&pgdat
->kswapd_wait
, &wait
);
1255 balance_pgdat(pgdat
, order
);
1261 * A zone is low on free memory, so wake its kswapd task to service it.
1263 void wakeup_kswapd(struct zone
*zone
, int order
)
1267 if (!populated_zone(zone
))
1270 pgdat
= zone
->zone_pgdat
;
1271 if (zone_watermark_ok(zone
, order
, zone
->pages_low
, 0, 0))
1273 if (pgdat
->kswapd_max_order
< order
)
1274 pgdat
->kswapd_max_order
= order
;
1275 if (!cpuset_zone_allowed(zone
, __GFP_HARDWALL
))
1277 if (!waitqueue_active(&pgdat
->kswapd_wait
))
1279 wake_up_interruptible(&pgdat
->kswapd_wait
);
1284 * Helper function for shrink_all_memory(). Tries to reclaim 'nr_pages' pages
1285 * from LRU lists system-wide, for given pass and priority, and returns the
1286 * number of reclaimed pages
1288 * For pass > 3 we also try to shrink the LRU lists that contain a few pages
1290 static unsigned long shrink_all_zones(unsigned long nr_pages
, int pass
,
1291 int prio
, struct scan_control
*sc
)
1294 unsigned long nr_to_scan
, ret
= 0;
1296 for_each_zone(zone
) {
1298 if (!populated_zone(zone
))
1301 if (zone
->all_unreclaimable
&& prio
!= DEF_PRIORITY
)
1304 /* For pass = 0 we don't shrink the active list */
1306 zone
->nr_scan_active
+= (zone
->nr_active
>> prio
) + 1;
1307 if (zone
->nr_scan_active
>= nr_pages
|| pass
> 3) {
1308 zone
->nr_scan_active
= 0;
1309 nr_to_scan
= min(nr_pages
, zone
->nr_active
);
1310 shrink_active_list(nr_to_scan
, zone
, sc
);
1314 zone
->nr_scan_inactive
+= (zone
->nr_inactive
>> prio
) + 1;
1315 if (zone
->nr_scan_inactive
>= nr_pages
|| pass
> 3) {
1316 zone
->nr_scan_inactive
= 0;
1317 nr_to_scan
= min(nr_pages
, zone
->nr_inactive
);
1318 ret
+= shrink_inactive_list(nr_to_scan
, zone
, sc
);
1319 if (ret
>= nr_pages
)
1328 * Try to free `nr_pages' of memory, system-wide, and return the number of
1331 * Rather than trying to age LRUs the aim is to preserve the overall
1332 * LRU order by reclaiming preferentially
1333 * inactive > active > active referenced > active mapped
1335 unsigned long shrink_all_memory(unsigned long nr_pages
)
1337 unsigned long lru_pages
, nr_slab
;
1338 unsigned long ret
= 0;
1340 struct reclaim_state reclaim_state
;
1342 struct scan_control sc
= {
1343 .gfp_mask
= GFP_KERNEL
,
1345 .swap_cluster_max
= nr_pages
,
1347 .swappiness
= vm_swappiness
,
1350 current
->reclaim_state
= &reclaim_state
;
1354 lru_pages
+= zone
->nr_active
+ zone
->nr_inactive
;
1356 nr_slab
= read_page_state(nr_slab
);
1357 /* If slab caches are huge, it's better to hit them first */
1358 while (nr_slab
>= lru_pages
) {
1359 reclaim_state
.reclaimed_slab
= 0;
1360 shrink_slab(nr_pages
, sc
.gfp_mask
, lru_pages
);
1361 if (!reclaim_state
.reclaimed_slab
)
1364 ret
+= reclaim_state
.reclaimed_slab
;
1365 if (ret
>= nr_pages
)
1368 nr_slab
-= reclaim_state
.reclaimed_slab
;
1372 * We try to shrink LRUs in 5 passes:
1373 * 0 = Reclaim from inactive_list only
1374 * 1 = Reclaim from active list but don't reclaim mapped
1375 * 2 = 2nd pass of type 1
1376 * 3 = Reclaim mapped (normal reclaim)
1377 * 4 = 2nd pass of type 3
1379 for (pass
= 0; pass
< 5; pass
++) {
1382 /* Needed for shrinking slab caches later on */
1384 for_each_zone(zone
) {
1385 lru_pages
+= zone
->nr_active
;
1386 lru_pages
+= zone
->nr_inactive
;
1389 /* Force reclaiming mapped pages in the passes #3 and #4 */
1392 sc
.swappiness
= 100;
1395 for (prio
= DEF_PRIORITY
; prio
>= 0; prio
--) {
1396 unsigned long nr_to_scan
= nr_pages
- ret
;
1398 sc
.nr_mapped
= read_page_state(nr_mapped
);
1401 ret
+= shrink_all_zones(nr_to_scan
, prio
, pass
, &sc
);
1402 if (ret
>= nr_pages
)
1405 reclaim_state
.reclaimed_slab
= 0;
1406 shrink_slab(sc
.nr_scanned
, sc
.gfp_mask
, lru_pages
);
1407 ret
+= reclaim_state
.reclaimed_slab
;
1408 if (ret
>= nr_pages
)
1411 if (sc
.nr_scanned
&& prio
< DEF_PRIORITY
- 2)
1412 blk_congestion_wait(WRITE
, HZ
/ 10);
1419 * If ret = 0, we could not shrink LRUs, but there may be something
1424 reclaim_state
.reclaimed_slab
= 0;
1425 shrink_slab(nr_pages
, sc
.gfp_mask
, lru_pages
);
1426 ret
+= reclaim_state
.reclaimed_slab
;
1427 } while (ret
< nr_pages
&& reclaim_state
.reclaimed_slab
> 0);
1430 current
->reclaim_state
= NULL
;
1436 #ifdef CONFIG_HOTPLUG_CPU
1437 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1438 not required for correctness. So if the last cpu in a node goes
1439 away, we get changed to run anywhere: as the first one comes back,
1440 restore their cpu bindings. */
1441 static int cpu_callback(struct notifier_block
*nfb
,
1442 unsigned long action
, void *hcpu
)
1447 if (action
== CPU_ONLINE
) {
1448 for_each_online_pgdat(pgdat
) {
1449 mask
= node_to_cpumask(pgdat
->node_id
);
1450 if (any_online_cpu(mask
) != NR_CPUS
)
1451 /* One of our CPUs online: restore mask */
1452 set_cpus_allowed(pgdat
->kswapd
, mask
);
1457 #endif /* CONFIG_HOTPLUG_CPU */
1459 static int __init
kswapd_init(void)
1464 for_each_online_pgdat(pgdat
) {
1467 pid
= kernel_thread(kswapd
, pgdat
, CLONE_KERNEL
);
1469 read_lock(&tasklist_lock
);
1470 pgdat
->kswapd
= find_task_by_pid(pid
);
1471 read_unlock(&tasklist_lock
);
1473 total_memory
= nr_free_pagecache_pages();
1474 hotcpu_notifier(cpu_callback
, 0);
1478 module_init(kswapd_init
)
1484 * If non-zero call zone_reclaim when the number of free pages falls below
1487 * In the future we may add flags to the mode. However, the page allocator
1488 * should only have to check that zone_reclaim_mode != 0 before calling
1491 int zone_reclaim_mode __read_mostly
;
1493 #define RECLAIM_OFF 0
1494 #define RECLAIM_ZONE (1<<0) /* Run shrink_cache on the zone */
1495 #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
1496 #define RECLAIM_SWAP (1<<2) /* Swap pages out during reclaim */
1497 #define RECLAIM_SLAB (1<<3) /* Do a global slab shrink if the zone is out of memory */
1500 * Mininum time between zone reclaim scans
1502 int zone_reclaim_interval __read_mostly
= 30*HZ
;
1505 * Priority for ZONE_RECLAIM. This determines the fraction of pages
1506 * of a node considered for each zone_reclaim. 4 scans 1/16th of
1509 #define ZONE_RECLAIM_PRIORITY 4
1512 * Try to free up some pages from this zone through reclaim.
1514 static int __zone_reclaim(struct zone
*zone
, gfp_t gfp_mask
, unsigned int order
)
1516 /* Minimum pages needed in order to stay on node */
1517 const unsigned long nr_pages
= 1 << order
;
1518 struct task_struct
*p
= current
;
1519 struct reclaim_state reclaim_state
;
1521 unsigned long nr_reclaimed
= 0;
1522 struct scan_control sc
= {
1523 .may_writepage
= !!(zone_reclaim_mode
& RECLAIM_WRITE
),
1524 .may_swap
= !!(zone_reclaim_mode
& RECLAIM_SWAP
),
1525 .nr_mapped
= read_page_state(nr_mapped
),
1526 .swap_cluster_max
= max_t(unsigned long, nr_pages
,
1528 .gfp_mask
= gfp_mask
,
1529 .swappiness
= vm_swappiness
,
1532 disable_swap_token();
1535 * We need to be able to allocate from the reserves for RECLAIM_SWAP
1536 * and we also need to be able to write out pages for RECLAIM_WRITE
1539 p
->flags
|= PF_MEMALLOC
| PF_SWAPWRITE
;
1540 reclaim_state
.reclaimed_slab
= 0;
1541 p
->reclaim_state
= &reclaim_state
;
1544 * Free memory by calling shrink zone with increasing priorities
1545 * until we have enough memory freed.
1547 priority
= ZONE_RECLAIM_PRIORITY
;
1549 nr_reclaimed
+= shrink_zone(priority
, zone
, &sc
);
1551 } while (priority
>= 0 && nr_reclaimed
< nr_pages
);
1553 if (nr_reclaimed
< nr_pages
&& (zone_reclaim_mode
& RECLAIM_SLAB
)) {
1555 * shrink_slab() does not currently allow us to determine how
1556 * many pages were freed in this zone. So we just shake the slab
1557 * a bit and then go off node for this particular allocation
1558 * despite possibly having freed enough memory to allocate in
1559 * this zone. If we freed local memory then the next
1560 * allocations will be local again.
1562 * shrink_slab will free memory on all zones and may take
1565 shrink_slab(sc
.nr_scanned
, gfp_mask
, order
);
1568 p
->reclaim_state
= NULL
;
1569 current
->flags
&= ~(PF_MEMALLOC
| PF_SWAPWRITE
);
1571 if (nr_reclaimed
== 0) {
1573 * We were unable to reclaim enough pages to stay on node. We
1574 * now allow off node accesses for a certain time period before
1575 * trying again to reclaim pages from the local zone.
1577 zone
->last_unsuccessful_zone_reclaim
= jiffies
;
1580 return nr_reclaimed
>= nr_pages
;
1583 int zone_reclaim(struct zone
*zone
, gfp_t gfp_mask
, unsigned int order
)
1589 * Do not reclaim if there was a recent unsuccessful attempt at zone
1590 * reclaim. In that case we let allocations go off node for the
1591 * zone_reclaim_interval. Otherwise we would scan for each off-node
1594 if (time_before(jiffies
,
1595 zone
->last_unsuccessful_zone_reclaim
+ zone_reclaim_interval
))
1599 * Avoid concurrent zone reclaims, do not reclaim in a zone that does
1600 * not have reclaimable pages and if we should not delay the allocation
1603 if (!(gfp_mask
& __GFP_WAIT
) ||
1604 zone
->all_unreclaimable
||
1605 atomic_read(&zone
->reclaim_in_progress
) > 0 ||
1606 (current
->flags
& PF_MEMALLOC
))
1610 * Only run zone reclaim on the local zone or on zones that do not
1611 * have associated processors. This will favor the local processor
1612 * over remote processors and spread off node memory allocations
1613 * as wide as possible.
1615 node_id
= zone
->zone_pgdat
->node_id
;
1616 mask
= node_to_cpumask(node_id
);
1617 if (!cpus_empty(mask
) && node_id
!= numa_node_id())
1619 return __zone_reclaim(zone
, gfp_mask
, order
);