inotify: fix race
[linux-2.6.22.y-op.git] / mm / vmscan.c
bloba618717ebe0ba0e19cdf66a2e4a9c0e17bb7a515
1 /*
2 * linux/mm/vmscan.c
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.
14 #include <linux/mm.h>
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/vmstat.h>
23 #include <linux/file.h>
24 #include <linux/writeback.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/cpuset.h>
35 #include <linux/notifier.h>
36 #include <linux/rwsem.h>
37 #include <linux/delay.h>
38 #include <linux/kthread.h>
39 #include <linux/freezer.h>
41 #include <asm/tlbflush.h>
42 #include <asm/div64.h>
44 #include <linux/swapops.h>
46 #include "internal.h"
48 struct scan_control {
49 /* Incremented by the number of inactive pages that were scanned */
50 unsigned long nr_scanned;
52 /* This context's GFP mask */
53 gfp_t gfp_mask;
55 int may_writepage;
57 /* Can pages be swapped as part of reclaim? */
58 int may_swap;
60 /* This context's SWAP_CLUSTER_MAX. If freeing memory for
61 * suspend, we effectively ignore SWAP_CLUSTER_MAX.
62 * In this context, it doesn't matter that we scan the
63 * whole list at once. */
64 int swap_cluster_max;
66 int swappiness;
68 int all_unreclaimable;
72 * The list of shrinker callbacks used by to apply pressure to
73 * ageable caches.
75 struct shrinker {
76 shrinker_t shrinker;
77 struct list_head list;
78 int seeks; /* seeks to recreate an obj */
79 long nr; /* objs pending delete */
82 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
84 #ifdef ARCH_HAS_PREFETCH
85 #define prefetch_prev_lru_page(_page, _base, _field) \
86 do { \
87 if ((_page)->lru.prev != _base) { \
88 struct page *prev; \
90 prev = lru_to_page(&(_page->lru)); \
91 prefetch(&prev->_field); \
92 } \
93 } while (0)
94 #else
95 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
96 #endif
98 #ifdef ARCH_HAS_PREFETCHW
99 #define prefetchw_prev_lru_page(_page, _base, _field) \
100 do { \
101 if ((_page)->lru.prev != _base) { \
102 struct page *prev; \
104 prev = lru_to_page(&(_page->lru)); \
105 prefetchw(&prev->_field); \
107 } while (0)
108 #else
109 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
110 #endif
113 * From 0 .. 100. Higher means more swappy.
115 int vm_swappiness = 60;
116 long vm_total_pages; /* The total number of pages which the VM controls */
118 static LIST_HEAD(shrinker_list);
119 static DECLARE_RWSEM(shrinker_rwsem);
122 * Add a shrinker callback to be called from the vm
124 struct shrinker *set_shrinker(int seeks, shrinker_t theshrinker)
126 struct shrinker *shrinker;
128 shrinker = kmalloc(sizeof(*shrinker), GFP_KERNEL);
129 if (shrinker) {
130 shrinker->shrinker = theshrinker;
131 shrinker->seeks = seeks;
132 shrinker->nr = 0;
133 down_write(&shrinker_rwsem);
134 list_add_tail(&shrinker->list, &shrinker_list);
135 up_write(&shrinker_rwsem);
137 return shrinker;
139 EXPORT_SYMBOL(set_shrinker);
142 * Remove one
144 void remove_shrinker(struct shrinker *shrinker)
146 down_write(&shrinker_rwsem);
147 list_del(&shrinker->list);
148 up_write(&shrinker_rwsem);
149 kfree(shrinker);
151 EXPORT_SYMBOL(remove_shrinker);
153 #define SHRINK_BATCH 128
155 * Call the shrink functions to age shrinkable caches
157 * Here we assume it costs one seek to replace a lru page and that it also
158 * takes a seek to recreate a cache object. With this in mind we age equal
159 * percentages of the lru and ageable caches. This should balance the seeks
160 * generated by these structures.
162 * If the vm encounted mapped pages on the LRU it increase the pressure on
163 * slab to avoid swapping.
165 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
167 * `lru_pages' represents the number of on-LRU pages in all the zones which
168 * are eligible for the caller's allocation attempt. It is used for balancing
169 * slab reclaim versus page reclaim.
171 * Returns the number of slab objects which we shrunk.
173 unsigned long shrink_slab(unsigned long scanned, gfp_t gfp_mask,
174 unsigned long lru_pages)
176 struct shrinker *shrinker;
177 unsigned long ret = 0;
179 if (scanned == 0)
180 scanned = SWAP_CLUSTER_MAX;
182 if (!down_read_trylock(&shrinker_rwsem))
183 return 1; /* Assume we'll be able to shrink next time */
185 list_for_each_entry(shrinker, &shrinker_list, list) {
186 unsigned long long delta;
187 unsigned long total_scan;
188 unsigned long max_pass = (*shrinker->shrinker)(0, gfp_mask);
190 delta = (4 * scanned) / shrinker->seeks;
191 delta *= max_pass;
192 do_div(delta, lru_pages + 1);
193 shrinker->nr += delta;
194 if (shrinker->nr < 0) {
195 printk(KERN_ERR "%s: nr=%ld\n",
196 __FUNCTION__, shrinker->nr);
197 shrinker->nr = max_pass;
201 * Avoid risking looping forever due to too large nr value:
202 * never try to free more than twice the estimate number of
203 * freeable entries.
205 if (shrinker->nr > max_pass * 2)
206 shrinker->nr = max_pass * 2;
208 total_scan = shrinker->nr;
209 shrinker->nr = 0;
211 while (total_scan >= SHRINK_BATCH) {
212 long this_scan = SHRINK_BATCH;
213 int shrink_ret;
214 int nr_before;
216 nr_before = (*shrinker->shrinker)(0, gfp_mask);
217 shrink_ret = (*shrinker->shrinker)(this_scan, gfp_mask);
218 if (shrink_ret == -1)
219 break;
220 if (shrink_ret < nr_before)
221 ret += nr_before - shrink_ret;
222 count_vm_events(SLABS_SCANNED, this_scan);
223 total_scan -= this_scan;
225 cond_resched();
228 shrinker->nr += total_scan;
230 up_read(&shrinker_rwsem);
231 return ret;
234 /* Called without lock on whether page is mapped, so answer is unstable */
235 static inline int page_mapping_inuse(struct page *page)
237 struct address_space *mapping;
239 /* Page is in somebody's page tables. */
240 if (page_mapped(page))
241 return 1;
243 /* Be more reluctant to reclaim swapcache than pagecache */
244 if (PageSwapCache(page))
245 return 1;
247 mapping = page_mapping(page);
248 if (!mapping)
249 return 0;
251 /* File is mmap'd by somebody? */
252 return mapping_mapped(mapping);
255 static inline int is_page_cache_freeable(struct page *page)
257 return page_count(page) - !!PagePrivate(page) == 2;
260 static int may_write_to_queue(struct backing_dev_info *bdi)
262 if (current->flags & PF_SWAPWRITE)
263 return 1;
264 if (!bdi_write_congested(bdi))
265 return 1;
266 if (bdi == current->backing_dev_info)
267 return 1;
268 return 0;
272 * We detected a synchronous write error writing a page out. Probably
273 * -ENOSPC. We need to propagate that into the address_space for a subsequent
274 * fsync(), msync() or close().
276 * The tricky part is that after writepage we cannot touch the mapping: nothing
277 * prevents it from being freed up. But we have a ref on the page and once
278 * that page is locked, the mapping is pinned.
280 * We're allowed to run sleeping lock_page() here because we know the caller has
281 * __GFP_FS.
283 static void handle_write_error(struct address_space *mapping,
284 struct page *page, int error)
286 lock_page(page);
287 if (page_mapping(page) == mapping)
288 mapping_set_error(mapping, error);
289 unlock_page(page);
292 /* possible outcome of pageout() */
293 typedef enum {
294 /* failed to write page out, page is locked */
295 PAGE_KEEP,
296 /* move page to the active list, page is locked */
297 PAGE_ACTIVATE,
298 /* page has been sent to the disk successfully, page is unlocked */
299 PAGE_SUCCESS,
300 /* page is clean and locked */
301 PAGE_CLEAN,
302 } pageout_t;
305 * pageout is called by shrink_page_list() for each dirty page.
306 * Calls ->writepage().
308 static pageout_t pageout(struct page *page, struct address_space *mapping)
311 * If the page is dirty, only perform writeback if that write
312 * will be non-blocking. To prevent this allocation from being
313 * stalled by pagecache activity. But note that there may be
314 * stalls if we need to run get_block(). We could test
315 * PagePrivate for that.
317 * If this process is currently in generic_file_write() against
318 * this page's queue, we can perform writeback even if that
319 * will block.
321 * If the page is swapcache, write it back even if that would
322 * block, for some throttling. This happens by accident, because
323 * swap_backing_dev_info is bust: it doesn't reflect the
324 * congestion state of the swapdevs. Easy to fix, if needed.
325 * See swapfile.c:page_queue_congested().
327 if (!is_page_cache_freeable(page))
328 return PAGE_KEEP;
329 if (!mapping) {
331 * Some data journaling orphaned pages can have
332 * page->mapping == NULL while being dirty with clean buffers.
334 if (PagePrivate(page)) {
335 if (try_to_free_buffers(page)) {
336 ClearPageDirty(page);
337 printk("%s: orphaned page\n", __FUNCTION__);
338 return PAGE_CLEAN;
341 return PAGE_KEEP;
343 if (mapping->a_ops->writepage == NULL)
344 return PAGE_ACTIVATE;
345 if (!may_write_to_queue(mapping->backing_dev_info))
346 return PAGE_KEEP;
348 if (clear_page_dirty_for_io(page)) {
349 int res;
350 struct writeback_control wbc = {
351 .sync_mode = WB_SYNC_NONE,
352 .nr_to_write = SWAP_CLUSTER_MAX,
353 .range_start = 0,
354 .range_end = LLONG_MAX,
355 .nonblocking = 1,
356 .for_reclaim = 1,
359 SetPageReclaim(page);
360 res = mapping->a_ops->writepage(page, &wbc);
361 if (res < 0)
362 handle_write_error(mapping, page, res);
363 if (res == AOP_WRITEPAGE_ACTIVATE) {
364 ClearPageReclaim(page);
365 return PAGE_ACTIVATE;
367 if (!PageWriteback(page)) {
368 /* synchronous write or broken a_ops? */
369 ClearPageReclaim(page);
371 inc_zone_page_state(page, NR_VMSCAN_WRITE);
372 return PAGE_SUCCESS;
375 return PAGE_CLEAN;
379 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
380 * someone else has a ref on the page, abort and return 0. If it was
381 * successfully detached, return 1. Assumes the caller has a single ref on
382 * this page.
384 int remove_mapping(struct address_space *mapping, struct page *page)
386 BUG_ON(!PageLocked(page));
387 BUG_ON(mapping != page_mapping(page));
389 write_lock_irq(&mapping->tree_lock);
391 * The non racy check for a busy page.
393 * Must be careful with the order of the tests. When someone has
394 * a ref to the page, it may be possible that they dirty it then
395 * drop the reference. So if PageDirty is tested before page_count
396 * here, then the following race may occur:
398 * get_user_pages(&page);
399 * [user mapping goes away]
400 * write_to(page);
401 * !PageDirty(page) [good]
402 * SetPageDirty(page);
403 * put_page(page);
404 * !page_count(page) [good, discard it]
406 * [oops, our write_to data is lost]
408 * Reversing the order of the tests ensures such a situation cannot
409 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
410 * load is not satisfied before that of page->_count.
412 * Note that if SetPageDirty is always performed via set_page_dirty,
413 * and thus under tree_lock, then this ordering is not required.
415 if (unlikely(page_count(page) != 2))
416 goto cannot_free;
417 smp_rmb();
418 if (unlikely(PageDirty(page)))
419 goto cannot_free;
421 if (PageSwapCache(page)) {
422 swp_entry_t swap = { .val = page_private(page) };
423 __delete_from_swap_cache(page);
424 write_unlock_irq(&mapping->tree_lock);
425 swap_free(swap);
426 __put_page(page); /* The pagecache ref */
427 return 1;
430 __remove_from_page_cache(page);
431 write_unlock_irq(&mapping->tree_lock);
432 __put_page(page);
433 return 1;
435 cannot_free:
436 write_unlock_irq(&mapping->tree_lock);
437 return 0;
441 * shrink_page_list() returns the number of reclaimed pages
443 static unsigned long shrink_page_list(struct list_head *page_list,
444 struct scan_control *sc)
446 LIST_HEAD(ret_pages);
447 struct pagevec freed_pvec;
448 int pgactivate = 0;
449 unsigned long nr_reclaimed = 0;
451 cond_resched();
453 pagevec_init(&freed_pvec, 1);
454 while (!list_empty(page_list)) {
455 struct address_space *mapping;
456 struct page *page;
457 int may_enter_fs;
458 int referenced;
460 cond_resched();
462 page = lru_to_page(page_list);
463 list_del(&page->lru);
465 if (TestSetPageLocked(page))
466 goto keep;
468 VM_BUG_ON(PageActive(page));
470 sc->nr_scanned++;
472 if (!sc->may_swap && page_mapped(page))
473 goto keep_locked;
475 /* Double the slab pressure for mapped and swapcache pages */
476 if (page_mapped(page) || PageSwapCache(page))
477 sc->nr_scanned++;
479 if (PageWriteback(page))
480 goto keep_locked;
482 referenced = page_referenced(page, 1);
483 /* In active use or really unfreeable? Activate it. */
484 if (referenced && page_mapping_inuse(page))
485 goto activate_locked;
487 #ifdef CONFIG_SWAP
489 * Anonymous process memory has backing store?
490 * Try to allocate it some swap space here.
492 if (PageAnon(page) && !PageSwapCache(page))
493 if (!add_to_swap(page, GFP_ATOMIC))
494 goto activate_locked;
495 #endif /* CONFIG_SWAP */
497 mapping = page_mapping(page);
498 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
499 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
502 * The page is mapped into the page tables of one or more
503 * processes. Try to unmap it here.
505 if (page_mapped(page) && mapping) {
506 switch (try_to_unmap(page, 0)) {
507 case SWAP_FAIL:
508 goto activate_locked;
509 case SWAP_AGAIN:
510 goto keep_locked;
511 case SWAP_SUCCESS:
512 ; /* try to free the page below */
516 if (PageDirty(page)) {
517 if (referenced)
518 goto keep_locked;
519 if (!may_enter_fs)
520 goto keep_locked;
521 if (!sc->may_writepage)
522 goto keep_locked;
524 /* Page is dirty, try to write it out here */
525 switch(pageout(page, mapping)) {
526 case PAGE_KEEP:
527 goto keep_locked;
528 case PAGE_ACTIVATE:
529 goto activate_locked;
530 case PAGE_SUCCESS:
531 if (PageWriteback(page) || PageDirty(page))
532 goto keep;
534 * A synchronous write - probably a ramdisk. Go
535 * ahead and try to reclaim the page.
537 if (TestSetPageLocked(page))
538 goto keep;
539 if (PageDirty(page) || PageWriteback(page))
540 goto keep_locked;
541 mapping = page_mapping(page);
542 case PAGE_CLEAN:
543 ; /* try to free the page below */
548 * If the page has buffers, try to free the buffer mappings
549 * associated with this page. If we succeed we try to free
550 * the page as well.
552 * We do this even if the page is PageDirty().
553 * try_to_release_page() does not perform I/O, but it is
554 * possible for a page to have PageDirty set, but it is actually
555 * clean (all its buffers are clean). This happens if the
556 * buffers were written out directly, with submit_bh(). ext3
557 * will do this, as well as the blockdev mapping.
558 * try_to_release_page() will discover that cleanness and will
559 * drop the buffers and mark the page clean - it can be freed.
561 * Rarely, pages can have buffers and no ->mapping. These are
562 * the pages which were not successfully invalidated in
563 * truncate_complete_page(). We try to drop those buffers here
564 * and if that worked, and the page is no longer mapped into
565 * process address space (page_count == 1) it can be freed.
566 * Otherwise, leave the page on the LRU so it is swappable.
568 if (PagePrivate(page)) {
569 if (!try_to_release_page(page, sc->gfp_mask))
570 goto activate_locked;
571 if (!mapping && page_count(page) == 1)
572 goto free_it;
575 if (!mapping || !remove_mapping(mapping, page))
576 goto keep_locked;
578 free_it:
579 unlock_page(page);
580 nr_reclaimed++;
581 if (!pagevec_add(&freed_pvec, page))
582 __pagevec_release_nonlru(&freed_pvec);
583 continue;
585 activate_locked:
586 SetPageActive(page);
587 pgactivate++;
588 keep_locked:
589 unlock_page(page);
590 keep:
591 list_add(&page->lru, &ret_pages);
592 VM_BUG_ON(PageLRU(page));
594 list_splice(&ret_pages, page_list);
595 if (pagevec_count(&freed_pvec))
596 __pagevec_release_nonlru(&freed_pvec);
597 count_vm_events(PGACTIVATE, pgactivate);
598 return nr_reclaimed;
602 * zone->lru_lock is heavily contended. Some of the functions that
603 * shrink the lists perform better by taking out a batch of pages
604 * and working on them outside the LRU lock.
606 * For pagecache intensive workloads, this function is the hottest
607 * spot in the kernel (apart from copy_*_user functions).
609 * Appropriate locks must be held before calling this function.
611 * @nr_to_scan: The number of pages to look through on the list.
612 * @src: The LRU list to pull pages off.
613 * @dst: The temp list to put pages on to.
614 * @scanned: The number of pages that were scanned.
616 * returns how many pages were moved onto *@dst.
618 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
619 struct list_head *src, struct list_head *dst,
620 unsigned long *scanned)
622 unsigned long nr_taken = 0;
623 struct page *page;
624 unsigned long scan;
626 for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
627 struct list_head *target;
628 page = lru_to_page(src);
629 prefetchw_prev_lru_page(page, src, flags);
631 VM_BUG_ON(!PageLRU(page));
633 list_del(&page->lru);
634 target = src;
635 if (likely(get_page_unless_zero(page))) {
637 * Be careful not to clear PageLRU until after we're
638 * sure the page is not being freed elsewhere -- the
639 * page release code relies on it.
641 ClearPageLRU(page);
642 target = dst;
643 nr_taken++;
644 } /* else it is being freed elsewhere */
646 list_add(&page->lru, target);
649 *scanned = scan;
650 return nr_taken;
654 * shrink_inactive_list() is a helper for shrink_zone(). It returns the number
655 * of reclaimed pages
657 static unsigned long shrink_inactive_list(unsigned long max_scan,
658 struct zone *zone, struct scan_control *sc)
660 LIST_HEAD(page_list);
661 struct pagevec pvec;
662 unsigned long nr_scanned = 0;
663 unsigned long nr_reclaimed = 0;
665 pagevec_init(&pvec, 1);
667 lru_add_drain();
668 spin_lock_irq(&zone->lru_lock);
669 do {
670 struct page *page;
671 unsigned long nr_taken;
672 unsigned long nr_scan;
673 unsigned long nr_freed;
675 nr_taken = isolate_lru_pages(sc->swap_cluster_max,
676 &zone->inactive_list,
677 &page_list, &nr_scan);
678 __mod_zone_page_state(zone, NR_INACTIVE, -nr_taken);
679 zone->pages_scanned += nr_scan;
680 spin_unlock_irq(&zone->lru_lock);
682 nr_scanned += nr_scan;
683 nr_freed = shrink_page_list(&page_list, sc);
684 nr_reclaimed += nr_freed;
685 local_irq_disable();
686 if (current_is_kswapd()) {
687 __count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scan);
688 __count_vm_events(KSWAPD_STEAL, nr_freed);
689 } else
690 __count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scan);
691 __count_zone_vm_events(PGSTEAL, zone, nr_freed);
693 if (nr_taken == 0)
694 goto done;
696 spin_lock(&zone->lru_lock);
698 * Put back any unfreeable pages.
700 while (!list_empty(&page_list)) {
701 page = lru_to_page(&page_list);
702 VM_BUG_ON(PageLRU(page));
703 SetPageLRU(page);
704 list_del(&page->lru);
705 if (PageActive(page))
706 add_page_to_active_list(zone, page);
707 else
708 add_page_to_inactive_list(zone, page);
709 if (!pagevec_add(&pvec, page)) {
710 spin_unlock_irq(&zone->lru_lock);
711 __pagevec_release(&pvec);
712 spin_lock_irq(&zone->lru_lock);
715 } while (nr_scanned < max_scan);
716 spin_unlock(&zone->lru_lock);
717 done:
718 local_irq_enable();
719 pagevec_release(&pvec);
720 return nr_reclaimed;
724 * We are about to scan this zone at a certain priority level. If that priority
725 * level is smaller (ie: more urgent) than the previous priority, then note
726 * that priority level within the zone. This is done so that when the next
727 * process comes in to scan this zone, it will immediately start out at this
728 * priority level rather than having to build up its own scanning priority.
729 * Here, this priority affects only the reclaim-mapped threshold.
731 static inline void note_zone_scanning_priority(struct zone *zone, int priority)
733 if (priority < zone->prev_priority)
734 zone->prev_priority = priority;
737 static inline int zone_is_near_oom(struct zone *zone)
739 return zone->pages_scanned >= (zone_page_state(zone, NR_ACTIVE)
740 + zone_page_state(zone, NR_INACTIVE))*3;
744 * This moves pages from the active list to the inactive list.
746 * We move them the other way if the page is referenced by one or more
747 * processes, from rmap.
749 * If the pages are mostly unmapped, the processing is fast and it is
750 * appropriate to hold zone->lru_lock across the whole operation. But if
751 * the pages are mapped, the processing is slow (page_referenced()) so we
752 * should drop zone->lru_lock around each page. It's impossible to balance
753 * this, so instead we remove the pages from the LRU while processing them.
754 * It is safe to rely on PG_active against the non-LRU pages in here because
755 * nobody will play with that bit on a non-LRU page.
757 * The downside is that we have to touch page->_count against each page.
758 * But we had to alter page->flags anyway.
760 static void shrink_active_list(unsigned long nr_pages, struct zone *zone,
761 struct scan_control *sc, int priority)
763 unsigned long pgmoved;
764 int pgdeactivate = 0;
765 unsigned long pgscanned;
766 LIST_HEAD(l_hold); /* The pages which were snipped off */
767 LIST_HEAD(l_inactive); /* Pages to go onto the inactive_list */
768 LIST_HEAD(l_active); /* Pages to go onto the active_list */
769 struct page *page;
770 struct pagevec pvec;
771 int reclaim_mapped = 0;
773 if (sc->may_swap) {
774 long mapped_ratio;
775 long distress;
776 long swap_tendency;
777 long imbalance;
779 if (zone_is_near_oom(zone))
780 goto force_reclaim_mapped;
783 * `distress' is a measure of how much trouble we're having
784 * reclaiming pages. 0 -> no problems. 100 -> great trouble.
786 distress = 100 >> min(zone->prev_priority, priority);
789 * The point of this algorithm is to decide when to start
790 * reclaiming mapped memory instead of just pagecache. Work out
791 * how much memory
792 * is mapped.
794 mapped_ratio = ((global_page_state(NR_FILE_MAPPED) +
795 global_page_state(NR_ANON_PAGES)) * 100) /
796 vm_total_pages;
799 * Now decide how much we really want to unmap some pages. The
800 * mapped ratio is downgraded - just because there's a lot of
801 * mapped memory doesn't necessarily mean that page reclaim
802 * isn't succeeding.
804 * The distress ratio is important - we don't want to start
805 * going oom.
807 * A 100% value of vm_swappiness overrides this algorithm
808 * altogether.
810 swap_tendency = mapped_ratio / 2 + distress + sc->swappiness;
813 * If there's huge imbalance between active and inactive
814 * (think active 100 times larger than inactive) we should
815 * become more permissive, or the system will take too much
816 * cpu before it start swapping during memory pressure.
817 * Distress is about avoiding early-oom, this is about
818 * making swappiness graceful despite setting it to low
819 * values.
821 * Avoid div by zero with nr_inactive+1, and max resulting
822 * value is vm_total_pages.
824 imbalance = zone_page_state(zone, NR_ACTIVE);
825 imbalance /= zone_page_state(zone, NR_INACTIVE) + 1;
828 * Reduce the effect of imbalance if swappiness is low,
829 * this means for a swappiness very low, the imbalance
830 * must be much higher than 100 for this logic to make
831 * the difference.
833 * Max temporary value is vm_total_pages*100.
835 imbalance *= (vm_swappiness + 1);
836 imbalance /= 100;
839 * If not much of the ram is mapped, makes the imbalance
840 * less relevant, it's high priority we refill the inactive
841 * list with mapped pages only in presence of high ratio of
842 * mapped pages.
844 * Max temporary value is vm_total_pages*100.
846 imbalance *= mapped_ratio;
847 imbalance /= 100;
849 /* apply imbalance feedback to swap_tendency */
850 swap_tendency += imbalance;
853 * Now use this metric to decide whether to start moving mapped
854 * memory onto the inactive list.
856 if (swap_tendency >= 100)
857 force_reclaim_mapped:
858 reclaim_mapped = 1;
861 lru_add_drain();
862 spin_lock_irq(&zone->lru_lock);
863 pgmoved = isolate_lru_pages(nr_pages, &zone->active_list,
864 &l_hold, &pgscanned);
865 zone->pages_scanned += pgscanned;
866 __mod_zone_page_state(zone, NR_ACTIVE, -pgmoved);
867 spin_unlock_irq(&zone->lru_lock);
869 while (!list_empty(&l_hold)) {
870 cond_resched();
871 page = lru_to_page(&l_hold);
872 list_del(&page->lru);
873 if (page_mapped(page)) {
874 if (!reclaim_mapped ||
875 (total_swap_pages == 0 && PageAnon(page)) ||
876 page_referenced(page, 0)) {
877 list_add(&page->lru, &l_active);
878 continue;
881 list_add(&page->lru, &l_inactive);
884 pagevec_init(&pvec, 1);
885 pgmoved = 0;
886 spin_lock_irq(&zone->lru_lock);
887 while (!list_empty(&l_inactive)) {
888 page = lru_to_page(&l_inactive);
889 prefetchw_prev_lru_page(page, &l_inactive, flags);
890 VM_BUG_ON(PageLRU(page));
891 SetPageLRU(page);
892 VM_BUG_ON(!PageActive(page));
893 ClearPageActive(page);
895 list_move(&page->lru, &zone->inactive_list);
896 pgmoved++;
897 if (!pagevec_add(&pvec, page)) {
898 __mod_zone_page_state(zone, NR_INACTIVE, pgmoved);
899 spin_unlock_irq(&zone->lru_lock);
900 pgdeactivate += pgmoved;
901 pgmoved = 0;
902 if (buffer_heads_over_limit)
903 pagevec_strip(&pvec);
904 __pagevec_release(&pvec);
905 spin_lock_irq(&zone->lru_lock);
908 __mod_zone_page_state(zone, NR_INACTIVE, pgmoved);
909 pgdeactivate += pgmoved;
910 if (buffer_heads_over_limit) {
911 spin_unlock_irq(&zone->lru_lock);
912 pagevec_strip(&pvec);
913 spin_lock_irq(&zone->lru_lock);
916 pgmoved = 0;
917 while (!list_empty(&l_active)) {
918 page = lru_to_page(&l_active);
919 prefetchw_prev_lru_page(page, &l_active, flags);
920 VM_BUG_ON(PageLRU(page));
921 SetPageLRU(page);
922 VM_BUG_ON(!PageActive(page));
923 list_move(&page->lru, &zone->active_list);
924 pgmoved++;
925 if (!pagevec_add(&pvec, page)) {
926 __mod_zone_page_state(zone, NR_ACTIVE, pgmoved);
927 pgmoved = 0;
928 spin_unlock_irq(&zone->lru_lock);
929 __pagevec_release(&pvec);
930 spin_lock_irq(&zone->lru_lock);
933 __mod_zone_page_state(zone, NR_ACTIVE, pgmoved);
935 __count_zone_vm_events(PGREFILL, zone, pgscanned);
936 __count_vm_events(PGDEACTIVATE, pgdeactivate);
937 spin_unlock_irq(&zone->lru_lock);
939 pagevec_release(&pvec);
943 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
945 static unsigned long shrink_zone(int priority, struct zone *zone,
946 struct scan_control *sc)
948 unsigned long nr_active;
949 unsigned long nr_inactive;
950 unsigned long nr_to_scan;
951 unsigned long nr_reclaimed = 0;
953 atomic_inc(&zone->reclaim_in_progress);
956 * Add one to `nr_to_scan' just to make sure that the kernel will
957 * slowly sift through the active list.
959 zone->nr_scan_active +=
960 (zone_page_state(zone, NR_ACTIVE) >> priority) + 1;
961 nr_active = zone->nr_scan_active;
962 if (nr_active >= sc->swap_cluster_max)
963 zone->nr_scan_active = 0;
964 else
965 nr_active = 0;
967 zone->nr_scan_inactive +=
968 (zone_page_state(zone, NR_INACTIVE) >> priority) + 1;
969 nr_inactive = zone->nr_scan_inactive;
970 if (nr_inactive >= sc->swap_cluster_max)
971 zone->nr_scan_inactive = 0;
972 else
973 nr_inactive = 0;
975 while (nr_active || nr_inactive) {
976 if (nr_active) {
977 nr_to_scan = min(nr_active,
978 (unsigned long)sc->swap_cluster_max);
979 nr_active -= nr_to_scan;
980 shrink_active_list(nr_to_scan, zone, sc, priority);
983 if (nr_inactive) {
984 nr_to_scan = min(nr_inactive,
985 (unsigned long)sc->swap_cluster_max);
986 nr_inactive -= nr_to_scan;
987 nr_reclaimed += shrink_inactive_list(nr_to_scan, zone,
988 sc);
992 throttle_vm_writeout(sc->gfp_mask);
994 atomic_dec(&zone->reclaim_in_progress);
995 return nr_reclaimed;
999 * This is the direct reclaim path, for page-allocating processes. We only
1000 * try to reclaim pages from zones which will satisfy the caller's allocation
1001 * request.
1003 * We reclaim from a zone even if that zone is over pages_high. Because:
1004 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
1005 * allocation or
1006 * b) The zones may be over pages_high but they must go *over* pages_high to
1007 * satisfy the `incremental min' zone defense algorithm.
1009 * Returns the number of reclaimed pages.
1011 * If a zone is deemed to be full of pinned pages then just give it a light
1012 * scan then give up on it.
1014 static unsigned long shrink_zones(int priority, struct zone **zones,
1015 struct scan_control *sc)
1017 unsigned long nr_reclaimed = 0;
1018 int i;
1020 sc->all_unreclaimable = 1;
1021 for (i = 0; zones[i] != NULL; i++) {
1022 struct zone *zone = zones[i];
1024 if (!populated_zone(zone))
1025 continue;
1027 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1028 continue;
1030 note_zone_scanning_priority(zone, priority);
1032 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1033 continue; /* Let kswapd poll it */
1035 sc->all_unreclaimable = 0;
1037 nr_reclaimed += shrink_zone(priority, zone, sc);
1039 return nr_reclaimed;
1043 * This is the main entry point to direct page reclaim.
1045 * If a full scan of the inactive list fails to free enough memory then we
1046 * are "out of memory" and something needs to be killed.
1048 * If the caller is !__GFP_FS then the probability of a failure is reasonably
1049 * high - the zone may be full of dirty or under-writeback pages, which this
1050 * caller can't do much about. We kick pdflush and take explicit naps in the
1051 * hope that some of these pages can be written. But if the allocating task
1052 * holds filesystem locks which prevent writeout this might not work, and the
1053 * allocation attempt will fail.
1055 unsigned long try_to_free_pages(struct zone **zones, gfp_t gfp_mask)
1057 int priority;
1058 int ret = 0;
1059 unsigned long total_scanned = 0;
1060 unsigned long nr_reclaimed = 0;
1061 struct reclaim_state *reclaim_state = current->reclaim_state;
1062 unsigned long lru_pages = 0;
1063 int i;
1064 struct scan_control sc = {
1065 .gfp_mask = gfp_mask,
1066 .may_writepage = !laptop_mode,
1067 .swap_cluster_max = SWAP_CLUSTER_MAX,
1068 .may_swap = 1,
1069 .swappiness = vm_swappiness,
1072 count_vm_event(ALLOCSTALL);
1074 for (i = 0; zones[i] != NULL; i++) {
1075 struct zone *zone = zones[i];
1077 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1078 continue;
1080 lru_pages += zone_page_state(zone, NR_ACTIVE)
1081 + zone_page_state(zone, NR_INACTIVE);
1084 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1085 sc.nr_scanned = 0;
1086 if (!priority)
1087 disable_swap_token();
1088 nr_reclaimed += shrink_zones(priority, zones, &sc);
1089 shrink_slab(sc.nr_scanned, gfp_mask, lru_pages);
1090 if (reclaim_state) {
1091 nr_reclaimed += reclaim_state->reclaimed_slab;
1092 reclaim_state->reclaimed_slab = 0;
1094 total_scanned += sc.nr_scanned;
1095 if (nr_reclaimed >= sc.swap_cluster_max) {
1096 ret = 1;
1097 goto out;
1101 * Try to write back as many pages as we just scanned. This
1102 * tends to cause slow streaming writers to write data to the
1103 * disk smoothly, at the dirtying rate, which is nice. But
1104 * that's undesirable in laptop mode, where we *want* lumpy
1105 * writeout. So in laptop mode, write out the whole world.
1107 if (total_scanned > sc.swap_cluster_max +
1108 sc.swap_cluster_max / 2) {
1109 wakeup_pdflush(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 congestion_wait(WRITE, HZ/10);
1117 /* top priority shrink_caches still had more to do? don't OOM, then */
1118 if (!sc.all_unreclaimable)
1119 ret = 1;
1120 out:
1122 * Now that we've scanned all the zones at this priority level, note
1123 * that level within the zone so that the next thread which performs
1124 * scanning of this zone will immediately start out at this priority
1125 * level. This affects only the decision whether or not to bring
1126 * mapped pages onto the inactive list.
1128 if (priority < 0)
1129 priority = 0;
1130 for (i = 0; zones[i] != 0; i++) {
1131 struct zone *zone = zones[i];
1133 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1134 continue;
1136 zone->prev_priority = priority;
1138 return ret;
1142 * For kswapd, balance_pgdat() will work across all this node's zones until
1143 * they are all at pages_high.
1145 * Returns the number of pages which were actually freed.
1147 * There is special handling here for zones which are full of pinned pages.
1148 * This can happen if the pages are all mlocked, or if they are all used by
1149 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
1150 * What we do is to detect the case where all pages in the zone have been
1151 * scanned twice and there has been zero successful reclaim. Mark the zone as
1152 * dead and from now on, only perform a short scan. Basically we're polling
1153 * the zone for when the problem goes away.
1155 * kswapd scans the zones in the highmem->normal->dma direction. It skips
1156 * zones which have free_pages > pages_high, but once a zone is found to have
1157 * free_pages <= pages_high, we scan that zone and the lower zones regardless
1158 * of the number of free pages in the lower zones. This interoperates with
1159 * the page allocator fallback scheme to ensure that aging of pages is balanced
1160 * across the zones.
1162 static unsigned long balance_pgdat(pg_data_t *pgdat, int order)
1164 int all_zones_ok;
1165 int priority;
1166 int i;
1167 unsigned long total_scanned;
1168 unsigned long nr_reclaimed;
1169 struct reclaim_state *reclaim_state = current->reclaim_state;
1170 struct scan_control sc = {
1171 .gfp_mask = GFP_KERNEL,
1172 .may_swap = 1,
1173 .swap_cluster_max = SWAP_CLUSTER_MAX,
1174 .swappiness = vm_swappiness,
1177 * temp_priority is used to remember the scanning priority at which
1178 * this zone was successfully refilled to free_pages == pages_high.
1180 int temp_priority[MAX_NR_ZONES];
1182 loop_again:
1183 total_scanned = 0;
1184 nr_reclaimed = 0;
1185 sc.may_writepage = !laptop_mode;
1186 count_vm_event(PAGEOUTRUN);
1188 for (i = 0; i < pgdat->nr_zones; i++)
1189 temp_priority[i] = DEF_PRIORITY;
1191 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1192 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
1193 unsigned long lru_pages = 0;
1195 /* The swap token gets in the way of swapout... */
1196 if (!priority)
1197 disable_swap_token();
1199 all_zones_ok = 1;
1202 * Scan in the highmem->dma direction for the highest
1203 * zone which needs scanning
1205 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
1206 struct zone *zone = pgdat->node_zones + i;
1208 if (!populated_zone(zone))
1209 continue;
1211 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1212 continue;
1214 if (!zone_watermark_ok(zone, order, zone->pages_high,
1215 0, 0)) {
1216 end_zone = i;
1217 break;
1220 if (i < 0)
1221 goto out;
1223 for (i = 0; i <= end_zone; i++) {
1224 struct zone *zone = pgdat->node_zones + i;
1226 lru_pages += zone_page_state(zone, NR_ACTIVE)
1227 + zone_page_state(zone, NR_INACTIVE);
1231 * Now scan the zone in the dma->highmem direction, stopping
1232 * at the last zone which needs scanning.
1234 * We do this because the page allocator works in the opposite
1235 * direction. This prevents the page allocator from allocating
1236 * pages behind kswapd's direction of progress, which would
1237 * cause too much scanning of the lower zones.
1239 for (i = 0; i <= end_zone; i++) {
1240 struct zone *zone = pgdat->node_zones + i;
1241 int nr_slab;
1243 if (!populated_zone(zone))
1244 continue;
1246 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1247 continue;
1249 if (!zone_watermark_ok(zone, order, zone->pages_high,
1250 end_zone, 0))
1251 all_zones_ok = 0;
1252 temp_priority[i] = priority;
1253 sc.nr_scanned = 0;
1254 note_zone_scanning_priority(zone, priority);
1255 nr_reclaimed += shrink_zone(priority, zone, &sc);
1256 reclaim_state->reclaimed_slab = 0;
1257 nr_slab = shrink_slab(sc.nr_scanned, GFP_KERNEL,
1258 lru_pages);
1259 nr_reclaimed += reclaim_state->reclaimed_slab;
1260 total_scanned += sc.nr_scanned;
1261 if (zone->all_unreclaimable)
1262 continue;
1263 if (nr_slab == 0 && zone->pages_scanned >=
1264 (zone_page_state(zone, NR_ACTIVE)
1265 + zone_page_state(zone, NR_INACTIVE)) * 6)
1266 zone->all_unreclaimable = 1;
1268 * If we've done a decent amount of scanning and
1269 * the reclaim ratio is low, start doing writepage
1270 * even in laptop mode
1272 if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
1273 total_scanned > nr_reclaimed + nr_reclaimed / 2)
1274 sc.may_writepage = 1;
1276 if (all_zones_ok)
1277 break; /* kswapd: all done */
1279 * OK, kswapd is getting into trouble. Take a nap, then take
1280 * another pass across the zones.
1282 if (total_scanned && priority < DEF_PRIORITY - 2)
1283 congestion_wait(WRITE, HZ/10);
1286 * We do this so kswapd doesn't build up large priorities for
1287 * example when it is freeing in parallel with allocators. It
1288 * matches the direct reclaim path behaviour in terms of impact
1289 * on zone->*_priority.
1291 if (nr_reclaimed >= SWAP_CLUSTER_MAX)
1292 break;
1294 out:
1296 * Note within each zone the priority level at which this zone was
1297 * brought into a happy state. So that the next thread which scans this
1298 * zone will start out at that priority level.
1300 for (i = 0; i < pgdat->nr_zones; i++) {
1301 struct zone *zone = pgdat->node_zones + i;
1303 zone->prev_priority = temp_priority[i];
1305 if (!all_zones_ok) {
1306 cond_resched();
1308 try_to_freeze();
1310 goto loop_again;
1313 return nr_reclaimed;
1317 * The background pageout daemon, started as a kernel thread
1318 * from the init process.
1320 * This basically trickles out pages so that we have _some_
1321 * free memory available even if there is no other activity
1322 * that frees anything up. This is needed for things like routing
1323 * etc, where we otherwise might have all activity going on in
1324 * asynchronous contexts that cannot page things out.
1326 * If there are applications that are active memory-allocators
1327 * (most normal use), this basically shouldn't matter.
1329 static int kswapd(void *p)
1331 unsigned long order;
1332 pg_data_t *pgdat = (pg_data_t*)p;
1333 struct task_struct *tsk = current;
1334 DEFINE_WAIT(wait);
1335 struct reclaim_state reclaim_state = {
1336 .reclaimed_slab = 0,
1338 cpumask_t cpumask;
1340 cpumask = node_to_cpumask(pgdat->node_id);
1341 if (!cpus_empty(cpumask))
1342 set_cpus_allowed(tsk, cpumask);
1343 current->reclaim_state = &reclaim_state;
1346 * Tell the memory management that we're a "memory allocator",
1347 * and that if we need more memory we should get access to it
1348 * regardless (see "__alloc_pages()"). "kswapd" should
1349 * never get caught in the normal page freeing logic.
1351 * (Kswapd normally doesn't need memory anyway, but sometimes
1352 * you need a small amount of memory in order to be able to
1353 * page out something else, and this flag essentially protects
1354 * us from recursively trying to free more memory as we're
1355 * trying to free the first piece of memory in the first place).
1357 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
1359 order = 0;
1360 for ( ; ; ) {
1361 unsigned long new_order;
1363 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
1364 new_order = pgdat->kswapd_max_order;
1365 pgdat->kswapd_max_order = 0;
1366 if (order < new_order) {
1368 * Don't sleep if someone wants a larger 'order'
1369 * allocation
1371 order = new_order;
1372 } else {
1373 if (!freezing(current))
1374 schedule();
1376 order = pgdat->kswapd_max_order;
1378 finish_wait(&pgdat->kswapd_wait, &wait);
1380 if (!try_to_freeze()) {
1381 /* We can speed up thawing tasks if we don't call
1382 * balance_pgdat after returning from the refrigerator
1384 balance_pgdat(pgdat, order);
1387 return 0;
1391 * A zone is low on free memory, so wake its kswapd task to service it.
1393 void wakeup_kswapd(struct zone *zone, int order)
1395 pg_data_t *pgdat;
1397 if (!populated_zone(zone))
1398 return;
1400 pgdat = zone->zone_pgdat;
1401 if (zone_watermark_ok(zone, order, zone->pages_low, 0, 0))
1402 return;
1403 if (pgdat->kswapd_max_order < order)
1404 pgdat->kswapd_max_order = order;
1405 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1406 return;
1407 if (!waitqueue_active(&pgdat->kswapd_wait))
1408 return;
1409 wake_up_interruptible(&pgdat->kswapd_wait);
1412 #ifdef CONFIG_PM
1414 * Helper function for shrink_all_memory(). Tries to reclaim 'nr_pages' pages
1415 * from LRU lists system-wide, for given pass and priority, and returns the
1416 * number of reclaimed pages
1418 * For pass > 3 we also try to shrink the LRU lists that contain a few pages
1420 static unsigned long shrink_all_zones(unsigned long nr_pages, int prio,
1421 int pass, struct scan_control *sc)
1423 struct zone *zone;
1424 unsigned long nr_to_scan, ret = 0;
1426 for_each_zone(zone) {
1428 if (!populated_zone(zone))
1429 continue;
1431 if (zone->all_unreclaimable && prio != DEF_PRIORITY)
1432 continue;
1434 /* For pass = 0 we don't shrink the active list */
1435 if (pass > 0) {
1436 zone->nr_scan_active +=
1437 (zone_page_state(zone, NR_ACTIVE) >> prio) + 1;
1438 if (zone->nr_scan_active >= nr_pages || pass > 3) {
1439 zone->nr_scan_active = 0;
1440 nr_to_scan = min(nr_pages,
1441 zone_page_state(zone, NR_ACTIVE));
1442 shrink_active_list(nr_to_scan, zone, sc, prio);
1446 zone->nr_scan_inactive +=
1447 (zone_page_state(zone, NR_INACTIVE) >> prio) + 1;
1448 if (zone->nr_scan_inactive >= nr_pages || pass > 3) {
1449 zone->nr_scan_inactive = 0;
1450 nr_to_scan = min(nr_pages,
1451 zone_page_state(zone, NR_INACTIVE));
1452 ret += shrink_inactive_list(nr_to_scan, zone, sc);
1453 if (ret >= nr_pages)
1454 return ret;
1458 return ret;
1461 static unsigned long count_lru_pages(void)
1463 return global_page_state(NR_ACTIVE) + global_page_state(NR_INACTIVE);
1467 * Try to free `nr_pages' of memory, system-wide, and return the number of
1468 * freed pages.
1470 * Rather than trying to age LRUs the aim is to preserve the overall
1471 * LRU order by reclaiming preferentially
1472 * inactive > active > active referenced > active mapped
1474 unsigned long shrink_all_memory(unsigned long nr_pages)
1476 unsigned long lru_pages, nr_slab;
1477 unsigned long ret = 0;
1478 int pass;
1479 struct reclaim_state reclaim_state;
1480 struct scan_control sc = {
1481 .gfp_mask = GFP_KERNEL,
1482 .may_swap = 0,
1483 .swap_cluster_max = nr_pages,
1484 .may_writepage = 1,
1485 .swappiness = vm_swappiness,
1488 current->reclaim_state = &reclaim_state;
1490 lru_pages = count_lru_pages();
1491 nr_slab = global_page_state(NR_SLAB_RECLAIMABLE);
1492 /* If slab caches are huge, it's better to hit them first */
1493 while (nr_slab >= lru_pages) {
1494 reclaim_state.reclaimed_slab = 0;
1495 shrink_slab(nr_pages, sc.gfp_mask, lru_pages);
1496 if (!reclaim_state.reclaimed_slab)
1497 break;
1499 ret += reclaim_state.reclaimed_slab;
1500 if (ret >= nr_pages)
1501 goto out;
1503 nr_slab -= reclaim_state.reclaimed_slab;
1507 * We try to shrink LRUs in 5 passes:
1508 * 0 = Reclaim from inactive_list only
1509 * 1 = Reclaim from active list but don't reclaim mapped
1510 * 2 = 2nd pass of type 1
1511 * 3 = Reclaim mapped (normal reclaim)
1512 * 4 = 2nd pass of type 3
1514 for (pass = 0; pass < 5; pass++) {
1515 int prio;
1517 /* Force reclaiming mapped pages in the passes #3 and #4 */
1518 if (pass > 2) {
1519 sc.may_swap = 1;
1520 sc.swappiness = 100;
1523 for (prio = DEF_PRIORITY; prio >= 0; prio--) {
1524 unsigned long nr_to_scan = nr_pages - ret;
1526 sc.nr_scanned = 0;
1527 ret += shrink_all_zones(nr_to_scan, prio, pass, &sc);
1528 if (ret >= nr_pages)
1529 goto out;
1531 reclaim_state.reclaimed_slab = 0;
1532 shrink_slab(sc.nr_scanned, sc.gfp_mask,
1533 count_lru_pages());
1534 ret += reclaim_state.reclaimed_slab;
1535 if (ret >= nr_pages)
1536 goto out;
1538 if (sc.nr_scanned && prio < DEF_PRIORITY - 2)
1539 congestion_wait(WRITE, HZ / 10);
1544 * If ret = 0, we could not shrink LRUs, but there may be something
1545 * in slab caches
1547 if (!ret) {
1548 do {
1549 reclaim_state.reclaimed_slab = 0;
1550 shrink_slab(nr_pages, sc.gfp_mask, count_lru_pages());
1551 ret += reclaim_state.reclaimed_slab;
1552 } while (ret < nr_pages && reclaim_state.reclaimed_slab > 0);
1555 out:
1556 current->reclaim_state = NULL;
1558 return ret;
1560 #endif
1562 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1563 not required for correctness. So if the last cpu in a node goes
1564 away, we get changed to run anywhere: as the first one comes back,
1565 restore their cpu bindings. */
1566 static int __devinit cpu_callback(struct notifier_block *nfb,
1567 unsigned long action, void *hcpu)
1569 pg_data_t *pgdat;
1570 cpumask_t mask;
1572 if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
1573 for_each_online_pgdat(pgdat) {
1574 mask = node_to_cpumask(pgdat->node_id);
1575 if (any_online_cpu(mask) != NR_CPUS)
1576 /* One of our CPUs online: restore mask */
1577 set_cpus_allowed(pgdat->kswapd, mask);
1580 return NOTIFY_OK;
1584 * This kswapd start function will be called by init and node-hot-add.
1585 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
1587 int kswapd_run(int nid)
1589 pg_data_t *pgdat = NODE_DATA(nid);
1590 int ret = 0;
1592 if (pgdat->kswapd)
1593 return 0;
1595 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
1596 if (IS_ERR(pgdat->kswapd)) {
1597 /* failure at boot is fatal */
1598 BUG_ON(system_state == SYSTEM_BOOTING);
1599 printk("Failed to start kswapd on node %d\n",nid);
1600 ret = -1;
1602 return ret;
1605 static int __init kswapd_init(void)
1607 int nid;
1609 swap_setup();
1610 for_each_online_node(nid)
1611 kswapd_run(nid);
1612 hotcpu_notifier(cpu_callback, 0);
1613 return 0;
1616 module_init(kswapd_init)
1618 #ifdef CONFIG_NUMA
1620 * Zone reclaim mode
1622 * If non-zero call zone_reclaim when the number of free pages falls below
1623 * the watermarks.
1625 int zone_reclaim_mode __read_mostly;
1627 #define RECLAIM_OFF 0
1628 #define RECLAIM_ZONE (1<<0) /* Run shrink_cache on the zone */
1629 #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
1630 #define RECLAIM_SWAP (1<<2) /* Swap pages out during reclaim */
1633 * Priority for ZONE_RECLAIM. This determines the fraction of pages
1634 * of a node considered for each zone_reclaim. 4 scans 1/16th of
1635 * a zone.
1637 #define ZONE_RECLAIM_PRIORITY 4
1640 * Percentage of pages in a zone that must be unmapped for zone_reclaim to
1641 * occur.
1643 int sysctl_min_unmapped_ratio = 1;
1646 * If the number of slab pages in a zone grows beyond this percentage then
1647 * slab reclaim needs to occur.
1649 int sysctl_min_slab_ratio = 5;
1652 * Try to free up some pages from this zone through reclaim.
1654 static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
1656 /* Minimum pages needed in order to stay on node */
1657 const unsigned long nr_pages = 1 << order;
1658 struct task_struct *p = current;
1659 struct reclaim_state reclaim_state;
1660 int priority;
1661 unsigned long nr_reclaimed = 0;
1662 struct scan_control sc = {
1663 .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
1664 .may_swap = !!(zone_reclaim_mode & RECLAIM_SWAP),
1665 .swap_cluster_max = max_t(unsigned long, nr_pages,
1666 SWAP_CLUSTER_MAX),
1667 .gfp_mask = gfp_mask,
1668 .swappiness = vm_swappiness,
1670 unsigned long slab_reclaimable;
1672 disable_swap_token();
1673 cond_resched();
1675 * We need to be able to allocate from the reserves for RECLAIM_SWAP
1676 * and we also need to be able to write out pages for RECLAIM_WRITE
1677 * and RECLAIM_SWAP.
1679 p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
1680 reclaim_state.reclaimed_slab = 0;
1681 p->reclaim_state = &reclaim_state;
1683 if (zone_page_state(zone, NR_FILE_PAGES) -
1684 zone_page_state(zone, NR_FILE_MAPPED) >
1685 zone->min_unmapped_pages) {
1687 * Free memory by calling shrink zone with increasing
1688 * priorities until we have enough memory freed.
1690 priority = ZONE_RECLAIM_PRIORITY;
1691 do {
1692 note_zone_scanning_priority(zone, priority);
1693 nr_reclaimed += shrink_zone(priority, zone, &sc);
1694 priority--;
1695 } while (priority >= 0 && nr_reclaimed < nr_pages);
1698 slab_reclaimable = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
1699 if (slab_reclaimable > zone->min_slab_pages) {
1701 * shrink_slab() does not currently allow us to determine how
1702 * many pages were freed in this zone. So we take the current
1703 * number of slab pages and shake the slab until it is reduced
1704 * by the same nr_pages that we used for reclaiming unmapped
1705 * pages.
1707 * Note that shrink_slab will free memory on all zones and may
1708 * take a long time.
1710 while (shrink_slab(sc.nr_scanned, gfp_mask, order) &&
1711 zone_page_state(zone, NR_SLAB_RECLAIMABLE) >
1712 slab_reclaimable - nr_pages)
1716 * Update nr_reclaimed by the number of slab pages we
1717 * reclaimed from this zone.
1719 nr_reclaimed += slab_reclaimable -
1720 zone_page_state(zone, NR_SLAB_RECLAIMABLE);
1723 p->reclaim_state = NULL;
1724 current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
1725 return nr_reclaimed >= nr_pages;
1728 int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
1730 cpumask_t mask;
1731 int node_id;
1734 * Zone reclaim reclaims unmapped file backed pages and
1735 * slab pages if we are over the defined limits.
1737 * A small portion of unmapped file backed pages is needed for
1738 * file I/O otherwise pages read by file I/O will be immediately
1739 * thrown out if the zone is overallocated. So we do not reclaim
1740 * if less than a specified percentage of the zone is used by
1741 * unmapped file backed pages.
1743 if (zone_page_state(zone, NR_FILE_PAGES) -
1744 zone_page_state(zone, NR_FILE_MAPPED) <= zone->min_unmapped_pages
1745 && zone_page_state(zone, NR_SLAB_RECLAIMABLE)
1746 <= zone->min_slab_pages)
1747 return 0;
1750 * Avoid concurrent zone reclaims, do not reclaim in a zone that does
1751 * not have reclaimable pages and if we should not delay the allocation
1752 * then do not scan.
1754 if (!(gfp_mask & __GFP_WAIT) ||
1755 zone->all_unreclaimable ||
1756 atomic_read(&zone->reclaim_in_progress) > 0 ||
1757 (current->flags & PF_MEMALLOC))
1758 return 0;
1761 * Only run zone reclaim on the local zone or on zones that do not
1762 * have associated processors. This will favor the local processor
1763 * over remote processors and spread off node memory allocations
1764 * as wide as possible.
1766 node_id = zone_to_nid(zone);
1767 mask = node_to_cpumask(node_id);
1768 if (!cpus_empty(mask) && node_id != numa_node_id())
1769 return 0;
1770 return __zone_reclaim(zone, gfp_mask, order);
1772 #endif