hugetlb: correct page count for surplus huge pages
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / mm / vmscan.c
blob45711585684ec74c01f7b93ae28a8d8b4f62bfb9
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 #ifdef CONFIG_CGROUP_MEM_RES_CTLR
130 #define scan_global_lru(sc) (!(sc)->mem_cgroup)
131 #else
132 #define scan_global_lru(sc) (1)
133 #endif
136 * Add a shrinker callback to be called from the vm
138 void register_shrinker(struct shrinker *shrinker)
140 shrinker->nr = 0;
141 down_write(&shrinker_rwsem);
142 list_add_tail(&shrinker->list, &shrinker_list);
143 up_write(&shrinker_rwsem);
145 EXPORT_SYMBOL(register_shrinker);
148 * Remove one
150 void unregister_shrinker(struct shrinker *shrinker)
152 down_write(&shrinker_rwsem);
153 list_del(&shrinker->list);
154 up_write(&shrinker_rwsem);
156 EXPORT_SYMBOL(unregister_shrinker);
158 #define SHRINK_BATCH 128
160 * Call the shrink functions to age shrinkable caches
162 * Here we assume it costs one seek to replace a lru page and that it also
163 * takes a seek to recreate a cache object. With this in mind we age equal
164 * percentages of the lru and ageable caches. This should balance the seeks
165 * generated by these structures.
167 * If the vm encountered mapped pages on the LRU it increase the pressure on
168 * slab to avoid swapping.
170 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
172 * `lru_pages' represents the number of on-LRU pages in all the zones which
173 * are eligible for the caller's allocation attempt. It is used for balancing
174 * slab reclaim versus page reclaim.
176 * Returns the number of slab objects which we shrunk.
178 unsigned long shrink_slab(unsigned long scanned, gfp_t gfp_mask,
179 unsigned long lru_pages)
181 struct shrinker *shrinker;
182 unsigned long ret = 0;
184 if (scanned == 0)
185 scanned = SWAP_CLUSTER_MAX;
187 if (!down_read_trylock(&shrinker_rwsem))
188 return 1; /* Assume we'll be able to shrink next time */
190 list_for_each_entry(shrinker, &shrinker_list, list) {
191 unsigned long long delta;
192 unsigned long total_scan;
193 unsigned long max_pass = (*shrinker->shrink)(0, gfp_mask);
195 delta = (4 * scanned) / shrinker->seeks;
196 delta *= max_pass;
197 do_div(delta, lru_pages + 1);
198 shrinker->nr += delta;
199 if (shrinker->nr < 0) {
200 printk(KERN_ERR "%s: nr=%ld\n",
201 __FUNCTION__, shrinker->nr);
202 shrinker->nr = max_pass;
206 * Avoid risking looping forever due to too large nr value:
207 * never try to free more than twice the estimate number of
208 * freeable entries.
210 if (shrinker->nr > max_pass * 2)
211 shrinker->nr = max_pass * 2;
213 total_scan = shrinker->nr;
214 shrinker->nr = 0;
216 while (total_scan >= SHRINK_BATCH) {
217 long this_scan = SHRINK_BATCH;
218 int shrink_ret;
219 int nr_before;
221 nr_before = (*shrinker->shrink)(0, gfp_mask);
222 shrink_ret = (*shrinker->shrink)(this_scan, gfp_mask);
223 if (shrink_ret == -1)
224 break;
225 if (shrink_ret < nr_before)
226 ret += nr_before - shrink_ret;
227 count_vm_events(SLABS_SCANNED, this_scan);
228 total_scan -= this_scan;
230 cond_resched();
233 shrinker->nr += total_scan;
235 up_read(&shrinker_rwsem);
236 return ret;
239 /* Called without lock on whether page is mapped, so answer is unstable */
240 static inline int page_mapping_inuse(struct page *page)
242 struct address_space *mapping;
244 /* Page is in somebody's page tables. */
245 if (page_mapped(page))
246 return 1;
248 /* Be more reluctant to reclaim swapcache than pagecache */
249 if (PageSwapCache(page))
250 return 1;
252 mapping = page_mapping(page);
253 if (!mapping)
254 return 0;
256 /* File is mmap'd by somebody? */
257 return mapping_mapped(mapping);
260 static inline int is_page_cache_freeable(struct page *page)
262 return page_count(page) - !!PagePrivate(page) == 2;
265 static int may_write_to_queue(struct backing_dev_info *bdi)
267 if (current->flags & PF_SWAPWRITE)
268 return 1;
269 if (!bdi_write_congested(bdi))
270 return 1;
271 if (bdi == current->backing_dev_info)
272 return 1;
273 return 0;
277 * We detected a synchronous write error writing a page out. Probably
278 * -ENOSPC. We need to propagate that into the address_space for a subsequent
279 * fsync(), msync() or close().
281 * The tricky part is that after writepage we cannot touch the mapping: nothing
282 * prevents it from being freed up. But we have a ref on the page and once
283 * that page is locked, the mapping is pinned.
285 * We're allowed to run sleeping lock_page() here because we know the caller has
286 * __GFP_FS.
288 static void handle_write_error(struct address_space *mapping,
289 struct page *page, int error)
291 lock_page(page);
292 if (page_mapping(page) == mapping)
293 mapping_set_error(mapping, error);
294 unlock_page(page);
297 /* Request for sync pageout. */
298 enum pageout_io {
299 PAGEOUT_IO_ASYNC,
300 PAGEOUT_IO_SYNC,
303 /* possible outcome of pageout() */
304 typedef enum {
305 /* failed to write page out, page is locked */
306 PAGE_KEEP,
307 /* move page to the active list, page is locked */
308 PAGE_ACTIVATE,
309 /* page has been sent to the disk successfully, page is unlocked */
310 PAGE_SUCCESS,
311 /* page is clean and locked */
312 PAGE_CLEAN,
313 } pageout_t;
316 * pageout is called by shrink_page_list() for each dirty page.
317 * Calls ->writepage().
319 static pageout_t pageout(struct page *page, struct address_space *mapping,
320 enum pageout_io sync_writeback)
323 * If the page is dirty, only perform writeback if that write
324 * will be non-blocking. To prevent this allocation from being
325 * stalled by pagecache activity. But note that there may be
326 * stalls if we need to run get_block(). We could test
327 * PagePrivate for that.
329 * If this process is currently in generic_file_write() against
330 * this page's queue, we can perform writeback even if that
331 * will block.
333 * If the page is swapcache, write it back even if that would
334 * block, for some throttling. This happens by accident, because
335 * swap_backing_dev_info is bust: it doesn't reflect the
336 * congestion state of the swapdevs. Easy to fix, if needed.
337 * See swapfile.c:page_queue_congested().
339 if (!is_page_cache_freeable(page))
340 return PAGE_KEEP;
341 if (!mapping) {
343 * Some data journaling orphaned pages can have
344 * page->mapping == NULL while being dirty with clean buffers.
346 if (PagePrivate(page)) {
347 if (try_to_free_buffers(page)) {
348 ClearPageDirty(page);
349 printk("%s: orphaned page\n", __FUNCTION__);
350 return PAGE_CLEAN;
353 return PAGE_KEEP;
355 if (mapping->a_ops->writepage == NULL)
356 return PAGE_ACTIVATE;
357 if (!may_write_to_queue(mapping->backing_dev_info))
358 return PAGE_KEEP;
360 if (clear_page_dirty_for_io(page)) {
361 int res;
362 struct writeback_control wbc = {
363 .sync_mode = WB_SYNC_NONE,
364 .nr_to_write = SWAP_CLUSTER_MAX,
365 .range_start = 0,
366 .range_end = LLONG_MAX,
367 .nonblocking = 1,
368 .for_reclaim = 1,
371 SetPageReclaim(page);
372 res = mapping->a_ops->writepage(page, &wbc);
373 if (res < 0)
374 handle_write_error(mapping, page, res);
375 if (res == AOP_WRITEPAGE_ACTIVATE) {
376 ClearPageReclaim(page);
377 return PAGE_ACTIVATE;
381 * Wait on writeback if requested to. This happens when
382 * direct reclaiming a large contiguous area and the
383 * first attempt to free a range of pages fails.
385 if (PageWriteback(page) && sync_writeback == PAGEOUT_IO_SYNC)
386 wait_on_page_writeback(page);
388 if (!PageWriteback(page)) {
389 /* synchronous write or broken a_ops? */
390 ClearPageReclaim(page);
392 inc_zone_page_state(page, NR_VMSCAN_WRITE);
393 return PAGE_SUCCESS;
396 return PAGE_CLEAN;
400 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
401 * someone else has a ref on the page, abort and return 0. If it was
402 * successfully detached, return 1. Assumes the caller has a single ref on
403 * this page.
405 int remove_mapping(struct address_space *mapping, struct page *page)
407 BUG_ON(!PageLocked(page));
408 BUG_ON(mapping != page_mapping(page));
410 write_lock_irq(&mapping->tree_lock);
412 * The non racy check for a busy page.
414 * Must be careful with the order of the tests. When someone has
415 * a ref to the page, it may be possible that they dirty it then
416 * drop the reference. So if PageDirty is tested before page_count
417 * here, then the following race may occur:
419 * get_user_pages(&page);
420 * [user mapping goes away]
421 * write_to(page);
422 * !PageDirty(page) [good]
423 * SetPageDirty(page);
424 * put_page(page);
425 * !page_count(page) [good, discard it]
427 * [oops, our write_to data is lost]
429 * Reversing the order of the tests ensures such a situation cannot
430 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
431 * load is not satisfied before that of page->_count.
433 * Note that if SetPageDirty is always performed via set_page_dirty,
434 * and thus under tree_lock, then this ordering is not required.
436 if (unlikely(page_count(page) != 2))
437 goto cannot_free;
438 smp_rmb();
439 if (unlikely(PageDirty(page)))
440 goto cannot_free;
442 if (PageSwapCache(page)) {
443 swp_entry_t swap = { .val = page_private(page) };
444 __delete_from_swap_cache(page);
445 write_unlock_irq(&mapping->tree_lock);
446 swap_free(swap);
447 __put_page(page); /* The pagecache ref */
448 return 1;
451 __remove_from_page_cache(page);
452 write_unlock_irq(&mapping->tree_lock);
453 __put_page(page);
454 return 1;
456 cannot_free:
457 write_unlock_irq(&mapping->tree_lock);
458 return 0;
462 * shrink_page_list() returns the number of reclaimed pages
464 static unsigned long shrink_page_list(struct list_head *page_list,
465 struct scan_control *sc,
466 enum pageout_io sync_writeback)
468 LIST_HEAD(ret_pages);
469 struct pagevec freed_pvec;
470 int pgactivate = 0;
471 unsigned long nr_reclaimed = 0;
473 cond_resched();
475 pagevec_init(&freed_pvec, 1);
476 while (!list_empty(page_list)) {
477 struct address_space *mapping;
478 struct page *page;
479 int may_enter_fs;
480 int referenced;
482 cond_resched();
484 page = lru_to_page(page_list);
485 list_del(&page->lru);
487 if (TestSetPageLocked(page))
488 goto keep;
490 VM_BUG_ON(PageActive(page));
492 sc->nr_scanned++;
494 if (!sc->may_swap && page_mapped(page))
495 goto keep_locked;
497 /* Double the slab pressure for mapped and swapcache pages */
498 if (page_mapped(page) || PageSwapCache(page))
499 sc->nr_scanned++;
501 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
502 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
504 if (PageWriteback(page)) {
506 * Synchronous reclaim is performed in two passes,
507 * first an asynchronous pass over the list to
508 * start parallel writeback, and a second synchronous
509 * pass to wait for the IO to complete. Wait here
510 * for any page for which writeback has already
511 * started.
513 if (sync_writeback == PAGEOUT_IO_SYNC && may_enter_fs)
514 wait_on_page_writeback(page);
515 else {
516 sc->nr_io_pages++;
517 goto keep_locked;
521 referenced = page_referenced(page, 1, sc->mem_cgroup);
522 /* In active use or really unfreeable? Activate it. */
523 if (sc->order <= PAGE_ALLOC_COSTLY_ORDER &&
524 referenced && page_mapping_inuse(page))
525 goto activate_locked;
527 #ifdef CONFIG_SWAP
529 * Anonymous process memory has backing store?
530 * Try to allocate it some swap space here.
532 if (PageAnon(page) && !PageSwapCache(page))
533 if (!add_to_swap(page, GFP_ATOMIC))
534 goto activate_locked;
535 #endif /* CONFIG_SWAP */
537 mapping = page_mapping(page);
540 * The page is mapped into the page tables of one or more
541 * processes. Try to unmap it here.
543 if (page_mapped(page) && mapping) {
544 switch (try_to_unmap(page, 0)) {
545 case SWAP_FAIL:
546 goto activate_locked;
547 case SWAP_AGAIN:
548 goto keep_locked;
549 case SWAP_SUCCESS:
550 ; /* try to free the page below */
554 if (PageDirty(page)) {
555 if (sc->order <= PAGE_ALLOC_COSTLY_ORDER && referenced)
556 goto keep_locked;
557 if (!may_enter_fs) {
558 sc->nr_io_pages++;
559 goto keep_locked;
561 if (!sc->may_writepage)
562 goto keep_locked;
564 /* Page is dirty, try to write it out here */
565 switch (pageout(page, mapping, sync_writeback)) {
566 case PAGE_KEEP:
567 goto keep_locked;
568 case PAGE_ACTIVATE:
569 goto activate_locked;
570 case PAGE_SUCCESS:
571 if (PageWriteback(page) || PageDirty(page)) {
572 sc->nr_io_pages++;
573 goto keep;
576 * A synchronous write - probably a ramdisk. Go
577 * ahead and try to reclaim the page.
579 if (TestSetPageLocked(page))
580 goto keep;
581 if (PageDirty(page) || PageWriteback(page))
582 goto keep_locked;
583 mapping = page_mapping(page);
584 case PAGE_CLEAN:
585 ; /* try to free the page below */
590 * If the page has buffers, try to free the buffer mappings
591 * associated with this page. If we succeed we try to free
592 * the page as well.
594 * We do this even if the page is PageDirty().
595 * try_to_release_page() does not perform I/O, but it is
596 * possible for a page to have PageDirty set, but it is actually
597 * clean (all its buffers are clean). This happens if the
598 * buffers were written out directly, with submit_bh(). ext3
599 * will do this, as well as the blockdev mapping.
600 * try_to_release_page() will discover that cleanness and will
601 * drop the buffers and mark the page clean - it can be freed.
603 * Rarely, pages can have buffers and no ->mapping. These are
604 * the pages which were not successfully invalidated in
605 * truncate_complete_page(). We try to drop those buffers here
606 * and if that worked, and the page is no longer mapped into
607 * process address space (page_count == 1) it can be freed.
608 * Otherwise, leave the page on the LRU so it is swappable.
610 if (PagePrivate(page)) {
611 if (!try_to_release_page(page, sc->gfp_mask))
612 goto activate_locked;
613 if (!mapping && page_count(page) == 1)
614 goto free_it;
617 if (!mapping || !remove_mapping(mapping, page))
618 goto keep_locked;
620 free_it:
621 unlock_page(page);
622 nr_reclaimed++;
623 if (!pagevec_add(&freed_pvec, page))
624 __pagevec_release_nonlru(&freed_pvec);
625 continue;
627 activate_locked:
628 SetPageActive(page);
629 pgactivate++;
630 keep_locked:
631 unlock_page(page);
632 keep:
633 list_add(&page->lru, &ret_pages);
634 VM_BUG_ON(PageLRU(page));
636 list_splice(&ret_pages, page_list);
637 if (pagevec_count(&freed_pvec))
638 __pagevec_release_nonlru(&freed_pvec);
639 count_vm_events(PGACTIVATE, pgactivate);
640 return nr_reclaimed;
643 /* LRU Isolation modes. */
644 #define ISOLATE_INACTIVE 0 /* Isolate inactive pages. */
645 #define ISOLATE_ACTIVE 1 /* Isolate active pages. */
646 #define ISOLATE_BOTH 2 /* Isolate both active and inactive pages. */
649 * Attempt to remove the specified page from its LRU. Only take this page
650 * if it is of the appropriate PageActive status. Pages which are being
651 * freed elsewhere are also ignored.
653 * page: page to consider
654 * mode: one of the LRU isolation modes defined above
656 * returns 0 on success, -ve errno on failure.
658 int __isolate_lru_page(struct page *page, int mode)
660 int ret = -EINVAL;
662 /* Only take pages on the LRU. */
663 if (!PageLRU(page))
664 return ret;
667 * When checking the active state, we need to be sure we are
668 * dealing with comparible boolean values. Take the logical not
669 * of each.
671 if (mode != ISOLATE_BOTH && (!PageActive(page) != !mode))
672 return ret;
674 ret = -EBUSY;
675 if (likely(get_page_unless_zero(page))) {
677 * Be careful not to clear PageLRU until after we're
678 * sure the page is not being freed elsewhere -- the
679 * page release code relies on it.
681 ClearPageLRU(page);
682 ret = 0;
685 return ret;
689 * zone->lru_lock is heavily contended. Some of the functions that
690 * shrink the lists perform better by taking out a batch of pages
691 * and working on them outside the LRU lock.
693 * For pagecache intensive workloads, this function is the hottest
694 * spot in the kernel (apart from copy_*_user functions).
696 * Appropriate locks must be held before calling this function.
698 * @nr_to_scan: The number of pages to look through on the list.
699 * @src: The LRU list to pull pages off.
700 * @dst: The temp list to put pages on to.
701 * @scanned: The number of pages that were scanned.
702 * @order: The caller's attempted allocation order
703 * @mode: One of the LRU isolation modes
705 * returns how many pages were moved onto *@dst.
707 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
708 struct list_head *src, struct list_head *dst,
709 unsigned long *scanned, int order, int mode)
711 unsigned long nr_taken = 0;
712 unsigned long scan;
714 for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
715 struct page *page;
716 unsigned long pfn;
717 unsigned long end_pfn;
718 unsigned long page_pfn;
719 int zone_id;
721 page = lru_to_page(src);
722 prefetchw_prev_lru_page(page, src, flags);
724 VM_BUG_ON(!PageLRU(page));
726 switch (__isolate_lru_page(page, mode)) {
727 case 0:
728 list_move(&page->lru, dst);
729 nr_taken++;
730 break;
732 case -EBUSY:
733 /* else it is being freed elsewhere */
734 list_move(&page->lru, src);
735 continue;
737 default:
738 BUG();
741 if (!order)
742 continue;
745 * Attempt to take all pages in the order aligned region
746 * surrounding the tag page. Only take those pages of
747 * the same active state as that tag page. We may safely
748 * round the target page pfn down to the requested order
749 * as the mem_map is guarenteed valid out to MAX_ORDER,
750 * where that page is in a different zone we will detect
751 * it from its zone id and abort this block scan.
753 zone_id = page_zone_id(page);
754 page_pfn = page_to_pfn(page);
755 pfn = page_pfn & ~((1 << order) - 1);
756 end_pfn = pfn + (1 << order);
757 for (; pfn < end_pfn; pfn++) {
758 struct page *cursor_page;
760 /* The target page is in the block, ignore it. */
761 if (unlikely(pfn == page_pfn))
762 continue;
764 /* Avoid holes within the zone. */
765 if (unlikely(!pfn_valid_within(pfn)))
766 break;
768 cursor_page = pfn_to_page(pfn);
769 /* Check that we have not crossed a zone boundary. */
770 if (unlikely(page_zone_id(cursor_page) != zone_id))
771 continue;
772 switch (__isolate_lru_page(cursor_page, mode)) {
773 case 0:
774 list_move(&cursor_page->lru, dst);
775 nr_taken++;
776 scan++;
777 break;
779 case -EBUSY:
780 /* else it is being freed elsewhere */
781 list_move(&cursor_page->lru, src);
782 default:
783 break;
788 *scanned = scan;
789 return nr_taken;
792 static unsigned long isolate_pages_global(unsigned long nr,
793 struct list_head *dst,
794 unsigned long *scanned, int order,
795 int mode, struct zone *z,
796 struct mem_cgroup *mem_cont,
797 int active)
799 if (active)
800 return isolate_lru_pages(nr, &z->active_list, dst,
801 scanned, order, mode);
802 else
803 return isolate_lru_pages(nr, &z->inactive_list, dst,
804 scanned, order, mode);
808 * clear_active_flags() is a helper for shrink_active_list(), clearing
809 * any active bits from the pages in the list.
811 static unsigned long clear_active_flags(struct list_head *page_list)
813 int nr_active = 0;
814 struct page *page;
816 list_for_each_entry(page, page_list, lru)
817 if (PageActive(page)) {
818 ClearPageActive(page);
819 nr_active++;
822 return nr_active;
826 * shrink_inactive_list() is a helper for shrink_zone(). It returns the number
827 * of reclaimed pages
829 static unsigned long shrink_inactive_list(unsigned long max_scan,
830 struct zone *zone, struct scan_control *sc)
832 LIST_HEAD(page_list);
833 struct pagevec pvec;
834 unsigned long nr_scanned = 0;
835 unsigned long nr_reclaimed = 0;
837 pagevec_init(&pvec, 1);
839 lru_add_drain();
840 spin_lock_irq(&zone->lru_lock);
841 do {
842 struct page *page;
843 unsigned long nr_taken;
844 unsigned long nr_scan;
845 unsigned long nr_freed;
846 unsigned long nr_active;
848 nr_taken = sc->isolate_pages(sc->swap_cluster_max,
849 &page_list, &nr_scan, sc->order,
850 (sc->order > PAGE_ALLOC_COSTLY_ORDER)?
851 ISOLATE_BOTH : ISOLATE_INACTIVE,
852 zone, sc->mem_cgroup, 0);
853 nr_active = clear_active_flags(&page_list);
854 __count_vm_events(PGDEACTIVATE, nr_active);
856 __mod_zone_page_state(zone, NR_ACTIVE, -nr_active);
857 __mod_zone_page_state(zone, NR_INACTIVE,
858 -(nr_taken - nr_active));
859 if (scan_global_lru(sc))
860 zone->pages_scanned += nr_scan;
861 spin_unlock_irq(&zone->lru_lock);
863 nr_scanned += nr_scan;
864 nr_freed = shrink_page_list(&page_list, sc, PAGEOUT_IO_ASYNC);
867 * If we are direct reclaiming for contiguous pages and we do
868 * not reclaim everything in the list, try again and wait
869 * for IO to complete. This will stall high-order allocations
870 * but that should be acceptable to the caller
872 if (nr_freed < nr_taken && !current_is_kswapd() &&
873 sc->order > PAGE_ALLOC_COSTLY_ORDER) {
874 congestion_wait(WRITE, HZ/10);
877 * The attempt at page out may have made some
878 * of the pages active, mark them inactive again.
880 nr_active = clear_active_flags(&page_list);
881 count_vm_events(PGDEACTIVATE, nr_active);
883 nr_freed += shrink_page_list(&page_list, sc,
884 PAGEOUT_IO_SYNC);
887 nr_reclaimed += nr_freed;
888 local_irq_disable();
889 if (current_is_kswapd()) {
890 __count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scan);
891 __count_vm_events(KSWAPD_STEAL, nr_freed);
892 } else if (scan_global_lru(sc))
893 __count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scan);
895 __count_zone_vm_events(PGSTEAL, zone, nr_freed);
897 if (nr_taken == 0)
898 goto done;
900 spin_lock(&zone->lru_lock);
902 * Put back any unfreeable pages.
904 while (!list_empty(&page_list)) {
905 page = lru_to_page(&page_list);
906 VM_BUG_ON(PageLRU(page));
907 SetPageLRU(page);
908 list_del(&page->lru);
909 if (PageActive(page))
910 add_page_to_active_list(zone, page);
911 else
912 add_page_to_inactive_list(zone, page);
913 if (!pagevec_add(&pvec, page)) {
914 spin_unlock_irq(&zone->lru_lock);
915 __pagevec_release(&pvec);
916 spin_lock_irq(&zone->lru_lock);
919 } while (nr_scanned < max_scan);
920 spin_unlock(&zone->lru_lock);
921 done:
922 local_irq_enable();
923 pagevec_release(&pvec);
924 return nr_reclaimed;
928 * We are about to scan this zone at a certain priority level. If that priority
929 * level is smaller (ie: more urgent) than the previous priority, then note
930 * that priority level within the zone. This is done so that when the next
931 * process comes in to scan this zone, it will immediately start out at this
932 * priority level rather than having to build up its own scanning priority.
933 * Here, this priority affects only the reclaim-mapped threshold.
935 static inline void note_zone_scanning_priority(struct zone *zone, int priority)
937 if (priority < zone->prev_priority)
938 zone->prev_priority = priority;
941 static inline int zone_is_near_oom(struct zone *zone)
943 return zone->pages_scanned >= (zone_page_state(zone, NR_ACTIVE)
944 + zone_page_state(zone, NR_INACTIVE))*3;
948 * Determine we should try to reclaim mapped pages.
949 * This is called only when sc->mem_cgroup is NULL.
951 static int calc_reclaim_mapped(struct scan_control *sc, struct zone *zone,
952 int priority)
954 long mapped_ratio;
955 long distress;
956 long swap_tendency;
957 long imbalance;
958 int reclaim_mapped = 0;
959 int prev_priority;
961 if (scan_global_lru(sc) && zone_is_near_oom(zone))
962 return 1;
964 * `distress' is a measure of how much trouble we're having
965 * reclaiming pages. 0 -> no problems. 100 -> great trouble.
967 if (scan_global_lru(sc))
968 prev_priority = zone->prev_priority;
969 else
970 prev_priority = mem_cgroup_get_reclaim_priority(sc->mem_cgroup);
972 distress = 100 >> min(prev_priority, priority);
975 * The point of this algorithm is to decide when to start
976 * reclaiming mapped memory instead of just pagecache. Work out
977 * how much memory
978 * is mapped.
980 if (scan_global_lru(sc))
981 mapped_ratio = ((global_page_state(NR_FILE_MAPPED) +
982 global_page_state(NR_ANON_PAGES)) * 100) /
983 vm_total_pages;
984 else
985 mapped_ratio = mem_cgroup_calc_mapped_ratio(sc->mem_cgroup);
988 * Now decide how much we really want to unmap some pages. The
989 * mapped ratio is downgraded - just because there's a lot of
990 * mapped memory doesn't necessarily mean that page reclaim
991 * isn't succeeding.
993 * The distress ratio is important - we don't want to start
994 * going oom.
996 * A 100% value of vm_swappiness overrides this algorithm
997 * altogether.
999 swap_tendency = mapped_ratio / 2 + distress + sc->swappiness;
1002 * If there's huge imbalance between active and inactive
1003 * (think active 100 times larger than inactive) we should
1004 * become more permissive, or the system will take too much
1005 * cpu before it start swapping during memory pressure.
1006 * Distress is about avoiding early-oom, this is about
1007 * making swappiness graceful despite setting it to low
1008 * values.
1010 * Avoid div by zero with nr_inactive+1, and max resulting
1011 * value is vm_total_pages.
1013 if (scan_global_lru(sc)) {
1014 imbalance = zone_page_state(zone, NR_ACTIVE);
1015 imbalance /= zone_page_state(zone, NR_INACTIVE) + 1;
1016 } else
1017 imbalance = mem_cgroup_reclaim_imbalance(sc->mem_cgroup);
1020 * Reduce the effect of imbalance if swappiness is low,
1021 * this means for a swappiness very low, the imbalance
1022 * must be much higher than 100 for this logic to make
1023 * the difference.
1025 * Max temporary value is vm_total_pages*100.
1027 imbalance *= (vm_swappiness + 1);
1028 imbalance /= 100;
1031 * If not much of the ram is mapped, makes the imbalance
1032 * less relevant, it's high priority we refill the inactive
1033 * list with mapped pages only in presence of high ratio of
1034 * mapped pages.
1036 * Max temporary value is vm_total_pages*100.
1038 imbalance *= mapped_ratio;
1039 imbalance /= 100;
1041 /* apply imbalance feedback to swap_tendency */
1042 swap_tendency += imbalance;
1045 * Now use this metric to decide whether to start moving mapped
1046 * memory onto the inactive list.
1048 if (swap_tendency >= 100)
1049 reclaim_mapped = 1;
1051 return reclaim_mapped;
1055 * This moves pages from the active list to the inactive list.
1057 * We move them the other way if the page is referenced by one or more
1058 * processes, from rmap.
1060 * If the pages are mostly unmapped, the processing is fast and it is
1061 * appropriate to hold zone->lru_lock across the whole operation. But if
1062 * the pages are mapped, the processing is slow (page_referenced()) so we
1063 * should drop zone->lru_lock around each page. It's impossible to balance
1064 * this, so instead we remove the pages from the LRU while processing them.
1065 * It is safe to rely on PG_active against the non-LRU pages in here because
1066 * nobody will play with that bit on a non-LRU page.
1068 * The downside is that we have to touch page->_count against each page.
1069 * But we had to alter page->flags anyway.
1073 static void shrink_active_list(unsigned long nr_pages, struct zone *zone,
1074 struct scan_control *sc, int priority)
1076 unsigned long pgmoved;
1077 int pgdeactivate = 0;
1078 unsigned long pgscanned;
1079 LIST_HEAD(l_hold); /* The pages which were snipped off */
1080 LIST_HEAD(l_inactive); /* Pages to go onto the inactive_list */
1081 LIST_HEAD(l_active); /* Pages to go onto the active_list */
1082 struct page *page;
1083 struct pagevec pvec;
1084 int reclaim_mapped = 0;
1086 if (sc->may_swap)
1087 reclaim_mapped = calc_reclaim_mapped(sc, zone, priority);
1089 lru_add_drain();
1090 spin_lock_irq(&zone->lru_lock);
1091 pgmoved = sc->isolate_pages(nr_pages, &l_hold, &pgscanned, sc->order,
1092 ISOLATE_ACTIVE, zone,
1093 sc->mem_cgroup, 1);
1095 * zone->pages_scanned is used for detect zone's oom
1096 * mem_cgroup remembers nr_scan by itself.
1098 if (scan_global_lru(sc))
1099 zone->pages_scanned += pgscanned;
1101 __mod_zone_page_state(zone, NR_ACTIVE, -pgmoved);
1102 spin_unlock_irq(&zone->lru_lock);
1104 while (!list_empty(&l_hold)) {
1105 cond_resched();
1106 page = lru_to_page(&l_hold);
1107 list_del(&page->lru);
1108 if (page_mapped(page)) {
1109 if (!reclaim_mapped ||
1110 (total_swap_pages == 0 && PageAnon(page)) ||
1111 page_referenced(page, 0, sc->mem_cgroup)) {
1112 list_add(&page->lru, &l_active);
1113 continue;
1116 list_add(&page->lru, &l_inactive);
1119 pagevec_init(&pvec, 1);
1120 pgmoved = 0;
1121 spin_lock_irq(&zone->lru_lock);
1122 while (!list_empty(&l_inactive)) {
1123 page = lru_to_page(&l_inactive);
1124 prefetchw_prev_lru_page(page, &l_inactive, flags);
1125 VM_BUG_ON(PageLRU(page));
1126 SetPageLRU(page);
1127 VM_BUG_ON(!PageActive(page));
1128 ClearPageActive(page);
1130 list_move(&page->lru, &zone->inactive_list);
1131 mem_cgroup_move_lists(page, false);
1132 pgmoved++;
1133 if (!pagevec_add(&pvec, page)) {
1134 __mod_zone_page_state(zone, NR_INACTIVE, pgmoved);
1135 spin_unlock_irq(&zone->lru_lock);
1136 pgdeactivate += pgmoved;
1137 pgmoved = 0;
1138 if (buffer_heads_over_limit)
1139 pagevec_strip(&pvec);
1140 __pagevec_release(&pvec);
1141 spin_lock_irq(&zone->lru_lock);
1144 __mod_zone_page_state(zone, NR_INACTIVE, pgmoved);
1145 pgdeactivate += pgmoved;
1146 if (buffer_heads_over_limit) {
1147 spin_unlock_irq(&zone->lru_lock);
1148 pagevec_strip(&pvec);
1149 spin_lock_irq(&zone->lru_lock);
1152 pgmoved = 0;
1153 while (!list_empty(&l_active)) {
1154 page = lru_to_page(&l_active);
1155 prefetchw_prev_lru_page(page, &l_active, flags);
1156 VM_BUG_ON(PageLRU(page));
1157 SetPageLRU(page);
1158 VM_BUG_ON(!PageActive(page));
1160 list_move(&page->lru, &zone->active_list);
1161 mem_cgroup_move_lists(page, true);
1162 pgmoved++;
1163 if (!pagevec_add(&pvec, page)) {
1164 __mod_zone_page_state(zone, NR_ACTIVE, pgmoved);
1165 pgmoved = 0;
1166 spin_unlock_irq(&zone->lru_lock);
1167 __pagevec_release(&pvec);
1168 spin_lock_irq(&zone->lru_lock);
1171 __mod_zone_page_state(zone, NR_ACTIVE, pgmoved);
1173 __count_zone_vm_events(PGREFILL, zone, pgscanned);
1174 __count_vm_events(PGDEACTIVATE, pgdeactivate);
1175 spin_unlock_irq(&zone->lru_lock);
1177 pagevec_release(&pvec);
1181 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
1183 static unsigned long shrink_zone(int priority, struct zone *zone,
1184 struct scan_control *sc)
1186 unsigned long nr_active;
1187 unsigned long nr_inactive;
1188 unsigned long nr_to_scan;
1189 unsigned long nr_reclaimed = 0;
1191 if (scan_global_lru(sc)) {
1193 * Add one to nr_to_scan just to make sure that the kernel
1194 * will slowly sift through the active list.
1196 zone->nr_scan_active +=
1197 (zone_page_state(zone, NR_ACTIVE) >> priority) + 1;
1198 nr_active = zone->nr_scan_active;
1199 zone->nr_scan_inactive +=
1200 (zone_page_state(zone, NR_INACTIVE) >> priority) + 1;
1201 nr_inactive = zone->nr_scan_inactive;
1202 if (nr_inactive >= sc->swap_cluster_max)
1203 zone->nr_scan_inactive = 0;
1204 else
1205 nr_inactive = 0;
1207 if (nr_active >= sc->swap_cluster_max)
1208 zone->nr_scan_active = 0;
1209 else
1210 nr_active = 0;
1211 } else {
1213 * This reclaim occurs not because zone memory shortage but
1214 * because memory controller hits its limit.
1215 * Then, don't modify zone reclaim related data.
1217 nr_active = mem_cgroup_calc_reclaim_active(sc->mem_cgroup,
1218 zone, priority);
1220 nr_inactive = mem_cgroup_calc_reclaim_inactive(sc->mem_cgroup,
1221 zone, priority);
1225 while (nr_active || nr_inactive) {
1226 if (nr_active) {
1227 nr_to_scan = min(nr_active,
1228 (unsigned long)sc->swap_cluster_max);
1229 nr_active -= nr_to_scan;
1230 shrink_active_list(nr_to_scan, zone, sc, priority);
1233 if (nr_inactive) {
1234 nr_to_scan = min(nr_inactive,
1235 (unsigned long)sc->swap_cluster_max);
1236 nr_inactive -= nr_to_scan;
1237 nr_reclaimed += shrink_inactive_list(nr_to_scan, zone,
1238 sc);
1242 throttle_vm_writeout(sc->gfp_mask);
1243 return nr_reclaimed;
1247 * This is the direct reclaim path, for page-allocating processes. We only
1248 * try to reclaim pages from zones which will satisfy the caller's allocation
1249 * request.
1251 * We reclaim from a zone even if that zone is over pages_high. Because:
1252 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
1253 * allocation or
1254 * b) The zones may be over pages_high but they must go *over* pages_high to
1255 * satisfy the `incremental min' zone defense algorithm.
1257 * Returns the number of reclaimed pages.
1259 * If a zone is deemed to be full of pinned pages then just give it a light
1260 * scan then give up on it.
1262 static unsigned long shrink_zones(int priority, struct zone **zones,
1263 struct scan_control *sc)
1265 unsigned long nr_reclaimed = 0;
1266 int i;
1269 sc->all_unreclaimable = 1;
1270 for (i = 0; zones[i] != NULL; i++) {
1271 struct zone *zone = zones[i];
1273 if (!populated_zone(zone))
1274 continue;
1276 * Take care memory controller reclaiming has small influence
1277 * to global LRU.
1279 if (scan_global_lru(sc)) {
1280 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1281 continue;
1282 note_zone_scanning_priority(zone, priority);
1284 if (zone_is_all_unreclaimable(zone) &&
1285 priority != DEF_PRIORITY)
1286 continue; /* Let kswapd poll it */
1287 sc->all_unreclaimable = 0;
1288 } else {
1290 * Ignore cpuset limitation here. We just want to reduce
1291 * # of used pages by us regardless of memory shortage.
1293 sc->all_unreclaimable = 0;
1294 mem_cgroup_note_reclaim_priority(sc->mem_cgroup,
1295 priority);
1298 nr_reclaimed += shrink_zone(priority, zone, sc);
1301 return nr_reclaimed;
1305 * This is the main entry point to direct page reclaim.
1307 * If a full scan of the inactive list fails to free enough memory then we
1308 * are "out of memory" and something needs to be killed.
1310 * If the caller is !__GFP_FS then the probability of a failure is reasonably
1311 * high - the zone may be full of dirty or under-writeback pages, which this
1312 * caller can't do much about. We kick pdflush and take explicit naps in the
1313 * hope that some of these pages can be written. But if the allocating task
1314 * holds filesystem locks which prevent writeout this might not work, and the
1315 * allocation attempt will fail.
1317 static unsigned long do_try_to_free_pages(struct zone **zones, gfp_t gfp_mask,
1318 struct scan_control *sc)
1320 int priority;
1321 int ret = 0;
1322 unsigned long total_scanned = 0;
1323 unsigned long nr_reclaimed = 0;
1324 struct reclaim_state *reclaim_state = current->reclaim_state;
1325 unsigned long lru_pages = 0;
1326 int i;
1328 if (scan_global_lru(sc))
1329 count_vm_event(ALLOCSTALL);
1331 * mem_cgroup will not do shrink_slab.
1333 if (scan_global_lru(sc)) {
1334 for (i = 0; zones[i] != NULL; i++) {
1335 struct zone *zone = zones[i];
1337 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1338 continue;
1340 lru_pages += zone_page_state(zone, NR_ACTIVE)
1341 + zone_page_state(zone, NR_INACTIVE);
1345 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1346 sc->nr_scanned = 0;
1347 sc->nr_io_pages = 0;
1348 if (!priority)
1349 disable_swap_token();
1350 nr_reclaimed += shrink_zones(priority, zones, sc);
1352 * Don't shrink slabs when reclaiming memory from
1353 * over limit cgroups
1355 if (scan_global_lru(sc)) {
1356 shrink_slab(sc->nr_scanned, gfp_mask, lru_pages);
1357 if (reclaim_state) {
1358 nr_reclaimed += reclaim_state->reclaimed_slab;
1359 reclaim_state->reclaimed_slab = 0;
1362 total_scanned += sc->nr_scanned;
1363 if (nr_reclaimed >= sc->swap_cluster_max) {
1364 ret = 1;
1365 goto out;
1369 * Try to write back as many pages as we just scanned. This
1370 * tends to cause slow streaming writers to write data to the
1371 * disk smoothly, at the dirtying rate, which is nice. But
1372 * that's undesirable in laptop mode, where we *want* lumpy
1373 * writeout. So in laptop mode, write out the whole world.
1375 if (total_scanned > sc->swap_cluster_max +
1376 sc->swap_cluster_max / 2) {
1377 wakeup_pdflush(laptop_mode ? 0 : total_scanned);
1378 sc->may_writepage = 1;
1381 /* Take a nap, wait for some writeback to complete */
1382 if (sc->nr_scanned && priority < DEF_PRIORITY - 2 &&
1383 sc->nr_io_pages > sc->swap_cluster_max)
1384 congestion_wait(WRITE, HZ/10);
1386 /* top priority shrink_caches still had more to do? don't OOM, then */
1387 if (!sc->all_unreclaimable && scan_global_lru(sc))
1388 ret = 1;
1389 out:
1391 * Now that we've scanned all the zones at this priority level, note
1392 * that level within the zone so that the next thread which performs
1393 * scanning of this zone will immediately start out at this priority
1394 * level. This affects only the decision whether or not to bring
1395 * mapped pages onto the inactive list.
1397 if (priority < 0)
1398 priority = 0;
1400 if (scan_global_lru(sc)) {
1401 for (i = 0; zones[i] != NULL; i++) {
1402 struct zone *zone = zones[i];
1404 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1405 continue;
1407 zone->prev_priority = priority;
1409 } else
1410 mem_cgroup_record_reclaim_priority(sc->mem_cgroup, priority);
1412 return ret;
1415 unsigned long try_to_free_pages(struct zone **zones, int order, gfp_t gfp_mask)
1417 struct scan_control sc = {
1418 .gfp_mask = gfp_mask,
1419 .may_writepage = !laptop_mode,
1420 .swap_cluster_max = SWAP_CLUSTER_MAX,
1421 .may_swap = 1,
1422 .swappiness = vm_swappiness,
1423 .order = order,
1424 .mem_cgroup = NULL,
1425 .isolate_pages = isolate_pages_global,
1428 return do_try_to_free_pages(zones, gfp_mask, &sc);
1431 #ifdef CONFIG_CGROUP_MEM_RES_CTLR
1433 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *mem_cont,
1434 gfp_t gfp_mask)
1436 struct scan_control sc = {
1437 .gfp_mask = gfp_mask,
1438 .may_writepage = !laptop_mode,
1439 .may_swap = 1,
1440 .swap_cluster_max = SWAP_CLUSTER_MAX,
1441 .swappiness = vm_swappiness,
1442 .order = 0,
1443 .mem_cgroup = mem_cont,
1444 .isolate_pages = mem_cgroup_isolate_pages,
1446 struct zone **zones;
1447 int target_zone = gfp_zone(GFP_HIGHUSER_MOVABLE);
1449 zones = NODE_DATA(numa_node_id())->node_zonelists[target_zone].zones;
1450 if (do_try_to_free_pages(zones, sc.gfp_mask, &sc))
1451 return 1;
1452 return 0;
1454 #endif
1457 * For kswapd, balance_pgdat() will work across all this node's zones until
1458 * they are all at pages_high.
1460 * Returns the number of pages which were actually freed.
1462 * There is special handling here for zones which are full of pinned pages.
1463 * This can happen if the pages are all mlocked, or if they are all used by
1464 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
1465 * What we do is to detect the case where all pages in the zone have been
1466 * scanned twice and there has been zero successful reclaim. Mark the zone as
1467 * dead and from now on, only perform a short scan. Basically we're polling
1468 * the zone for when the problem goes away.
1470 * kswapd scans the zones in the highmem->normal->dma direction. It skips
1471 * zones which have free_pages > pages_high, but once a zone is found to have
1472 * free_pages <= pages_high, we scan that zone and the lower zones regardless
1473 * of the number of free pages in the lower zones. This interoperates with
1474 * the page allocator fallback scheme to ensure that aging of pages is balanced
1475 * across the zones.
1477 static unsigned long balance_pgdat(pg_data_t *pgdat, int order)
1479 int all_zones_ok;
1480 int priority;
1481 int i;
1482 unsigned long total_scanned;
1483 unsigned long nr_reclaimed;
1484 struct reclaim_state *reclaim_state = current->reclaim_state;
1485 struct scan_control sc = {
1486 .gfp_mask = GFP_KERNEL,
1487 .may_swap = 1,
1488 .swap_cluster_max = SWAP_CLUSTER_MAX,
1489 .swappiness = vm_swappiness,
1490 .order = order,
1491 .mem_cgroup = NULL,
1492 .isolate_pages = isolate_pages_global,
1495 * temp_priority is used to remember the scanning priority at which
1496 * this zone was successfully refilled to free_pages == pages_high.
1498 int temp_priority[MAX_NR_ZONES];
1500 loop_again:
1501 total_scanned = 0;
1502 nr_reclaimed = 0;
1503 sc.may_writepage = !laptop_mode;
1504 count_vm_event(PAGEOUTRUN);
1506 for (i = 0; i < pgdat->nr_zones; i++)
1507 temp_priority[i] = DEF_PRIORITY;
1509 for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1510 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
1511 unsigned long lru_pages = 0;
1513 /* The swap token gets in the way of swapout... */
1514 if (!priority)
1515 disable_swap_token();
1517 sc.nr_io_pages = 0;
1518 all_zones_ok = 1;
1521 * Scan in the highmem->dma direction for the highest
1522 * zone which needs scanning
1524 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
1525 struct zone *zone = pgdat->node_zones + i;
1527 if (!populated_zone(zone))
1528 continue;
1530 if (zone_is_all_unreclaimable(zone) &&
1531 priority != DEF_PRIORITY)
1532 continue;
1534 if (!zone_watermark_ok(zone, order, zone->pages_high,
1535 0, 0)) {
1536 end_zone = i;
1537 break;
1540 if (i < 0)
1541 goto out;
1543 for (i = 0; i <= end_zone; i++) {
1544 struct zone *zone = pgdat->node_zones + i;
1546 lru_pages += zone_page_state(zone, NR_ACTIVE)
1547 + zone_page_state(zone, NR_INACTIVE);
1551 * Now scan the zone in the dma->highmem direction, stopping
1552 * at the last zone which needs scanning.
1554 * We do this because the page allocator works in the opposite
1555 * direction. This prevents the page allocator from allocating
1556 * pages behind kswapd's direction of progress, which would
1557 * cause too much scanning of the lower zones.
1559 for (i = 0; i <= end_zone; i++) {
1560 struct zone *zone = pgdat->node_zones + i;
1561 int nr_slab;
1563 if (!populated_zone(zone))
1564 continue;
1566 if (zone_is_all_unreclaimable(zone) &&
1567 priority != DEF_PRIORITY)
1568 continue;
1570 if (!zone_watermark_ok(zone, order, zone->pages_high,
1571 end_zone, 0))
1572 all_zones_ok = 0;
1573 temp_priority[i] = priority;
1574 sc.nr_scanned = 0;
1575 note_zone_scanning_priority(zone, priority);
1577 * We put equal pressure on every zone, unless one
1578 * zone has way too many pages free already.
1580 if (!zone_watermark_ok(zone, order, 8*zone->pages_high,
1581 end_zone, 0))
1582 nr_reclaimed += shrink_zone(priority, zone, &sc);
1583 reclaim_state->reclaimed_slab = 0;
1584 nr_slab = shrink_slab(sc.nr_scanned, GFP_KERNEL,
1585 lru_pages);
1586 nr_reclaimed += reclaim_state->reclaimed_slab;
1587 total_scanned += sc.nr_scanned;
1588 if (zone_is_all_unreclaimable(zone))
1589 continue;
1590 if (nr_slab == 0 && zone->pages_scanned >=
1591 (zone_page_state(zone, NR_ACTIVE)
1592 + zone_page_state(zone, NR_INACTIVE)) * 6)
1593 zone_set_flag(zone,
1594 ZONE_ALL_UNRECLAIMABLE);
1596 * If we've done a decent amount of scanning and
1597 * the reclaim ratio is low, start doing writepage
1598 * even in laptop mode
1600 if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
1601 total_scanned > nr_reclaimed + nr_reclaimed / 2)
1602 sc.may_writepage = 1;
1604 if (all_zones_ok)
1605 break; /* kswapd: all done */
1607 * OK, kswapd is getting into trouble. Take a nap, then take
1608 * another pass across the zones.
1610 if (total_scanned && priority < DEF_PRIORITY - 2 &&
1611 sc.nr_io_pages > sc.swap_cluster_max)
1612 congestion_wait(WRITE, HZ/10);
1615 * We do this so kswapd doesn't build up large priorities for
1616 * example when it is freeing in parallel with allocators. It
1617 * matches the direct reclaim path behaviour in terms of impact
1618 * on zone->*_priority.
1620 if (nr_reclaimed >= SWAP_CLUSTER_MAX)
1621 break;
1623 out:
1625 * Note within each zone the priority level at which this zone was
1626 * brought into a happy state. So that the next thread which scans this
1627 * zone will start out at that priority level.
1629 for (i = 0; i < pgdat->nr_zones; i++) {
1630 struct zone *zone = pgdat->node_zones + i;
1632 zone->prev_priority = temp_priority[i];
1634 if (!all_zones_ok) {
1635 cond_resched();
1637 try_to_freeze();
1639 goto loop_again;
1642 return nr_reclaimed;
1646 * The background pageout daemon, started as a kernel thread
1647 * from the init process.
1649 * This basically trickles out pages so that we have _some_
1650 * free memory available even if there is no other activity
1651 * that frees anything up. This is needed for things like routing
1652 * etc, where we otherwise might have all activity going on in
1653 * asynchronous contexts that cannot page things out.
1655 * If there are applications that are active memory-allocators
1656 * (most normal use), this basically shouldn't matter.
1658 static int kswapd(void *p)
1660 unsigned long order;
1661 pg_data_t *pgdat = (pg_data_t*)p;
1662 struct task_struct *tsk = current;
1663 DEFINE_WAIT(wait);
1664 struct reclaim_state reclaim_state = {
1665 .reclaimed_slab = 0,
1667 cpumask_t cpumask;
1669 cpumask = node_to_cpumask(pgdat->node_id);
1670 if (!cpus_empty(cpumask))
1671 set_cpus_allowed(tsk, cpumask);
1672 current->reclaim_state = &reclaim_state;
1675 * Tell the memory management that we're a "memory allocator",
1676 * and that if we need more memory we should get access to it
1677 * regardless (see "__alloc_pages()"). "kswapd" should
1678 * never get caught in the normal page freeing logic.
1680 * (Kswapd normally doesn't need memory anyway, but sometimes
1681 * you need a small amount of memory in order to be able to
1682 * page out something else, and this flag essentially protects
1683 * us from recursively trying to free more memory as we're
1684 * trying to free the first piece of memory in the first place).
1686 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
1687 set_freezable();
1689 order = 0;
1690 for ( ; ; ) {
1691 unsigned long new_order;
1693 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
1694 new_order = pgdat->kswapd_max_order;
1695 pgdat->kswapd_max_order = 0;
1696 if (order < new_order) {
1698 * Don't sleep if someone wants a larger 'order'
1699 * allocation
1701 order = new_order;
1702 } else {
1703 if (!freezing(current))
1704 schedule();
1706 order = pgdat->kswapd_max_order;
1708 finish_wait(&pgdat->kswapd_wait, &wait);
1710 if (!try_to_freeze()) {
1711 /* We can speed up thawing tasks if we don't call
1712 * balance_pgdat after returning from the refrigerator
1714 balance_pgdat(pgdat, order);
1717 return 0;
1721 * A zone is low on free memory, so wake its kswapd task to service it.
1723 void wakeup_kswapd(struct zone *zone, int order)
1725 pg_data_t *pgdat;
1727 if (!populated_zone(zone))
1728 return;
1730 pgdat = zone->zone_pgdat;
1731 if (zone_watermark_ok(zone, order, zone->pages_low, 0, 0))
1732 return;
1733 if (pgdat->kswapd_max_order < order)
1734 pgdat->kswapd_max_order = order;
1735 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1736 return;
1737 if (!waitqueue_active(&pgdat->kswapd_wait))
1738 return;
1739 wake_up_interruptible(&pgdat->kswapd_wait);
1742 #ifdef CONFIG_PM
1744 * Helper function for shrink_all_memory(). Tries to reclaim 'nr_pages' pages
1745 * from LRU lists system-wide, for given pass and priority, and returns the
1746 * number of reclaimed pages
1748 * For pass > 3 we also try to shrink the LRU lists that contain a few pages
1750 static unsigned long shrink_all_zones(unsigned long nr_pages, int prio,
1751 int pass, struct scan_control *sc)
1753 struct zone *zone;
1754 unsigned long nr_to_scan, ret = 0;
1756 for_each_zone(zone) {
1758 if (!populated_zone(zone))
1759 continue;
1761 if (zone_is_all_unreclaimable(zone) && prio != DEF_PRIORITY)
1762 continue;
1764 /* For pass = 0 we don't shrink the active list */
1765 if (pass > 0) {
1766 zone->nr_scan_active +=
1767 (zone_page_state(zone, NR_ACTIVE) >> prio) + 1;
1768 if (zone->nr_scan_active >= nr_pages || pass > 3) {
1769 zone->nr_scan_active = 0;
1770 nr_to_scan = min(nr_pages,
1771 zone_page_state(zone, NR_ACTIVE));
1772 shrink_active_list(nr_to_scan, zone, sc, prio);
1776 zone->nr_scan_inactive +=
1777 (zone_page_state(zone, NR_INACTIVE) >> prio) + 1;
1778 if (zone->nr_scan_inactive >= nr_pages || pass > 3) {
1779 zone->nr_scan_inactive = 0;
1780 nr_to_scan = min(nr_pages,
1781 zone_page_state(zone, NR_INACTIVE));
1782 ret += shrink_inactive_list(nr_to_scan, zone, sc);
1783 if (ret >= nr_pages)
1784 return ret;
1788 return ret;
1791 static unsigned long count_lru_pages(void)
1793 return global_page_state(NR_ACTIVE) + global_page_state(NR_INACTIVE);
1797 * Try to free `nr_pages' of memory, system-wide, and return the number of
1798 * freed pages.
1800 * Rather than trying to age LRUs the aim is to preserve the overall
1801 * LRU order by reclaiming preferentially
1802 * inactive > active > active referenced > active mapped
1804 unsigned long shrink_all_memory(unsigned long nr_pages)
1806 unsigned long lru_pages, nr_slab;
1807 unsigned long ret = 0;
1808 int pass;
1809 struct reclaim_state reclaim_state;
1810 struct scan_control sc = {
1811 .gfp_mask = GFP_KERNEL,
1812 .may_swap = 0,
1813 .swap_cluster_max = nr_pages,
1814 .may_writepage = 1,
1815 .swappiness = vm_swappiness,
1816 .isolate_pages = isolate_pages_global,
1819 current->reclaim_state = &reclaim_state;
1821 lru_pages = count_lru_pages();
1822 nr_slab = global_page_state(NR_SLAB_RECLAIMABLE);
1823 /* If slab caches are huge, it's better to hit them first */
1824 while (nr_slab >= lru_pages) {
1825 reclaim_state.reclaimed_slab = 0;
1826 shrink_slab(nr_pages, sc.gfp_mask, lru_pages);
1827 if (!reclaim_state.reclaimed_slab)
1828 break;
1830 ret += reclaim_state.reclaimed_slab;
1831 if (ret >= nr_pages)
1832 goto out;
1834 nr_slab -= reclaim_state.reclaimed_slab;
1838 * We try to shrink LRUs in 5 passes:
1839 * 0 = Reclaim from inactive_list only
1840 * 1 = Reclaim from active list but don't reclaim mapped
1841 * 2 = 2nd pass of type 1
1842 * 3 = Reclaim mapped (normal reclaim)
1843 * 4 = 2nd pass of type 3
1845 for (pass = 0; pass < 5; pass++) {
1846 int prio;
1848 /* Force reclaiming mapped pages in the passes #3 and #4 */
1849 if (pass > 2) {
1850 sc.may_swap = 1;
1851 sc.swappiness = 100;
1854 for (prio = DEF_PRIORITY; prio >= 0; prio--) {
1855 unsigned long nr_to_scan = nr_pages - ret;
1857 sc.nr_scanned = 0;
1858 ret += shrink_all_zones(nr_to_scan, prio, pass, &sc);
1859 if (ret >= nr_pages)
1860 goto out;
1862 reclaim_state.reclaimed_slab = 0;
1863 shrink_slab(sc.nr_scanned, sc.gfp_mask,
1864 count_lru_pages());
1865 ret += reclaim_state.reclaimed_slab;
1866 if (ret >= nr_pages)
1867 goto out;
1869 if (sc.nr_scanned && prio < DEF_PRIORITY - 2)
1870 congestion_wait(WRITE, HZ / 10);
1875 * If ret = 0, we could not shrink LRUs, but there may be something
1876 * in slab caches
1878 if (!ret) {
1879 do {
1880 reclaim_state.reclaimed_slab = 0;
1881 shrink_slab(nr_pages, sc.gfp_mask, count_lru_pages());
1882 ret += reclaim_state.reclaimed_slab;
1883 } while (ret < nr_pages && reclaim_state.reclaimed_slab > 0);
1886 out:
1887 current->reclaim_state = NULL;
1889 return ret;
1891 #endif
1893 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1894 not required for correctness. So if the last cpu in a node goes
1895 away, we get changed to run anywhere: as the first one comes back,
1896 restore their cpu bindings. */
1897 static int __devinit cpu_callback(struct notifier_block *nfb,
1898 unsigned long action, void *hcpu)
1900 pg_data_t *pgdat;
1901 cpumask_t mask;
1902 int nid;
1904 if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
1905 for_each_node_state(nid, N_HIGH_MEMORY) {
1906 pgdat = NODE_DATA(nid);
1907 mask = node_to_cpumask(pgdat->node_id);
1908 if (any_online_cpu(mask) != NR_CPUS)
1909 /* One of our CPUs online: restore mask */
1910 set_cpus_allowed(pgdat->kswapd, mask);
1913 return NOTIFY_OK;
1917 * This kswapd start function will be called by init and node-hot-add.
1918 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
1920 int kswapd_run(int nid)
1922 pg_data_t *pgdat = NODE_DATA(nid);
1923 int ret = 0;
1925 if (pgdat->kswapd)
1926 return 0;
1928 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
1929 if (IS_ERR(pgdat->kswapd)) {
1930 /* failure at boot is fatal */
1931 BUG_ON(system_state == SYSTEM_BOOTING);
1932 printk("Failed to start kswapd on node %d\n",nid);
1933 ret = -1;
1935 return ret;
1938 static int __init kswapd_init(void)
1940 int nid;
1942 swap_setup();
1943 for_each_node_state(nid, N_HIGH_MEMORY)
1944 kswapd_run(nid);
1945 hotcpu_notifier(cpu_callback, 0);
1946 return 0;
1949 module_init(kswapd_init)
1951 #ifdef CONFIG_NUMA
1953 * Zone reclaim mode
1955 * If non-zero call zone_reclaim when the number of free pages falls below
1956 * the watermarks.
1958 int zone_reclaim_mode __read_mostly;
1960 #define RECLAIM_OFF 0
1961 #define RECLAIM_ZONE (1<<0) /* Run shrink_cache on the zone */
1962 #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
1963 #define RECLAIM_SWAP (1<<2) /* Swap pages out during reclaim */
1966 * Priority for ZONE_RECLAIM. This determines the fraction of pages
1967 * of a node considered for each zone_reclaim. 4 scans 1/16th of
1968 * a zone.
1970 #define ZONE_RECLAIM_PRIORITY 4
1973 * Percentage of pages in a zone that must be unmapped for zone_reclaim to
1974 * occur.
1976 int sysctl_min_unmapped_ratio = 1;
1979 * If the number of slab pages in a zone grows beyond this percentage then
1980 * slab reclaim needs to occur.
1982 int sysctl_min_slab_ratio = 5;
1985 * Try to free up some pages from this zone through reclaim.
1987 static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
1989 /* Minimum pages needed in order to stay on node */
1990 const unsigned long nr_pages = 1 << order;
1991 struct task_struct *p = current;
1992 struct reclaim_state reclaim_state;
1993 int priority;
1994 unsigned long nr_reclaimed = 0;
1995 struct scan_control sc = {
1996 .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
1997 .may_swap = !!(zone_reclaim_mode & RECLAIM_SWAP),
1998 .swap_cluster_max = max_t(unsigned long, nr_pages,
1999 SWAP_CLUSTER_MAX),
2000 .gfp_mask = gfp_mask,
2001 .swappiness = vm_swappiness,
2002 .isolate_pages = isolate_pages_global,
2004 unsigned long slab_reclaimable;
2006 disable_swap_token();
2007 cond_resched();
2009 * We need to be able to allocate from the reserves for RECLAIM_SWAP
2010 * and we also need to be able to write out pages for RECLAIM_WRITE
2011 * and RECLAIM_SWAP.
2013 p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
2014 reclaim_state.reclaimed_slab = 0;
2015 p->reclaim_state = &reclaim_state;
2017 if (zone_page_state(zone, NR_FILE_PAGES) -
2018 zone_page_state(zone, NR_FILE_MAPPED) >
2019 zone->min_unmapped_pages) {
2021 * Free memory by calling shrink zone with increasing
2022 * priorities until we have enough memory freed.
2024 priority = ZONE_RECLAIM_PRIORITY;
2025 do {
2026 note_zone_scanning_priority(zone, priority);
2027 nr_reclaimed += shrink_zone(priority, zone, &sc);
2028 priority--;
2029 } while (priority >= 0 && nr_reclaimed < nr_pages);
2032 slab_reclaimable = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
2033 if (slab_reclaimable > zone->min_slab_pages) {
2035 * shrink_slab() does not currently allow us to determine how
2036 * many pages were freed in this zone. So we take the current
2037 * number of slab pages and shake the slab until it is reduced
2038 * by the same nr_pages that we used for reclaiming unmapped
2039 * pages.
2041 * Note that shrink_slab will free memory on all zones and may
2042 * take a long time.
2044 while (shrink_slab(sc.nr_scanned, gfp_mask, order) &&
2045 zone_page_state(zone, NR_SLAB_RECLAIMABLE) >
2046 slab_reclaimable - nr_pages)
2050 * Update nr_reclaimed by the number of slab pages we
2051 * reclaimed from this zone.
2053 nr_reclaimed += slab_reclaimable -
2054 zone_page_state(zone, NR_SLAB_RECLAIMABLE);
2057 p->reclaim_state = NULL;
2058 current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
2059 return nr_reclaimed >= nr_pages;
2062 int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
2064 int node_id;
2065 int ret;
2068 * Zone reclaim reclaims unmapped file backed pages and
2069 * slab pages if we are over the defined limits.
2071 * A small portion of unmapped file backed pages is needed for
2072 * file I/O otherwise pages read by file I/O will be immediately
2073 * thrown out if the zone is overallocated. So we do not reclaim
2074 * if less than a specified percentage of the zone is used by
2075 * unmapped file backed pages.
2077 if (zone_page_state(zone, NR_FILE_PAGES) -
2078 zone_page_state(zone, NR_FILE_MAPPED) <= zone->min_unmapped_pages
2079 && zone_page_state(zone, NR_SLAB_RECLAIMABLE)
2080 <= zone->min_slab_pages)
2081 return 0;
2083 if (zone_is_all_unreclaimable(zone))
2084 return 0;
2087 * Do not scan if the allocation should not be delayed.
2089 if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
2090 return 0;
2093 * Only run zone reclaim on the local zone or on zones that do not
2094 * have associated processors. This will favor the local processor
2095 * over remote processors and spread off node memory allocations
2096 * as wide as possible.
2098 node_id = zone_to_nid(zone);
2099 if (node_state(node_id, N_CPU) && node_id != numa_node_id())
2100 return 0;
2102 if (zone_test_and_set_flag(zone, ZONE_RECLAIM_LOCKED))
2103 return 0;
2104 ret = __zone_reclaim(zone, gfp_mask, order);
2105 zone_clear_flag(zone, ZONE_RECLAIM_LOCKED);
2107 return ret;
2109 #endif