Merge git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6
[wrt350n-kernel.git] / mm / vmscan.c
blob65a6dd24ac052def18482f9dd5c087fe60bb8428
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>
40 #include <linux/memcontrol.h>
42 #include <asm/tlbflush.h>
43 #include <asm/div64.h>
45 #include <linux/swapops.h>
47 #include "internal.h"
49 struct scan_control {
50 /* Incremented by the number of inactive pages that were scanned */
51 unsigned long nr_scanned;
53 /* This context's GFP mask */
54 gfp_t gfp_mask;
56 int may_writepage;
58 /* Can pages be swapped as part of reclaim? */
59 int may_swap;
61 /* This context's SWAP_CLUSTER_MAX. If freeing memory for
62 * suspend, we effectively ignore SWAP_CLUSTER_MAX.
63 * In this context, it doesn't matter that we scan the
64 * whole list at once. */
65 int swap_cluster_max;
67 int swappiness;
69 int all_unreclaimable;
71 int order;
74 * Pages that have (or should have) IO pending. If we run into
75 * a lot of these, we're better off waiting a little for IO to
76 * finish rather than scanning more pages in the VM.
78 int nr_io_pages;
80 /* Which cgroup do we reclaim from */
81 struct mem_cgroup *mem_cgroup;
83 /* Pluggable isolate pages callback */
84 unsigned long (*isolate_pages)(unsigned long nr, struct list_head *dst,
85 unsigned long *scanned, int order, int mode,
86 struct zone *z, struct mem_cgroup *mem_cont,
87 int active);
90 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
92 #ifdef ARCH_HAS_PREFETCH
93 #define prefetch_prev_lru_page(_page, _base, _field) \
94 do { \
95 if ((_page)->lru.prev != _base) { \
96 struct page *prev; \
98 prev = lru_to_page(&(_page->lru)); \
99 prefetch(&prev->_field); \
101 } while (0)
102 #else
103 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
104 #endif
106 #ifdef ARCH_HAS_PREFETCHW
107 #define prefetchw_prev_lru_page(_page, _base, _field) \
108 do { \
109 if ((_page)->lru.prev != _base) { \
110 struct page *prev; \
112 prev = lru_to_page(&(_page->lru)); \
113 prefetchw(&prev->_field); \
115 } while (0)
116 #else
117 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
118 #endif
121 * From 0 .. 100. Higher means more swappy.
123 int vm_swappiness = 60;
124 long vm_total_pages; /* The total number of pages which the VM controls */
126 static LIST_HEAD(shrinker_list);
127 static DECLARE_RWSEM(shrinker_rwsem);
129 <<<<<<< HEAD:mm/vmscan.c
130 #ifdef CONFIG_CGROUP_MEM_CONT
131 =======
132 #ifdef CONFIG_CGROUP_MEM_RES_CTLR
133 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:mm/vmscan.c
134 #define scan_global_lru(sc) (!(sc)->mem_cgroup)
135 #else
136 #define scan_global_lru(sc) (1)
137 #endif
140 * Add a shrinker callback to be called from the vm
142 void register_shrinker(struct shrinker *shrinker)
144 shrinker->nr = 0;
145 down_write(&shrinker_rwsem);
146 list_add_tail(&shrinker->list, &shrinker_list);
147 up_write(&shrinker_rwsem);
149 EXPORT_SYMBOL(register_shrinker);
152 * Remove one
154 void unregister_shrinker(struct shrinker *shrinker)
156 down_write(&shrinker_rwsem);
157 list_del(&shrinker->list);
158 up_write(&shrinker_rwsem);
160 EXPORT_SYMBOL(unregister_shrinker);
162 #define SHRINK_BATCH 128
164 * Call the shrink functions to age shrinkable caches
166 * Here we assume it costs one seek to replace a lru page and that it also
167 * takes a seek to recreate a cache object. With this in mind we age equal
168 * percentages of the lru and ageable caches. This should balance the seeks
169 * generated by these structures.
171 * If the vm encountered mapped pages on the LRU it increase the pressure on
172 * slab to avoid swapping.
174 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
176 * `lru_pages' represents the number of on-LRU pages in all the zones which
177 * are eligible for the caller's allocation attempt. It is used for balancing
178 * slab reclaim versus page reclaim.
180 * Returns the number of slab objects which we shrunk.
182 unsigned long shrink_slab(unsigned long scanned, gfp_t gfp_mask,
183 unsigned long lru_pages)
185 struct shrinker *shrinker;
186 unsigned long ret = 0;
188 if (scanned == 0)
189 scanned = SWAP_CLUSTER_MAX;
191 if (!down_read_trylock(&shrinker_rwsem))
192 return 1; /* Assume we'll be able to shrink next time */
194 list_for_each_entry(shrinker, &shrinker_list, list) {
195 unsigned long long delta;
196 unsigned long total_scan;
197 unsigned long max_pass = (*shrinker->shrink)(0, gfp_mask);
199 delta = (4 * scanned) / shrinker->seeks;
200 delta *= max_pass;
201 do_div(delta, lru_pages + 1);
202 shrinker->nr += delta;
203 if (shrinker->nr < 0) {
204 printk(KERN_ERR "%s: nr=%ld\n",
205 __FUNCTION__, shrinker->nr);
206 shrinker->nr = max_pass;
210 * Avoid risking looping forever due to too large nr value:
211 * never try to free more than twice the estimate number of
212 * freeable entries.
214 if (shrinker->nr > max_pass * 2)
215 shrinker->nr = max_pass * 2;
217 total_scan = shrinker->nr;
218 shrinker->nr = 0;
220 while (total_scan >= SHRINK_BATCH) {
221 long this_scan = SHRINK_BATCH;
222 int shrink_ret;
223 int nr_before;
225 nr_before = (*shrinker->shrink)(0, gfp_mask);
226 shrink_ret = (*shrinker->shrink)(this_scan, gfp_mask);
227 if (shrink_ret == -1)
228 break;
229 if (shrink_ret < nr_before)
230 ret += nr_before - shrink_ret;
231 count_vm_events(SLABS_SCANNED, this_scan);
232 total_scan -= this_scan;
234 cond_resched();
237 shrinker->nr += total_scan;
239 up_read(&shrinker_rwsem);
240 return ret;
243 /* Called without lock on whether page is mapped, so answer is unstable */
244 static inline int page_mapping_inuse(struct page *page)
246 struct address_space *mapping;
248 /* Page is in somebody's page tables. */
249 if (page_mapped(page))
250 return 1;
252 /* Be more reluctant to reclaim swapcache than pagecache */
253 if (PageSwapCache(page))
254 return 1;
256 mapping = page_mapping(page);
257 if (!mapping)
258 return 0;
260 /* File is mmap'd by somebody? */
261 return mapping_mapped(mapping);
264 static inline int is_page_cache_freeable(struct page *page)
266 return page_count(page) - !!PagePrivate(page) == 2;
269 static int may_write_to_queue(struct backing_dev_info *bdi)
271 if (current->flags & PF_SWAPWRITE)
272 return 1;
273 if (!bdi_write_congested(bdi))
274 return 1;
275 if (bdi == current->backing_dev_info)
276 return 1;
277 return 0;
281 * We detected a synchronous write error writing a page out. Probably
282 * -ENOSPC. We need to propagate that into the address_space for a subsequent
283 * fsync(), msync() or close().
285 * The tricky part is that after writepage we cannot touch the mapping: nothing
286 * prevents it from being freed up. But we have a ref on the page and once
287 * that page is locked, the mapping is pinned.
289 * We're allowed to run sleeping lock_page() here because we know the caller has
290 * __GFP_FS.
292 static void handle_write_error(struct address_space *mapping,
293 struct page *page, int error)
295 lock_page(page);
296 if (page_mapping(page) == mapping)
297 mapping_set_error(mapping, error);
298 unlock_page(page);
301 /* Request for sync pageout. */
302 enum pageout_io {
303 PAGEOUT_IO_ASYNC,
304 PAGEOUT_IO_SYNC,
307 /* possible outcome of pageout() */
308 typedef enum {
309 /* failed to write page out, page is locked */
310 PAGE_KEEP,
311 /* move page to the active list, page is locked */
312 PAGE_ACTIVATE,
313 /* page has been sent to the disk successfully, page is unlocked */
314 PAGE_SUCCESS,
315 /* page is clean and locked */
316 PAGE_CLEAN,
317 } pageout_t;
320 * pageout is called by shrink_page_list() for each dirty page.
321 * Calls ->writepage().
323 static pageout_t pageout(struct page *page, struct address_space *mapping,
324 enum pageout_io sync_writeback)
327 * If the page is dirty, only perform writeback if that write
328 * will be non-blocking. To prevent this allocation from being
329 * stalled by pagecache activity. But note that there may be
330 * stalls if we need to run get_block(). We could test
331 * PagePrivate for that.
333 * If this process is currently in generic_file_write() against
334 * this page's queue, we can perform writeback even if that
335 * will block.
337 * If the page is swapcache, write it back even if that would
338 * block, for some throttling. This happens by accident, because
339 * swap_backing_dev_info is bust: it doesn't reflect the
340 * congestion state of the swapdevs. Easy to fix, if needed.
341 * See swapfile.c:page_queue_congested().
343 if (!is_page_cache_freeable(page))
344 return PAGE_KEEP;
345 if (!mapping) {
347 * Some data journaling orphaned pages can have
348 * page->mapping == NULL while being dirty with clean buffers.
350 if (PagePrivate(page)) {
351 if (try_to_free_buffers(page)) {
352 ClearPageDirty(page);
353 printk("%s: orphaned page\n", __FUNCTION__);
354 return PAGE_CLEAN;
357 return PAGE_KEEP;
359 if (mapping->a_ops->writepage == NULL)
360 return PAGE_ACTIVATE;
361 if (!may_write_to_queue(mapping->backing_dev_info))
362 return PAGE_KEEP;
364 if (clear_page_dirty_for_io(page)) {
365 int res;
366 struct writeback_control wbc = {
367 .sync_mode = WB_SYNC_NONE,
368 .nr_to_write = SWAP_CLUSTER_MAX,
369 .range_start = 0,
370 .range_end = LLONG_MAX,
371 .nonblocking = 1,
372 .for_reclaim = 1,
375 SetPageReclaim(page);
376 res = mapping->a_ops->writepage(page, &wbc);
377 if (res < 0)
378 handle_write_error(mapping, page, res);
379 if (res == AOP_WRITEPAGE_ACTIVATE) {
380 ClearPageReclaim(page);
381 return PAGE_ACTIVATE;
385 * Wait on writeback if requested to. This happens when
386 * direct reclaiming a large contiguous area and the
387 * first attempt to free a range of pages fails.
389 if (PageWriteback(page) && sync_writeback == PAGEOUT_IO_SYNC)
390 wait_on_page_writeback(page);
392 if (!PageWriteback(page)) {
393 /* synchronous write or broken a_ops? */
394 ClearPageReclaim(page);
396 inc_zone_page_state(page, NR_VMSCAN_WRITE);
397 return PAGE_SUCCESS;
400 return PAGE_CLEAN;
404 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
405 * someone else has a ref on the page, abort and return 0. If it was
406 * successfully detached, return 1. Assumes the caller has a single ref on
407 * this page.
409 int remove_mapping(struct address_space *mapping, struct page *page)
411 BUG_ON(!PageLocked(page));
412 BUG_ON(mapping != page_mapping(page));
414 write_lock_irq(&mapping->tree_lock);
416 * The non racy check for a busy page.
418 * Must be careful with the order of the tests. When someone has
419 * a ref to the page, it may be possible that they dirty it then
420 * drop the reference. So if PageDirty is tested before page_count
421 * here, then the following race may occur:
423 * get_user_pages(&page);
424 * [user mapping goes away]
425 * write_to(page);
426 * !PageDirty(page) [good]
427 * SetPageDirty(page);
428 * put_page(page);
429 * !page_count(page) [good, discard it]
431 * [oops, our write_to data is lost]
433 * Reversing the order of the tests ensures such a situation cannot
434 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
435 * load is not satisfied before that of page->_count.
437 * Note that if SetPageDirty is always performed via set_page_dirty,
438 * and thus under tree_lock, then this ordering is not required.
440 if (unlikely(page_count(page) != 2))
441 goto cannot_free;
442 smp_rmb();
443 if (unlikely(PageDirty(page)))
444 goto cannot_free;
446 if (PageSwapCache(page)) {
447 swp_entry_t swap = { .val = page_private(page) };
448 __delete_from_swap_cache(page);
449 write_unlock_irq(&mapping->tree_lock);
450 swap_free(swap);
451 __put_page(page); /* The pagecache ref */
452 return 1;
455 __remove_from_page_cache(page);
456 write_unlock_irq(&mapping->tree_lock);
457 __put_page(page);
458 return 1;
460 cannot_free:
461 write_unlock_irq(&mapping->tree_lock);
462 return 0;
466 * shrink_page_list() returns the number of reclaimed pages
468 static unsigned long shrink_page_list(struct list_head *page_list,
469 struct scan_control *sc,
470 enum pageout_io sync_writeback)
472 LIST_HEAD(ret_pages);
473 struct pagevec freed_pvec;
474 int pgactivate = 0;
475 unsigned long nr_reclaimed = 0;
477 cond_resched();
479 pagevec_init(&freed_pvec, 1);
480 while (!list_empty(page_list)) {
481 struct address_space *mapping;
482 struct page *page;
483 int may_enter_fs;
484 int referenced;
486 cond_resched();
488 page = lru_to_page(page_list);
489 list_del(&page->lru);
491 if (TestSetPageLocked(page))
492 goto keep;
494 VM_BUG_ON(PageActive(page));
496 sc->nr_scanned++;
498 if (!sc->may_swap && page_mapped(page))
499 goto keep_locked;
501 /* Double the slab pressure for mapped and swapcache pages */
502 if (page_mapped(page) || PageSwapCache(page))
503 sc->nr_scanned++;
505 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
506 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
508 if (PageWriteback(page)) {
510 * Synchronous reclaim is performed in two passes,
511 * first an asynchronous pass over the list to
512 * start parallel writeback, and a second synchronous
513 * pass to wait for the IO to complete. Wait here
514 * for any page for which writeback has already
515 * started.
517 if (sync_writeback == PAGEOUT_IO_SYNC && may_enter_fs)
518 wait_on_page_writeback(page);
519 else {
520 sc->nr_io_pages++;
521 goto keep_locked;
525 referenced = page_referenced(page, 1, sc->mem_cgroup);
526 /* In active use or really unfreeable? Activate it. */
527 if (sc->order <= PAGE_ALLOC_COSTLY_ORDER &&
528 referenced && page_mapping_inuse(page))
529 goto activate_locked;
531 #ifdef CONFIG_SWAP
533 * Anonymous process memory has backing store?
534 * Try to allocate it some swap space here.
536 if (PageAnon(page) && !PageSwapCache(page))
537 if (!add_to_swap(page, GFP_ATOMIC))
538 goto activate_locked;
539 #endif /* CONFIG_SWAP */
541 mapping = page_mapping(page);
544 * The page is mapped into the page tables of one or more
545 * processes. Try to unmap it here.
547 if (page_mapped(page) && mapping) {
548 switch (try_to_unmap(page, 0)) {
549 case SWAP_FAIL:
550 goto activate_locked;
551 case SWAP_AGAIN:
552 goto keep_locked;
553 case SWAP_SUCCESS:
554 ; /* try to free the page below */
558 if (PageDirty(page)) {
559 if (sc->order <= PAGE_ALLOC_COSTLY_ORDER && referenced)
560 goto keep_locked;
561 if (!may_enter_fs) {
562 sc->nr_io_pages++;
563 goto keep_locked;
565 if (!sc->may_writepage)
566 goto keep_locked;
568 /* Page is dirty, try to write it out here */
569 switch (pageout(page, mapping, sync_writeback)) {
570 case PAGE_KEEP:
571 goto keep_locked;
572 case PAGE_ACTIVATE:
573 goto activate_locked;
574 case PAGE_SUCCESS:
575 if (PageWriteback(page) || PageDirty(page)) {
576 sc->nr_io_pages++;
577 goto keep;
580 * A synchronous write - probably a ramdisk. Go
581 * ahead and try to reclaim the page.
583 if (TestSetPageLocked(page))
584 goto keep;
585 if (PageDirty(page) || PageWriteback(page))
586 goto keep_locked;
587 mapping = page_mapping(page);
588 case PAGE_CLEAN:
589 ; /* try to free the page below */
594 * If the page has buffers, try to free the buffer mappings
595 * associated with this page. If we succeed we try to free
596 * the page as well.
598 * We do this even if the page is PageDirty().
599 * try_to_release_page() does not perform I/O, but it is
600 * possible for a page to have PageDirty set, but it is actually
601 * clean (all its buffers are clean). This happens if the
602 * buffers were written out directly, with submit_bh(). ext3
603 * will do this, as well as the blockdev mapping.
604 * try_to_release_page() will discover that cleanness and will
605 * drop the buffers and mark the page clean - it can be freed.
607 * Rarely, pages can have buffers and no ->mapping. These are
608 * the pages which were not successfully invalidated in
609 * truncate_complete_page(). We try to drop those buffers here
610 * and if that worked, and the page is no longer mapped into
611 * process address space (page_count == 1) it can be freed.
612 * Otherwise, leave the page on the LRU so it is swappable.
614 if (PagePrivate(page)) {
615 if (!try_to_release_page(page, sc->gfp_mask))
616 goto activate_locked;
617 if (!mapping && page_count(page) == 1)
618 goto free_it;
621 if (!mapping || !remove_mapping(mapping, page))
622 goto keep_locked;
624 free_it:
625 unlock_page(page);
626 nr_reclaimed++;
627 if (!pagevec_add(&freed_pvec, page))
628 __pagevec_release_nonlru(&freed_pvec);
629 continue;
631 activate_locked:
632 SetPageActive(page);
633 pgactivate++;
634 keep_locked:
635 unlock_page(page);
636 keep:
637 list_add(&page->lru, &ret_pages);
638 VM_BUG_ON(PageLRU(page));
640 list_splice(&ret_pages, page_list);
641 if (pagevec_count(&freed_pvec))
642 __pagevec_release_nonlru(&freed_pvec);
643 count_vm_events(PGACTIVATE, pgactivate);
644 return nr_reclaimed;
647 /* LRU Isolation modes. */
648 #define ISOLATE_INACTIVE 0 /* Isolate inactive pages. */
649 #define ISOLATE_ACTIVE 1 /* Isolate active pages. */
650 #define ISOLATE_BOTH 2 /* Isolate both active and inactive pages. */
653 * Attempt to remove the specified page from its LRU. Only take this page
654 * if it is of the appropriate PageActive status. Pages which are being
655 * freed elsewhere are also ignored.
657 * page: page to consider
658 * mode: one of the LRU isolation modes defined above
660 * returns 0 on success, -ve errno on failure.
662 int __isolate_lru_page(struct page *page, int mode)
664 int ret = -EINVAL;
666 /* Only take pages on the LRU. */
667 if (!PageLRU(page))
668 return ret;
671 * When checking the active state, we need to be sure we are
672 * dealing with comparible boolean values. Take the logical not
673 * of each.
675 if (mode != ISOLATE_BOTH && (!PageActive(page) != !mode))
676 return ret;
678 ret = -EBUSY;
679 if (likely(get_page_unless_zero(page))) {
681 * Be careful not to clear PageLRU until after we're
682 * sure the page is not being freed elsewhere -- the
683 * page release code relies on it.
685 ClearPageLRU(page);
686 ret = 0;
689 return ret;
693 * zone->lru_lock is heavily contended. Some of the functions that
694 * shrink the lists perform better by taking out a batch of pages
695 * and working on them outside the LRU lock.
697 * For pagecache intensive workloads, this function is the hottest
698 * spot in the kernel (apart from copy_*_user functions).
700 * Appropriate locks must be held before calling this function.
702 * @nr_to_scan: The number of pages to look through on the list.
703 * @src: The LRU list to pull pages off.
704 * @dst: The temp list to put pages on to.
705 * @scanned: The number of pages that were scanned.
706 * @order: The caller's attempted allocation order
707 * @mode: One of the LRU isolation modes
709 * returns how many pages were moved onto *@dst.
711 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
712 struct list_head *src, struct list_head *dst,
713 unsigned long *scanned, int order, int mode)
715 unsigned long nr_taken = 0;
716 unsigned long scan;
718 for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
719 struct page *page;
720 unsigned long pfn;
721 unsigned long end_pfn;
722 unsigned long page_pfn;
723 int zone_id;
725 page = lru_to_page(src);
726 prefetchw_prev_lru_page(page, src, flags);
728 VM_BUG_ON(!PageLRU(page));
730 switch (__isolate_lru_page(page, mode)) {
731 case 0:
732 list_move(&page->lru, dst);
733 nr_taken++;
734 break;
736 case -EBUSY:
737 /* else it is being freed elsewhere */
738 list_move(&page->lru, src);
739 continue;
741 default:
742 BUG();
745 if (!order)
746 continue;
749 * Attempt to take all pages in the order aligned region
750 * surrounding the tag page. Only take those pages of
751 * the same active state as that tag page. We may safely
752 * round the target page pfn down to the requested order
753 * as the mem_map is guarenteed valid out to MAX_ORDER,
754 * where that page is in a different zone we will detect
755 * it from its zone id and abort this block scan.
757 zone_id = page_zone_id(page);
758 page_pfn = page_to_pfn(page);
759 pfn = page_pfn & ~((1 << order) - 1);
760 end_pfn = pfn + (1 << order);
761 for (; pfn < end_pfn; pfn++) {
762 struct page *cursor_page;
764 /* The target page is in the block, ignore it. */
765 if (unlikely(pfn == page_pfn))
766 continue;
768 /* Avoid holes within the zone. */
769 if (unlikely(!pfn_valid_within(pfn)))
770 break;
772 cursor_page = pfn_to_page(pfn);
773 /* Check that we have not crossed a zone boundary. */
774 if (unlikely(page_zone_id(cursor_page) != zone_id))
775 continue;
776 switch (__isolate_lru_page(cursor_page, mode)) {
777 case 0:
778 list_move(&cursor_page->lru, dst);
779 nr_taken++;
780 scan++;
781 break;
783 case -EBUSY:
784 /* else it is being freed elsewhere */
785 list_move(&cursor_page->lru, src);
786 default:
787 break;
792 *scanned = scan;
793 return nr_taken;
796 static unsigned long isolate_pages_global(unsigned long nr,
797 struct list_head *dst,
798 unsigned long *scanned, int order,
799 int mode, struct zone *z,
800 struct mem_cgroup *mem_cont,
801 int active)
803 if (active)
804 return isolate_lru_pages(nr, &z->active_list, dst,
805 scanned, order, mode);
806 else
807 return isolate_lru_pages(nr, &z->inactive_list, dst,
808 scanned, order, mode);
812 * clear_active_flags() is a helper for shrink_active_list(), clearing
813 * any active bits from the pages in the list.
815 static unsigned long clear_active_flags(struct list_head *page_list)
817 int nr_active = 0;
818 struct page *page;
820 list_for_each_entry(page, page_list, lru)
821 if (PageActive(page)) {
822 ClearPageActive(page);
823 nr_active++;
826 return nr_active;
830 * shrink_inactive_list() is a helper for shrink_zone(). It returns the number
831 * of reclaimed pages
833 static unsigned long shrink_inactive_list(unsigned long max_scan,
834 struct zone *zone, struct scan_control *sc)
836 LIST_HEAD(page_list);
837 struct pagevec pvec;
838 unsigned long nr_scanned = 0;
839 unsigned long nr_reclaimed = 0;
841 pagevec_init(&pvec, 1);
843 lru_add_drain();
844 spin_lock_irq(&zone->lru_lock);
845 do {
846 struct page *page;
847 unsigned long nr_taken;
848 unsigned long nr_scan;
849 unsigned long nr_freed;
850 unsigned long nr_active;
852 nr_taken = sc->isolate_pages(sc->swap_cluster_max,
853 &page_list, &nr_scan, sc->order,
854 (sc->order > PAGE_ALLOC_COSTLY_ORDER)?
855 ISOLATE_BOTH : ISOLATE_INACTIVE,
856 zone, sc->mem_cgroup, 0);
857 nr_active = clear_active_flags(&page_list);
858 __count_vm_events(PGDEACTIVATE, nr_active);
860 __mod_zone_page_state(zone, NR_ACTIVE, -nr_active);
861 __mod_zone_page_state(zone, NR_INACTIVE,
862 -(nr_taken - nr_active));
863 if (scan_global_lru(sc))
864 zone->pages_scanned += nr_scan;
865 spin_unlock_irq(&zone->lru_lock);
867 nr_scanned += nr_scan;
868 nr_freed = shrink_page_list(&page_list, sc, PAGEOUT_IO_ASYNC);
871 * If we are direct reclaiming for contiguous pages and we do
872 * not reclaim everything in the list, try again and wait
873 * for IO to complete. This will stall high-order allocations
874 * but that should be acceptable to the caller
876 if (nr_freed < nr_taken && !current_is_kswapd() &&
877 sc->order > PAGE_ALLOC_COSTLY_ORDER) {
878 congestion_wait(WRITE, HZ/10);
881 * The attempt at page out may have made some
882 * of the pages active, mark them inactive again.
884 nr_active = clear_active_flags(&page_list);
885 count_vm_events(PGDEACTIVATE, nr_active);
887 nr_freed += shrink_page_list(&page_list, sc,
888 PAGEOUT_IO_SYNC);
891 nr_reclaimed += nr_freed;
892 local_irq_disable();
893 if (current_is_kswapd()) {
894 __count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scan);
895 __count_vm_events(KSWAPD_STEAL, nr_freed);
896 } else if (scan_global_lru(sc))
897 __count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scan);
899 __count_zone_vm_events(PGSTEAL, zone, nr_freed);
901 if (nr_taken == 0)
902 goto done;
904 spin_lock(&zone->lru_lock);
906 * Put back any unfreeable pages.
908 while (!list_empty(&page_list)) {
909 page = lru_to_page(&page_list);
910 VM_BUG_ON(PageLRU(page));
911 SetPageLRU(page);
912 list_del(&page->lru);
913 if (PageActive(page))
914 add_page_to_active_list(zone, page);
915 else
916 add_page_to_inactive_list(zone, page);
917 if (!pagevec_add(&pvec, page)) {
918 spin_unlock_irq(&zone->lru_lock);
919 __pagevec_release(&pvec);
920 spin_lock_irq(&zone->lru_lock);
923 } while (nr_scanned < max_scan);
924 spin_unlock(&zone->lru_lock);
925 done:
926 local_irq_enable();
927 pagevec_release(&pvec);
928 return nr_reclaimed;
932 * We are about to scan this zone at a certain priority level. If that priority
933 * level is smaller (ie: more urgent) than the previous priority, then note
934 * that priority level within the zone. This is done so that when the next
935 * process comes in to scan this zone, it will immediately start out at this
936 * priority level rather than having to build up its own scanning priority.
937 * Here, this priority affects only the reclaim-mapped threshold.
939 static inline void note_zone_scanning_priority(struct zone *zone, int priority)
941 if (priority < zone->prev_priority)
942 zone->prev_priority = priority;
945 static inline int zone_is_near_oom(struct zone *zone)
947 return zone->pages_scanned >= (zone_page_state(zone, NR_ACTIVE)
948 + zone_page_state(zone, NR_INACTIVE))*3;
952 * Determine we should try to reclaim mapped pages.
953 * This is called only when sc->mem_cgroup is NULL.
955 static int calc_reclaim_mapped(struct scan_control *sc, struct zone *zone,
956 int priority)
958 long mapped_ratio;
959 long distress;
960 long swap_tendency;
961 long imbalance;
962 int reclaim_mapped = 0;
963 int prev_priority;
965 if (scan_global_lru(sc) && zone_is_near_oom(zone))
966 return 1;
968 * `distress' is a measure of how much trouble we're having
969 * reclaiming pages. 0 -> no problems. 100 -> great trouble.
971 if (scan_global_lru(sc))
972 prev_priority = zone->prev_priority;
973 else
974 prev_priority = mem_cgroup_get_reclaim_priority(sc->mem_cgroup);
976 distress = 100 >> min(prev_priority, priority);
979 * The point of this algorithm is to decide when to start
980 * reclaiming mapped memory instead of just pagecache. Work out
981 * how much memory
982 * is mapped.
984 if (scan_global_lru(sc))
985 mapped_ratio = ((global_page_state(NR_FILE_MAPPED) +
986 global_page_state(NR_ANON_PAGES)) * 100) /
987 vm_total_pages;
988 else
989 mapped_ratio = mem_cgroup_calc_mapped_ratio(sc->mem_cgroup);
992 * Now decide how much we really want to unmap some pages. The
993 * mapped ratio is downgraded - just because there's a lot of
994 * mapped memory doesn't necessarily mean that page reclaim
995 * isn't succeeding.
997 * The distress ratio is important - we don't want to start
998 * going oom.
1000 * A 100% value of vm_swappiness overrides this algorithm
1001 * altogether.
1003 swap_tendency = mapped_ratio / 2 + distress + sc->swappiness;
1006 * If there's huge imbalance between active and inactive
1007 * (think active 100 times larger than inactive) we should
1008 * become more permissive, or the system will take too much
1009 * cpu before it start swapping during memory pressure.
1010 * Distress is about avoiding early-oom, this is about
1011 * making swappiness graceful despite setting it to low
1012 * values.
1014 * Avoid div by zero with nr_inactive+1, and max resulting
1015 * value is vm_total_pages.
1017 if (scan_global_lru(sc)) {
1018 imbalance = zone_page_state(zone, NR_ACTIVE);
1019 imbalance /= zone_page_state(zone, NR_INACTIVE) + 1;
1020 } else
1021 imbalance = mem_cgroup_reclaim_imbalance(sc->mem_cgroup);
1024 * Reduce the effect of imbalance if swappiness is low,
1025 * this means for a swappiness very low, the imbalance
1026 * must be much higher than 100 for this logic to make
1027 * the difference.
1029 * Max temporary value is vm_total_pages*100.
1031 imbalance *= (vm_swappiness + 1);
1032 imbalance /= 100;
1035 * If not much of the ram is mapped, makes the imbalance
1036 * less relevant, it's high priority we refill the inactive
1037 * list with mapped pages only in presence of high ratio of
1038 * mapped pages.
1040 * Max temporary value is vm_total_pages*100.
1042 imbalance *= mapped_ratio;
1043 imbalance /= 100;
1045 /* apply imbalance feedback to swap_tendency */
1046 swap_tendency += imbalance;
1049 * Now use this metric to decide whether to start moving mapped
1050 * memory onto the inactive list.
1052 if (swap_tendency >= 100)
1053 reclaim_mapped = 1;
1055 return reclaim_mapped;
1059 * This moves pages from the active list to the inactive list.
1061 * We move them the other way if the page is referenced by one or more
1062 * processes, from rmap.
1064 * If the pages are mostly unmapped, the processing is fast and it is
1065 * appropriate to hold zone->lru_lock across the whole operation. But if
1066 * the pages are mapped, the processing is slow (page_referenced()) so we
1067 * should drop zone->lru_lock around each page. It's impossible to balance
1068 * this, so instead we remove the pages from the LRU while processing them.
1069 * It is safe to rely on PG_active against the non-LRU pages in here because
1070 * nobody will play with that bit on a non-LRU page.
1072 * The downside is that we have to touch page->_count against each page.
1073 * But we had to alter page->flags anyway.
1077 static void shrink_active_list(unsigned long nr_pages, struct zone *zone,
1078 struct scan_control *sc, int priority)
1080 unsigned long pgmoved;
1081 int pgdeactivate = 0;
1082 unsigned long pgscanned;
1083 LIST_HEAD(l_hold); /* The pages which were snipped off */
1084 LIST_HEAD(l_inactive); /* Pages to go onto the inactive_list */
1085 LIST_HEAD(l_active); /* Pages to go onto the active_list */
1086 struct page *page;
1087 struct pagevec pvec;
1088 int reclaim_mapped = 0;
1090 if (sc->may_swap)
1091 reclaim_mapped = calc_reclaim_mapped(sc, zone, priority);
1093 lru_add_drain();
1094 spin_lock_irq(&zone->lru_lock);
1095 pgmoved = sc->isolate_pages(nr_pages, &l_hold, &pgscanned, sc->order,
1096 ISOLATE_ACTIVE, zone,
1097 sc->mem_cgroup, 1);
1099 * zone->pages_scanned is used for detect zone's oom
1100 * mem_cgroup remembers nr_scan by itself.
1102 if (scan_global_lru(sc))
1103 zone->pages_scanned += pgscanned;
1105 __mod_zone_page_state(zone, NR_ACTIVE, -pgmoved);
1106 spin_unlock_irq(&zone->lru_lock);
1108 while (!list_empty(&l_hold)) {
1109 cond_resched();
1110 page = lru_to_page(&l_hold);
1111 list_del(&page->lru);
1112 if (page_mapped(page)) {
1113 if (!reclaim_mapped ||
1114 (total_swap_pages == 0 && PageAnon(page)) ||
1115 page_referenced(page, 0, sc->mem_cgroup)) {
1116 list_add(&page->lru, &l_active);
1117 continue;
1120 list_add(&page->lru, &l_inactive);
1123 pagevec_init(&pvec, 1);
1124 pgmoved = 0;
1125 spin_lock_irq(&zone->lru_lock);
1126 while (!list_empty(&l_inactive)) {
1127 page = lru_to_page(&l_inactive);
1128 prefetchw_prev_lru_page(page, &l_inactive, flags);
1129 VM_BUG_ON(PageLRU(page));
1130 SetPageLRU(page);
1131 VM_BUG_ON(!PageActive(page));
1132 ClearPageActive(page);
1134 list_move(&page->lru, &zone->inactive_list);
1135 <<<<<<< HEAD:mm/vmscan.c
1136 mem_cgroup_move_lists(page_get_page_cgroup(page), false);
1137 =======
1138 mem_cgroup_move_lists(page, false);
1139 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:mm/vmscan.c
1140 pgmoved++;
1141 if (!pagevec_add(&pvec, page)) {
1142 __mod_zone_page_state(zone, NR_INACTIVE, pgmoved);
1143 spin_unlock_irq(&zone->lru_lock);
1144 pgdeactivate += pgmoved;
1145 pgmoved = 0;
1146 if (buffer_heads_over_limit)
1147 pagevec_strip(&pvec);
1148 __pagevec_release(&pvec);
1149 spin_lock_irq(&zone->lru_lock);
1152 __mod_zone_page_state(zone, NR_INACTIVE, pgmoved);
1153 pgdeactivate += pgmoved;
1154 if (buffer_heads_over_limit) {
1155 spin_unlock_irq(&zone->lru_lock);
1156 pagevec_strip(&pvec);
1157 spin_lock_irq(&zone->lru_lock);
1160 pgmoved = 0;
1161 while (!list_empty(&l_active)) {
1162 page = lru_to_page(&l_active);
1163 prefetchw_prev_lru_page(page, &l_active, flags);
1164 VM_BUG_ON(PageLRU(page));
1165 SetPageLRU(page);
1166 VM_BUG_ON(!PageActive(page));
1167 <<<<<<< HEAD:mm/vmscan.c
1168 =======
1170 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:mm/vmscan.c
1171 list_move(&page->lru, &zone->active_list);
1172 <<<<<<< HEAD:mm/vmscan.c
1173 mem_cgroup_move_lists(page_get_page_cgroup(page), true);
1174 =======
1175 mem_cgroup_move_lists(page, true);
1176 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:mm/vmscan.c
1177 pgmoved++;
1178 if (!pagevec_add(&pvec, page)) {
1179 __mod_zone_page_state(zone, NR_ACTIVE, pgmoved);
1180 pgmoved = 0;
1181 spin_unlock_irq(&zone->lru_lock);
1182 __pagevec_release(&pvec);
1183 spin_lock_irq(&zone->lru_lock);
1186 __mod_zone_page_state(zone, NR_ACTIVE, pgmoved);
1188 __count_zone_vm_events(PGREFILL, zone, pgscanned);
1189 __count_vm_events(PGDEACTIVATE, pgdeactivate);
1190 spin_unlock_irq(&zone->lru_lock);
1192 pagevec_release(&pvec);
1196 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
1198 static unsigned long shrink_zone(int priority, struct zone *zone,
1199 struct scan_control *sc)
1201 unsigned long nr_active;
1202 unsigned long nr_inactive;
1203 unsigned long nr_to_scan;
1204 unsigned long nr_reclaimed = 0;
1206 if (scan_global_lru(sc)) {
1208 * Add one to nr_to_scan just to make sure that the kernel
1209 * will slowly sift through the active list.
1211 zone->nr_scan_active +=
1212 (zone_page_state(zone, NR_ACTIVE) >> priority) + 1;
1213 nr_active = zone->nr_scan_active;
1214 zone->nr_scan_inactive +=
1215 (zone_page_state(zone, NR_INACTIVE) >> priority) + 1;
1216 nr_inactive = zone->nr_scan_inactive;
1217 if (nr_inactive >= sc->swap_cluster_max)
1218 zone->nr_scan_inactive = 0;
1219 else
1220 nr_inactive = 0;
1222 if (nr_active >= sc->swap_cluster_max)
1223 zone->nr_scan_active = 0;
1224 else
1225 nr_active = 0;
1226 } else {
1228 * This reclaim occurs not because zone memory shortage but
1229 * because memory controller hits its limit.
1230 * Then, don't modify zone reclaim related data.
1232 nr_active = mem_cgroup_calc_reclaim_active(sc->mem_cgroup,
1233 zone, priority);
1235 nr_inactive = mem_cgroup_calc_reclaim_inactive(sc->mem_cgroup,
1236 zone, priority);
1240 while (nr_active || nr_inactive) {
1241 if (nr_active) {
1242 nr_to_scan = min(nr_active,
1243 (unsigned long)sc->swap_cluster_max);
1244 nr_active -= nr_to_scan;
1245 shrink_active_list(nr_to_scan, zone, sc, priority);
1248 if (nr_inactive) {
1249 nr_to_scan = min(nr_inactive,
1250 (unsigned long)sc->swap_cluster_max);
1251 nr_inactive -= nr_to_scan;
1252 nr_reclaimed += shrink_inactive_list(nr_to_scan, zone,
1253 sc);
1257 throttle_vm_writeout(sc->gfp_mask);
1258 return nr_reclaimed;
1262 * This is the direct reclaim path, for page-allocating processes. We only
1263 * try to reclaim pages from zones which will satisfy the caller's allocation
1264 * request.
1266 * We reclaim from a zone even if that zone is over pages_high. Because:
1267 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
1268 * allocation or
1269 * b) The zones may be over pages_high but they must go *over* pages_high to
1270 * satisfy the `incremental min' zone defense algorithm.
1272 * Returns the number of reclaimed pages.
1274 * If a zone is deemed to be full of pinned pages then just give it a light
1275 * scan then give up on it.
1277 static unsigned long shrink_zones(int priority, struct zone **zones,
1278 struct scan_control *sc)
1280 unsigned long nr_reclaimed = 0;
1281 int i;
1284 sc->all_unreclaimable = 1;
1285 for (i = 0; zones[i] != NULL; i++) {
1286 struct zone *zone = zones[i];
1288 if (!populated_zone(zone))
1289 continue;
1291 * Take care memory controller reclaiming has small influence
1292 * to global LRU.
1294 if (scan_global_lru(sc)) {
1295 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1296 continue;
1297 note_zone_scanning_priority(zone, priority);
1299 if (zone_is_all_unreclaimable(zone) &&
1300 priority != DEF_PRIORITY)
1301 continue; /* Let kswapd poll it */
1302 sc->all_unreclaimable = 0;
1303 } else {
1305 * Ignore cpuset limitation here. We just want to reduce
1306 * # of used pages by us regardless of memory shortage.
1308 sc->all_unreclaimable = 0;
1309 mem_cgroup_note_reclaim_priority(sc->mem_cgroup,
1310 priority);
1313 nr_reclaimed += shrink_zone(priority, zone, sc);
1316 return nr_reclaimed;
1320 * This is the main entry point to direct page reclaim.
1322 * If a full scan of the inactive list fails to free enough memory then we
1323 * are "out of memory" and something needs to be killed.
1325 * If the caller is !__GFP_FS then the probability of a failure is reasonably
1326 * high - the zone may be full of dirty or under-writeback pages, which this
1327 * caller can't do much about. We kick pdflush and take explicit naps in the
1328 * hope that some of these pages can be written. But if the allocating task
1329 * holds filesystem locks which prevent writeout this might not work, and the
1330 * allocation attempt will fail.
1332 static unsigned long do_try_to_free_pages(struct zone **zones, gfp_t gfp_mask,
1333 struct scan_control *sc)
1335 int priority;
1336 int ret = 0;
1337 unsigned long total_scanned = 0;
1338 unsigned long nr_reclaimed = 0;
1339 struct reclaim_state *reclaim_state = current->reclaim_state;
1340 unsigned long lru_pages = 0;
1341 int i;
1343 if (scan_global_lru(sc))
1344 count_vm_event(ALLOCSTALL);
1346 * mem_cgroup will not do shrink_slab.
1348 if (scan_global_lru(sc)) {
1349 for (i = 0; zones[i] != NULL; i++) {
1350 struct zone *zone = zones[i];
1352 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1353 continue;
1355 lru_pages += zone_page_state(zone, NR_ACTIVE)
1356 + zone_page_state(zone, NR_INACTIVE);
1360 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1361 sc->nr_scanned = 0;
1362 sc->nr_io_pages = 0;
1363 if (!priority)
1364 disable_swap_token();
1365 nr_reclaimed += shrink_zones(priority, zones, sc);
1367 * Don't shrink slabs when reclaiming memory from
1368 * over limit cgroups
1370 if (scan_global_lru(sc)) {
1371 shrink_slab(sc->nr_scanned, gfp_mask, lru_pages);
1372 if (reclaim_state) {
1373 nr_reclaimed += reclaim_state->reclaimed_slab;
1374 reclaim_state->reclaimed_slab = 0;
1377 total_scanned += sc->nr_scanned;
1378 if (nr_reclaimed >= sc->swap_cluster_max) {
1379 ret = 1;
1380 goto out;
1384 * Try to write back as many pages as we just scanned. This
1385 * tends to cause slow streaming writers to write data to the
1386 * disk smoothly, at the dirtying rate, which is nice. But
1387 * that's undesirable in laptop mode, where we *want* lumpy
1388 * writeout. So in laptop mode, write out the whole world.
1390 if (total_scanned > sc->swap_cluster_max +
1391 sc->swap_cluster_max / 2) {
1392 wakeup_pdflush(laptop_mode ? 0 : total_scanned);
1393 sc->may_writepage = 1;
1396 /* Take a nap, wait for some writeback to complete */
1397 if (sc->nr_scanned && priority < DEF_PRIORITY - 2 &&
1398 sc->nr_io_pages > sc->swap_cluster_max)
1399 congestion_wait(WRITE, HZ/10);
1401 /* top priority shrink_caches still had more to do? don't OOM, then */
1402 if (!sc->all_unreclaimable && scan_global_lru(sc))
1403 ret = 1;
1404 out:
1406 * Now that we've scanned all the zones at this priority level, note
1407 * that level within the zone so that the next thread which performs
1408 * scanning of this zone will immediately start out at this priority
1409 * level. This affects only the decision whether or not to bring
1410 * mapped pages onto the inactive list.
1412 if (priority < 0)
1413 priority = 0;
1415 if (scan_global_lru(sc)) {
1416 for (i = 0; zones[i] != NULL; i++) {
1417 struct zone *zone = zones[i];
1419 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1420 continue;
1422 zone->prev_priority = priority;
1424 } else
1425 mem_cgroup_record_reclaim_priority(sc->mem_cgroup, priority);
1427 return ret;
1430 unsigned long try_to_free_pages(struct zone **zones, int order, gfp_t gfp_mask)
1432 struct scan_control sc = {
1433 .gfp_mask = gfp_mask,
1434 .may_writepage = !laptop_mode,
1435 .swap_cluster_max = SWAP_CLUSTER_MAX,
1436 .may_swap = 1,
1437 .swappiness = vm_swappiness,
1438 .order = order,
1439 .mem_cgroup = NULL,
1440 .isolate_pages = isolate_pages_global,
1443 return do_try_to_free_pages(zones, gfp_mask, &sc);
1446 <<<<<<< HEAD:mm/vmscan.c
1447 #ifdef CONFIG_CGROUP_MEM_CONT
1448 =======
1449 #ifdef CONFIG_CGROUP_MEM_RES_CTLR
1450 >>>>>>> 264e3e889d86e552b4191d69bb60f4f3b383135a:mm/vmscan.c
1452 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *mem_cont,
1453 gfp_t gfp_mask)
1455 struct scan_control sc = {
1456 .gfp_mask = gfp_mask,
1457 .may_writepage = !laptop_mode,
1458 .may_swap = 1,
1459 .swap_cluster_max = SWAP_CLUSTER_MAX,
1460 .swappiness = vm_swappiness,
1461 .order = 0,
1462 .mem_cgroup = mem_cont,
1463 .isolate_pages = mem_cgroup_isolate_pages,
1465 struct zone **zones;
1466 int target_zone = gfp_zone(GFP_HIGHUSER_MOVABLE);
1468 zones = NODE_DATA(numa_node_id())->node_zonelists[target_zone].zones;
1469 if (do_try_to_free_pages(zones, sc.gfp_mask, &sc))
1470 return 1;
1471 return 0;
1473 #endif
1476 * For kswapd, balance_pgdat() will work across all this node's zones until
1477 * they are all at pages_high.
1479 * Returns the number of pages which were actually freed.
1481 * There is special handling here for zones which are full of pinned pages.
1482 * This can happen if the pages are all mlocked, or if they are all used by
1483 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
1484 * What we do is to detect the case where all pages in the zone have been
1485 * scanned twice and there has been zero successful reclaim. Mark the zone as
1486 * dead and from now on, only perform a short scan. Basically we're polling
1487 * the zone for when the problem goes away.
1489 * kswapd scans the zones in the highmem->normal->dma direction. It skips
1490 * zones which have free_pages > pages_high, but once a zone is found to have
1491 * free_pages <= pages_high, we scan that zone and the lower zones regardless
1492 * of the number of free pages in the lower zones. This interoperates with
1493 * the page allocator fallback scheme to ensure that aging of pages is balanced
1494 * across the zones.
1496 static unsigned long balance_pgdat(pg_data_t *pgdat, int order)
1498 int all_zones_ok;
1499 int priority;
1500 int i;
1501 unsigned long total_scanned;
1502 unsigned long nr_reclaimed;
1503 struct reclaim_state *reclaim_state = current->reclaim_state;
1504 struct scan_control sc = {
1505 .gfp_mask = GFP_KERNEL,
1506 .may_swap = 1,
1507 .swap_cluster_max = SWAP_CLUSTER_MAX,
1508 .swappiness = vm_swappiness,
1509 .order = order,
1510 .mem_cgroup = NULL,
1511 .isolate_pages = isolate_pages_global,
1514 * temp_priority is used to remember the scanning priority at which
1515 * this zone was successfully refilled to free_pages == pages_high.
1517 int temp_priority[MAX_NR_ZONES];
1519 loop_again:
1520 total_scanned = 0;
1521 nr_reclaimed = 0;
1522 sc.may_writepage = !laptop_mode;
1523 count_vm_event(PAGEOUTRUN);
1525 for (i = 0; i < pgdat->nr_zones; i++)
1526 temp_priority[i] = DEF_PRIORITY;
1528 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1529 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
1530 unsigned long lru_pages = 0;
1532 /* The swap token gets in the way of swapout... */
1533 if (!priority)
1534 disable_swap_token();
1536 sc.nr_io_pages = 0;
1537 all_zones_ok = 1;
1540 * Scan in the highmem->dma direction for the highest
1541 * zone which needs scanning
1543 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
1544 struct zone *zone = pgdat->node_zones + i;
1546 if (!populated_zone(zone))
1547 continue;
1549 if (zone_is_all_unreclaimable(zone) &&
1550 priority != DEF_PRIORITY)
1551 continue;
1553 if (!zone_watermark_ok(zone, order, zone->pages_high,
1554 0, 0)) {
1555 end_zone = i;
1556 break;
1559 if (i < 0)
1560 goto out;
1562 for (i = 0; i <= end_zone; i++) {
1563 struct zone *zone = pgdat->node_zones + i;
1565 lru_pages += zone_page_state(zone, NR_ACTIVE)
1566 + zone_page_state(zone, NR_INACTIVE);
1570 * Now scan the zone in the dma->highmem direction, stopping
1571 * at the last zone which needs scanning.
1573 * We do this because the page allocator works in the opposite
1574 * direction. This prevents the page allocator from allocating
1575 * pages behind kswapd's direction of progress, which would
1576 * cause too much scanning of the lower zones.
1578 for (i = 0; i <= end_zone; i++) {
1579 struct zone *zone = pgdat->node_zones + i;
1580 int nr_slab;
1582 if (!populated_zone(zone))
1583 continue;
1585 if (zone_is_all_unreclaimable(zone) &&
1586 priority != DEF_PRIORITY)
1587 continue;
1589 if (!zone_watermark_ok(zone, order, zone->pages_high,
1590 end_zone, 0))
1591 all_zones_ok = 0;
1592 temp_priority[i] = priority;
1593 sc.nr_scanned = 0;
1594 note_zone_scanning_priority(zone, priority);
1596 * We put equal pressure on every zone, unless one
1597 * zone has way too many pages free already.
1599 if (!zone_watermark_ok(zone, order, 8*zone->pages_high,
1600 end_zone, 0))
1601 nr_reclaimed += shrink_zone(priority, zone, &sc);
1602 reclaim_state->reclaimed_slab = 0;
1603 nr_slab = shrink_slab(sc.nr_scanned, GFP_KERNEL,
1604 lru_pages);
1605 nr_reclaimed += reclaim_state->reclaimed_slab;
1606 total_scanned += sc.nr_scanned;
1607 if (zone_is_all_unreclaimable(zone))
1608 continue;
1609 if (nr_slab == 0 && zone->pages_scanned >=
1610 (zone_page_state(zone, NR_ACTIVE)
1611 + zone_page_state(zone, NR_INACTIVE)) * 6)
1612 zone_set_flag(zone,
1613 ZONE_ALL_UNRECLAIMABLE);
1615 * If we've done a decent amount of scanning and
1616 * the reclaim ratio is low, start doing writepage
1617 * even in laptop mode
1619 if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
1620 total_scanned > nr_reclaimed + nr_reclaimed / 2)
1621 sc.may_writepage = 1;
1623 if (all_zones_ok)
1624 break; /* kswapd: all done */
1626 * OK, kswapd is getting into trouble. Take a nap, then take
1627 * another pass across the zones.
1629 if (total_scanned && priority < DEF_PRIORITY - 2 &&
1630 sc.nr_io_pages > sc.swap_cluster_max)
1631 congestion_wait(WRITE, HZ/10);
1634 * We do this so kswapd doesn't build up large priorities for
1635 * example when it is freeing in parallel with allocators. It
1636 * matches the direct reclaim path behaviour in terms of impact
1637 * on zone->*_priority.
1639 if (nr_reclaimed >= SWAP_CLUSTER_MAX)
1640 break;
1642 out:
1644 * Note within each zone the priority level at which this zone was
1645 * brought into a happy state. So that the next thread which scans this
1646 * zone will start out at that priority level.
1648 for (i = 0; i < pgdat->nr_zones; i++) {
1649 struct zone *zone = pgdat->node_zones + i;
1651 zone->prev_priority = temp_priority[i];
1653 if (!all_zones_ok) {
1654 cond_resched();
1656 try_to_freeze();
1658 goto loop_again;
1661 return nr_reclaimed;
1665 * The background pageout daemon, started as a kernel thread
1666 * from the init process.
1668 * This basically trickles out pages so that we have _some_
1669 * free memory available even if there is no other activity
1670 * that frees anything up. This is needed for things like routing
1671 * etc, where we otherwise might have all activity going on in
1672 * asynchronous contexts that cannot page things out.
1674 * If there are applications that are active memory-allocators
1675 * (most normal use), this basically shouldn't matter.
1677 static int kswapd(void *p)
1679 unsigned long order;
1680 pg_data_t *pgdat = (pg_data_t*)p;
1681 struct task_struct *tsk = current;
1682 DEFINE_WAIT(wait);
1683 struct reclaim_state reclaim_state = {
1684 .reclaimed_slab = 0,
1686 cpumask_t cpumask;
1688 cpumask = node_to_cpumask(pgdat->node_id);
1689 if (!cpus_empty(cpumask))
1690 set_cpus_allowed(tsk, cpumask);
1691 current->reclaim_state = &reclaim_state;
1694 * Tell the memory management that we're a "memory allocator",
1695 * and that if we need more memory we should get access to it
1696 * regardless (see "__alloc_pages()"). "kswapd" should
1697 * never get caught in the normal page freeing logic.
1699 * (Kswapd normally doesn't need memory anyway, but sometimes
1700 * you need a small amount of memory in order to be able to
1701 * page out something else, and this flag essentially protects
1702 * us from recursively trying to free more memory as we're
1703 * trying to free the first piece of memory in the first place).
1705 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
1706 set_freezable();
1708 order = 0;
1709 for ( ; ; ) {
1710 unsigned long new_order;
1712 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
1713 new_order = pgdat->kswapd_max_order;
1714 pgdat->kswapd_max_order = 0;
1715 if (order < new_order) {
1717 * Don't sleep if someone wants a larger 'order'
1718 * allocation
1720 order = new_order;
1721 } else {
1722 if (!freezing(current))
1723 schedule();
1725 order = pgdat->kswapd_max_order;
1727 finish_wait(&pgdat->kswapd_wait, &wait);
1729 if (!try_to_freeze()) {
1730 /* We can speed up thawing tasks if we don't call
1731 * balance_pgdat after returning from the refrigerator
1733 balance_pgdat(pgdat, order);
1736 return 0;
1740 * A zone is low on free memory, so wake its kswapd task to service it.
1742 void wakeup_kswapd(struct zone *zone, int order)
1744 pg_data_t *pgdat;
1746 if (!populated_zone(zone))
1747 return;
1749 pgdat = zone->zone_pgdat;
1750 if (zone_watermark_ok(zone, order, zone->pages_low, 0, 0))
1751 return;
1752 if (pgdat->kswapd_max_order < order)
1753 pgdat->kswapd_max_order = order;
1754 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1755 return;
1756 if (!waitqueue_active(&pgdat->kswapd_wait))
1757 return;
1758 wake_up_interruptible(&pgdat->kswapd_wait);
1761 #ifdef CONFIG_PM
1763 * Helper function for shrink_all_memory(). Tries to reclaim 'nr_pages' pages
1764 * from LRU lists system-wide, for given pass and priority, and returns the
1765 * number of reclaimed pages
1767 * For pass > 3 we also try to shrink the LRU lists that contain a few pages
1769 static unsigned long shrink_all_zones(unsigned long nr_pages, int prio,
1770 int pass, struct scan_control *sc)
1772 struct zone *zone;
1773 unsigned long nr_to_scan, ret = 0;
1775 for_each_zone(zone) {
1777 if (!populated_zone(zone))
1778 continue;
1780 if (zone_is_all_unreclaimable(zone) && prio != DEF_PRIORITY)
1781 continue;
1783 /* For pass = 0 we don't shrink the active list */
1784 if (pass > 0) {
1785 zone->nr_scan_active +=
1786 (zone_page_state(zone, NR_ACTIVE) >> prio) + 1;
1787 if (zone->nr_scan_active >= nr_pages || pass > 3) {
1788 zone->nr_scan_active = 0;
1789 nr_to_scan = min(nr_pages,
1790 zone_page_state(zone, NR_ACTIVE));
1791 shrink_active_list(nr_to_scan, zone, sc, prio);
1795 zone->nr_scan_inactive +=
1796 (zone_page_state(zone, NR_INACTIVE) >> prio) + 1;
1797 if (zone->nr_scan_inactive >= nr_pages || pass > 3) {
1798 zone->nr_scan_inactive = 0;
1799 nr_to_scan = min(nr_pages,
1800 zone_page_state(zone, NR_INACTIVE));
1801 ret += shrink_inactive_list(nr_to_scan, zone, sc);
1802 if (ret >= nr_pages)
1803 return ret;
1807 return ret;
1810 static unsigned long count_lru_pages(void)
1812 return global_page_state(NR_ACTIVE) + global_page_state(NR_INACTIVE);
1816 * Try to free `nr_pages' of memory, system-wide, and return the number of
1817 * freed pages.
1819 * Rather than trying to age LRUs the aim is to preserve the overall
1820 * LRU order by reclaiming preferentially
1821 * inactive > active > active referenced > active mapped
1823 unsigned long shrink_all_memory(unsigned long nr_pages)
1825 unsigned long lru_pages, nr_slab;
1826 unsigned long ret = 0;
1827 int pass;
1828 struct reclaim_state reclaim_state;
1829 struct scan_control sc = {
1830 .gfp_mask = GFP_KERNEL,
1831 .may_swap = 0,
1832 .swap_cluster_max = nr_pages,
1833 .may_writepage = 1,
1834 .swappiness = vm_swappiness,
1835 .isolate_pages = isolate_pages_global,
1838 current->reclaim_state = &reclaim_state;
1840 lru_pages = count_lru_pages();
1841 nr_slab = global_page_state(NR_SLAB_RECLAIMABLE);
1842 /* If slab caches are huge, it's better to hit them first */
1843 while (nr_slab >= lru_pages) {
1844 reclaim_state.reclaimed_slab = 0;
1845 shrink_slab(nr_pages, sc.gfp_mask, lru_pages);
1846 if (!reclaim_state.reclaimed_slab)
1847 break;
1849 ret += reclaim_state.reclaimed_slab;
1850 if (ret >= nr_pages)
1851 goto out;
1853 nr_slab -= reclaim_state.reclaimed_slab;
1857 * We try to shrink LRUs in 5 passes:
1858 * 0 = Reclaim from inactive_list only
1859 * 1 = Reclaim from active list but don't reclaim mapped
1860 * 2 = 2nd pass of type 1
1861 * 3 = Reclaim mapped (normal reclaim)
1862 * 4 = 2nd pass of type 3
1864 for (pass = 0; pass < 5; pass++) {
1865 int prio;
1867 /* Force reclaiming mapped pages in the passes #3 and #4 */
1868 if (pass > 2) {
1869 sc.may_swap = 1;
1870 sc.swappiness = 100;
1873 for (prio = DEF_PRIORITY; prio >= 0; prio--) {
1874 unsigned long nr_to_scan = nr_pages - ret;
1876 sc.nr_scanned = 0;
1877 ret += shrink_all_zones(nr_to_scan, prio, pass, &sc);
1878 if (ret >= nr_pages)
1879 goto out;
1881 reclaim_state.reclaimed_slab = 0;
1882 shrink_slab(sc.nr_scanned, sc.gfp_mask,
1883 count_lru_pages());
1884 ret += reclaim_state.reclaimed_slab;
1885 if (ret >= nr_pages)
1886 goto out;
1888 if (sc.nr_scanned && prio < DEF_PRIORITY - 2)
1889 congestion_wait(WRITE, HZ / 10);
1894 * If ret = 0, we could not shrink LRUs, but there may be something
1895 * in slab caches
1897 if (!ret) {
1898 do {
1899 reclaim_state.reclaimed_slab = 0;
1900 shrink_slab(nr_pages, sc.gfp_mask, count_lru_pages());
1901 ret += reclaim_state.reclaimed_slab;
1902 } while (ret < nr_pages && reclaim_state.reclaimed_slab > 0);
1905 out:
1906 current->reclaim_state = NULL;
1908 return ret;
1910 #endif
1912 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1913 not required for correctness. So if the last cpu in a node goes
1914 away, we get changed to run anywhere: as the first one comes back,
1915 restore their cpu bindings. */
1916 static int __devinit cpu_callback(struct notifier_block *nfb,
1917 unsigned long action, void *hcpu)
1919 pg_data_t *pgdat;
1920 cpumask_t mask;
1921 int nid;
1923 if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
1924 for_each_node_state(nid, N_HIGH_MEMORY) {
1925 pgdat = NODE_DATA(nid);
1926 mask = node_to_cpumask(pgdat->node_id);
1927 if (any_online_cpu(mask) != NR_CPUS)
1928 /* One of our CPUs online: restore mask */
1929 set_cpus_allowed(pgdat->kswapd, mask);
1932 return NOTIFY_OK;
1936 * This kswapd start function will be called by init and node-hot-add.
1937 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
1939 int kswapd_run(int nid)
1941 pg_data_t *pgdat = NODE_DATA(nid);
1942 int ret = 0;
1944 if (pgdat->kswapd)
1945 return 0;
1947 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
1948 if (IS_ERR(pgdat->kswapd)) {
1949 /* failure at boot is fatal */
1950 BUG_ON(system_state == SYSTEM_BOOTING);
1951 printk("Failed to start kswapd on node %d\n",nid);
1952 ret = -1;
1954 return ret;
1957 static int __init kswapd_init(void)
1959 int nid;
1961 swap_setup();
1962 for_each_node_state(nid, N_HIGH_MEMORY)
1963 kswapd_run(nid);
1964 hotcpu_notifier(cpu_callback, 0);
1965 return 0;
1968 module_init(kswapd_init)
1970 #ifdef CONFIG_NUMA
1972 * Zone reclaim mode
1974 * If non-zero call zone_reclaim when the number of free pages falls below
1975 * the watermarks.
1977 int zone_reclaim_mode __read_mostly;
1979 #define RECLAIM_OFF 0
1980 #define RECLAIM_ZONE (1<<0) /* Run shrink_cache on the zone */
1981 #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
1982 #define RECLAIM_SWAP (1<<2) /* Swap pages out during reclaim */
1985 * Priority for ZONE_RECLAIM. This determines the fraction of pages
1986 * of a node considered for each zone_reclaim. 4 scans 1/16th of
1987 * a zone.
1989 #define ZONE_RECLAIM_PRIORITY 4
1992 * Percentage of pages in a zone that must be unmapped for zone_reclaim to
1993 * occur.
1995 int sysctl_min_unmapped_ratio = 1;
1998 * If the number of slab pages in a zone grows beyond this percentage then
1999 * slab reclaim needs to occur.
2001 int sysctl_min_slab_ratio = 5;
2004 * Try to free up some pages from this zone through reclaim.
2006 static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
2008 /* Minimum pages needed in order to stay on node */
2009 const unsigned long nr_pages = 1 << order;
2010 struct task_struct *p = current;
2011 struct reclaim_state reclaim_state;
2012 int priority;
2013 unsigned long nr_reclaimed = 0;
2014 struct scan_control sc = {
2015 .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
2016 .may_swap = !!(zone_reclaim_mode & RECLAIM_SWAP),
2017 .swap_cluster_max = max_t(unsigned long, nr_pages,
2018 SWAP_CLUSTER_MAX),
2019 .gfp_mask = gfp_mask,
2020 .swappiness = vm_swappiness,
2021 .isolate_pages = isolate_pages_global,
2023 unsigned long slab_reclaimable;
2025 disable_swap_token();
2026 cond_resched();
2028 * We need to be able to allocate from the reserves for RECLAIM_SWAP
2029 * and we also need to be able to write out pages for RECLAIM_WRITE
2030 * and RECLAIM_SWAP.
2032 p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
2033 reclaim_state.reclaimed_slab = 0;
2034 p->reclaim_state = &reclaim_state;
2036 if (zone_page_state(zone, NR_FILE_PAGES) -
2037 zone_page_state(zone, NR_FILE_MAPPED) >
2038 zone->min_unmapped_pages) {
2040 * Free memory by calling shrink zone with increasing
2041 * priorities until we have enough memory freed.
2043 priority = ZONE_RECLAIM_PRIORITY;
2044 do {
2045 note_zone_scanning_priority(zone, priority);
2046 nr_reclaimed += shrink_zone(priority, zone, &sc);
2047 priority--;
2048 } while (priority >= 0 && nr_reclaimed < nr_pages);
2051 slab_reclaimable = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
2052 if (slab_reclaimable > zone->min_slab_pages) {
2054 * shrink_slab() does not currently allow us to determine how
2055 * many pages were freed in this zone. So we take the current
2056 * number of slab pages and shake the slab until it is reduced
2057 * by the same nr_pages that we used for reclaiming unmapped
2058 * pages.
2060 * Note that shrink_slab will free memory on all zones and may
2061 * take a long time.
2063 while (shrink_slab(sc.nr_scanned, gfp_mask, order) &&
2064 zone_page_state(zone, NR_SLAB_RECLAIMABLE) >
2065 slab_reclaimable - nr_pages)
2069 * Update nr_reclaimed by the number of slab pages we
2070 * reclaimed from this zone.
2072 nr_reclaimed += slab_reclaimable -
2073 zone_page_state(zone, NR_SLAB_RECLAIMABLE);
2076 p->reclaim_state = NULL;
2077 current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
2078 return nr_reclaimed >= nr_pages;
2081 int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
2083 int node_id;
2084 int ret;
2087 * Zone reclaim reclaims unmapped file backed pages and
2088 * slab pages if we are over the defined limits.
2090 * A small portion of unmapped file backed pages is needed for
2091 * file I/O otherwise pages read by file I/O will be immediately
2092 * thrown out if the zone is overallocated. So we do not reclaim
2093 * if less than a specified percentage of the zone is used by
2094 * unmapped file backed pages.
2096 if (zone_page_state(zone, NR_FILE_PAGES) -
2097 zone_page_state(zone, NR_FILE_MAPPED) <= zone->min_unmapped_pages
2098 && zone_page_state(zone, NR_SLAB_RECLAIMABLE)
2099 <= zone->min_slab_pages)
2100 return 0;
2102 if (zone_is_all_unreclaimable(zone))
2103 return 0;
2106 * Do not scan if the allocation should not be delayed.
2108 if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
2109 return 0;
2112 * Only run zone reclaim on the local zone or on zones that do not
2113 * have associated processors. This will favor the local processor
2114 * over remote processors and spread off node memory allocations
2115 * as wide as possible.
2117 node_id = zone_to_nid(zone);
2118 if (node_state(node_id, N_CPU) && node_id != numa_node_id())
2119 return 0;
2121 if (zone_test_and_set_flag(zone, ZONE_RECLAIM_LOCKED))
2122 return 0;
2123 ret = __zone_reclaim(zone, gfp_mask, order);
2124 zone_clear_flag(zone, ZONE_RECLAIM_LOCKED);
2126 return ret;
2128 #endif