1 /*
2 * linux/mm/vmscan.c
3 *
4 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
5 *
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.
12 */
14 #include <linux/mm.h>
15 #include <linux/module.h>
16 #include <linux/gfp.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/backing-dev.h>
30 #include <linux/rmap.h>
31 #include <linux/topology.h>
32 #include <linux/cpu.h>
33 #include <linux/cpuset.h>
34 #include <linux/compaction.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>
41 #include <linux/delayacct.h>
42 #include <linux/sysctl.h>
43 #include <linux/oom.h>
44 #include <linux/prefetch.h>
45 #include <linux/debugfs.h>
47 #include <asm/tlbflush.h>
48 #include <asm/div64.h>
50 #include <linux/swapops.h>
52 #include "internal.h"
54 #define CREATE_TRACE_POINTS
55 #include <trace/events/vmscan.h>
57 struct scan_control {
58 /* Incremented by the number of inactive pages that were scanned */
59 unsigned long nr_scanned;
61 /* Number of pages freed so far during a call to shrink_zones() */
62 unsigned long nr_reclaimed;
64 /* How many pages shrink_list() should reclaim */
65 unsigned long nr_to_reclaim;
67 unsigned long hibernation_mode;
69 /* This context's GFP mask */
70 gfp_t gfp_mask;
72 int may_writepage;
74 /* Can mapped pages be reclaimed? */
75 int may_unmap;
77 /* Can pages be swapped as part of reclaim? */
78 int may_swap;
80 int order;
82 /* Scan (total_size >> priority) pages at once */
83 int priority;
85 /*
86 * The memory cgroup that hit its limit and as a result is the
87 * primary target of this reclaim invocation.
88 */
89 struct mem_cgroup *target_mem_cgroup;
91 /*
92 * Nodemask of nodes allowed by the caller. If NULL, all nodes
93 * are scanned.
94 */
95 nodemask_t *nodemask;
96 };
98 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
100 #ifdef ARCH_HAS_PREFETCH
101 #define prefetch_prev_lru_page(_page, _base, _field) \
102 do { \
103 if ((_page)->lru.prev != _base) { \
104 struct page *prev; \
105 \
106 prev = lru_to_page(&(_page->lru)); \
107 prefetch(&prev->_field); \
108 } \
109 } while (0)
110 #else
111 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
112 #endif
114 #ifdef ARCH_HAS_PREFETCHW
115 #define prefetchw_prev_lru_page(_page, _base, _field) \
116 do { \
117 if ((_page)->lru.prev != _base) { \
118 struct page *prev; \
119 \
120 prev = lru_to_page(&(_page->lru)); \
121 prefetchw(&prev->_field); \
122 } \
123 } while (0)
124 #else
125 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
126 #endif
128 /*
129 * From 0 .. 100. Higher means more swappy.
130 */
131 int vm_swappiness = 60;
132 long vm_total_pages; /* The total number of pages which the VM controls */
134 static LIST_HEAD(shrinker_list);
135 static DECLARE_RWSEM(shrinker_rwsem);
137 #ifdef CONFIG_MEMCG
138 static bool global_reclaim(struct scan_control *sc)
139 {
140 return !sc->target_mem_cgroup;
141 }
142 #else
143 static bool global_reclaim(struct scan_control *sc)
144 {
145 return true;
146 }
147 #endif
149 static unsigned long get_lru_size(struct lruvec *lruvec, enum lru_list lru)
150 {
151 if (!mem_cgroup_disabled())
152 return mem_cgroup_get_lru_size(lruvec, lru);
154 return zone_page_state(lruvec_zone(lruvec), NR_LRU_BASE + lru);
155 }
157 struct dentry *debug_file;
159 static int debug_shrinker_show(struct seq_file *s, void *unused)
160 {
161 struct shrinker *shrinker;
162 struct shrink_control sc;
164 sc.gfp_mask = -1;
165 sc.nr_to_scan = 0;
167 down_read(&shrinker_rwsem);
168 list_for_each_entry(shrinker, &shrinker_list, list) {
169 char name[64];
170 int num_objs;
172 num_objs = shrinker->shrink(shrinker, &sc);
173 seq_printf(s, "%pf %d\n", shrinker->shrink, num_objs);
174 }
175 up_read(&shrinker_rwsem);
176 return 0;
177 }
179 static int debug_shrinker_open(struct inode *inode, struct file *file)
180 {
181 return single_open(file, debug_shrinker_show, inode->i_private);
182 }
184 static const struct file_operations debug_shrinker_fops = {
185 .open = debug_shrinker_open,
186 .read = seq_read,
187 .llseek = seq_lseek,
188 .release = single_release,
189 };
191 /*
192 * Add a shrinker callback to be called from the vm
193 */
194 void register_shrinker(struct shrinker *shrinker)
195 {
196 atomic_long_set(&shrinker->nr_in_batch, 0);
197 down_write(&shrinker_rwsem);
198 list_add_tail(&shrinker->list, &shrinker_list);
199 up_write(&shrinker_rwsem);
200 }
201 EXPORT_SYMBOL(register_shrinker);
203 static int __init add_shrinker_debug(void)
204 {
205 debugfs_create_file("shrinker", 0644, NULL, NULL,
206 &debug_shrinker_fops);
207 return 0;
208 }
210 late_initcall(add_shrinker_debug);
212 /*
213 * Remove one
214 */
215 void unregister_shrinker(struct shrinker *shrinker)
216 {
217 down_write(&shrinker_rwsem);
218 list_del(&shrinker->list);
219 up_write(&shrinker_rwsem);
220 }
221 EXPORT_SYMBOL(unregister_shrinker);
223 static inline int do_shrinker_shrink(struct shrinker *shrinker,
224 struct shrink_control *sc,
225 unsigned long nr_to_scan)
226 {
227 sc->nr_to_scan = nr_to_scan;
228 return (*shrinker->shrink)(shrinker, sc);
229 }
231 #define SHRINK_BATCH 128
232 /*
233 * Call the shrink functions to age shrinkable caches
234 *
235 * Here we assume it costs one seek to replace a lru page and that it also
236 * takes a seek to recreate a cache object. With this in mind we age equal
237 * percentages of the lru and ageable caches. This should balance the seeks
238 * generated by these structures.
239 *
240 * If the vm encountered mapped pages on the LRU it increase the pressure on
241 * slab to avoid swapping.
242 *
243 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
244 *
245 * `lru_pages' represents the number of on-LRU pages in all the zones which
246 * are eligible for the caller's allocation attempt. It is used for balancing
247 * slab reclaim versus page reclaim.
248 *
249 * Returns the number of slab objects which we shrunk.
250 */
251 unsigned long shrink_slab(struct shrink_control *shrink,
252 unsigned long nr_pages_scanned,
253 unsigned long lru_pages)
254 {
255 struct shrinker *shrinker;
256 unsigned long ret = 0;
258 if (nr_pages_scanned == 0)
259 nr_pages_scanned = SWAP_CLUSTER_MAX;
261 if (!down_read_trylock(&shrinker_rwsem)) {
262 /* Assume we'll be able to shrink next time */
263 ret = 1;
264 goto out;
265 }
267 list_for_each_entry(shrinker, &shrinker_list, list) {
268 unsigned long long delta;
269 long total_scan;
270 long max_pass;
271 int shrink_ret = 0;
272 long nr;
273 long new_nr;
274 long batch_size = shrinker->batch ? shrinker->batch
275 : SHRINK_BATCH;
277 max_pass = do_shrinker_shrink(shrinker, shrink, 0);
278 if (max_pass <= 0)
279 continue;
281 /*
282 * copy the current shrinker scan count into a local variable
283 * and zero it so that other concurrent shrinker invocations
284 * don't also do this scanning work.
285 */
286 nr = atomic_long_xchg(&shrinker->nr_in_batch, 0);
288 total_scan = nr;
289 delta = (4 * nr_pages_scanned) / shrinker->seeks;
290 delta *= max_pass;
291 do_div(delta, lru_pages + 1);
292 total_scan += delta;
293 if (total_scan < 0) {
294 printk(KERN_ERR "shrink_slab: %pF negative objects to "
295 "delete nr=%ld\n",
296 shrinker->shrink, total_scan);
297 total_scan = max_pass;
298 }
300 /*
301 * We need to avoid excessive windup on filesystem shrinkers
302 * due to large numbers of GFP_NOFS allocations causing the
303 * shrinkers to return -1 all the time. This results in a large
304 * nr being built up so when a shrink that can do some work
305 * comes along it empties the entire cache due to nr >>>
306 * max_pass. This is bad for sustaining a working set in
307 * memory.
308 *
309 * Hence only allow the shrinker to scan the entire cache when
310 * a large delta change is calculated directly.
311 */
312 if (delta < max_pass / 4)
313 total_scan = min(total_scan, max_pass / 2);
315 /*
316 * Avoid risking looping forever due to too large nr value:
317 * never try to free more than twice the estimate number of
318 * freeable entries.
319 */
320 if (total_scan > max_pass * 2)
321 total_scan = max_pass * 2;
323 trace_mm_shrink_slab_start(shrinker, shrink, nr,
324 nr_pages_scanned, lru_pages,
325 max_pass, delta, total_scan);
327 while (total_scan >= batch_size) {
328 int nr_before;
330 nr_before = do_shrinker_shrink(shrinker, shrink, 0);
331 shrink_ret = do_shrinker_shrink(shrinker, shrink,
332 batch_size);
333 if (shrink_ret == -1)
334 break;
335 if (shrink_ret < nr_before)
336 ret += nr_before - shrink_ret;
337 count_vm_events(SLABS_SCANNED, batch_size);
338 total_scan -= batch_size;
340 cond_resched();
341 }
343 /*
344 * move the unused scan count back into the shrinker in a
345 * manner that handles concurrent updates. If we exhausted the
346 * scan, there is no need to do an update.
347 */
348 if (total_scan > 0)
349 new_nr = atomic_long_add_return(total_scan,
350 &shrinker->nr_in_batch);
351 else
352 new_nr = atomic_long_read(&shrinker->nr_in_batch);
354 trace_mm_shrink_slab_end(shrinker, shrink_ret, nr, new_nr);
355 }
356 up_read(&shrinker_rwsem);
357 out:
358 cond_resched();
359 return ret;
360 }
362 static inline int is_page_cache_freeable(struct page *page)
363 {
364 /*
365 * A freeable page cache page is referenced only by the caller
366 * that isolated the page, the page cache radix tree and
367 * optional buffer heads at page->private.
368 */
369 return page_count(page) - page_has_private(page) == 2;
370 }
372 static int may_write_to_queue(struct backing_dev_info *bdi,
373 struct scan_control *sc)
374 {
375 if (current->flags & PF_SWAPWRITE)
376 return 1;
377 if (!bdi_write_congested(bdi))
378 return 1;
379 if (bdi == current->backing_dev_info)
380 return 1;
381 return 0;
382 }
384 /*
385 * We detected a synchronous write error writing a page out. Probably
386 * -ENOSPC. We need to propagate that into the address_space for a subsequent
387 * fsync(), msync() or close().
388 *
389 * The tricky part is that after writepage we cannot touch the mapping: nothing
390 * prevents it from being freed up. But we have a ref on the page and once
391 * that page is locked, the mapping is pinned.
392 *
393 * We're allowed to run sleeping lock_page() here because we know the caller has
394 * __GFP_FS.
395 */
396 static void handle_write_error(struct address_space *mapping,
397 struct page *page, int error)
398 {
399 lock_page(page);
400 if (page_mapping(page) == mapping)
401 mapping_set_error(mapping, error);
402 unlock_page(page);
403 }
405 /* possible outcome of pageout() */
406 typedef enum {
407 /* failed to write page out, page is locked */
408 PAGE_KEEP,
409 /* move page to the active list, page is locked */
410 PAGE_ACTIVATE,
411 /* page has been sent to the disk successfully, page is unlocked */
412 PAGE_SUCCESS,
413 /* page is clean and locked */
414 PAGE_CLEAN,
415 } pageout_t;
417 /*
418 * pageout is called by shrink_page_list() for each dirty page.
419 * Calls ->writepage().
420 */
421 static pageout_t pageout(struct page *page, struct address_space *mapping,
422 struct scan_control *sc)
423 {
424 /*
425 * If the page is dirty, only perform writeback if that write
426 * will be non-blocking. To prevent this allocation from being
427 * stalled by pagecache activity. But note that there may be
428 * stalls if we need to run get_block(). We could test
429 * PagePrivate for that.
430 *
431 * If this process is currently in __generic_file_aio_write() against
432 * this page's queue, we can perform writeback even if that
433 * will block.
434 *
435 * If the page is swapcache, write it back even if that would
436 * block, for some throttling. This happens by accident, because
437 * swap_backing_dev_info is bust: it doesn't reflect the
438 * congestion state of the swapdevs. Easy to fix, if needed.
439 */
440 if (!is_page_cache_freeable(page))
441 return PAGE_KEEP;
442 if (!mapping) {
443 /*
444 * Some data journaling orphaned pages can have
445 * page->mapping == NULL while being dirty with clean buffers.
446 */
447 if (page_has_private(page)) {
448 if (try_to_free_buffers(page)) {
449 ClearPageDirty(page);
450 printk("%s: orphaned page\n", __func__);
451 return PAGE_CLEAN;
452 }
453 }
454 return PAGE_KEEP;
455 }
456 if (mapping->a_ops->writepage == NULL)
457 return PAGE_ACTIVATE;
458 if (!may_write_to_queue(mapping->backing_dev_info, sc))
459 return PAGE_KEEP;
461 if (clear_page_dirty_for_io(page)) {
462 int res;
463 struct writeback_control wbc = {
464 .sync_mode = WB_SYNC_NONE,
465 .nr_to_write = SWAP_CLUSTER_MAX,
466 .range_start = 0,
467 .range_end = LLONG_MAX,
468 .for_reclaim = 1,
469 };
471 SetPageReclaim(page);
472 res = mapping->a_ops->writepage(page, &wbc);
473 if (res < 0)
474 handle_write_error(mapping, page, res);
475 if (res == AOP_WRITEPAGE_ACTIVATE) {
476 ClearPageReclaim(page);
477 return PAGE_ACTIVATE;
478 }
480 if (!PageWriteback(page)) {
481 /* synchronous write or broken a_ops? */
482 ClearPageReclaim(page);
483 }
484 trace_mm_vmscan_writepage(page, trace_reclaim_flags(page));
485 inc_zone_page_state(page, NR_VMSCAN_WRITE);
486 return PAGE_SUCCESS;
487 }
489 return PAGE_CLEAN;
490 }
492 /*
493 * Same as remove_mapping, but if the page is removed from the mapping, it
494 * gets returned with a refcount of 0.
495 */
496 static int __remove_mapping(struct address_space *mapping, struct page *page)
497 {
498 BUG_ON(!PageLocked(page));
499 BUG_ON(mapping != page_mapping(page));
501 spin_lock_irq(&mapping->tree_lock);
502 /*
503 * The non racy check for a busy page.
504 *
505 * Must be careful with the order of the tests. When someone has
506 * a ref to the page, it may be possible that they dirty it then
507 * drop the reference. So if PageDirty is tested before page_count
508 * here, then the following race may occur:
509 *
510 * get_user_pages(&page);
511 * [user mapping goes away]
512 * write_to(page);
513 * !PageDirty(page) [good]
514 * SetPageDirty(page);
515 * put_page(page);
516 * !page_count(page) [good, discard it]
517 *
518 * [oops, our write_to data is lost]
519 *
520 * Reversing the order of the tests ensures such a situation cannot
521 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
522 * load is not satisfied before that of page->_count.
523 *
524 * Note that if SetPageDirty is always performed via set_page_dirty,
525 * and thus under tree_lock, then this ordering is not required.
526 */
527 if (!page_freeze_refs(page, 2))
528 goto cannot_free;
529 /* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
530 if (unlikely(PageDirty(page))) {
531 page_unfreeze_refs(page, 2);
532 goto cannot_free;
533 }
535 if (PageSwapCache(page)) {
536 swp_entry_t swap = { .val = page_private(page) };
537 __delete_from_swap_cache(page);
538 spin_unlock_irq(&mapping->tree_lock);
539 swapcache_free(swap, page);
540 } else {
541 void (*freepage)(struct page *);
543 freepage = mapping->a_ops->freepage;
545 __delete_from_page_cache(page);
546 spin_unlock_irq(&mapping->tree_lock);
547 mem_cgroup_uncharge_cache_page(page);
549 if (freepage != NULL)
550 freepage(page);
551 }
553 return 1;
555 cannot_free:
556 spin_unlock_irq(&mapping->tree_lock);
557 return 0;
558 }
560 /*
561 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
562 * someone else has a ref on the page, abort and return 0. If it was
563 * successfully detached, return 1. Assumes the caller has a single ref on
564 * this page.
565 */
566 int remove_mapping(struct address_space *mapping, struct page *page)
567 {
568 if (__remove_mapping(mapping, page)) {
569 /*
570 * Unfreezing the refcount with 1 rather than 2 effectively
571 * drops the pagecache ref for us without requiring another
572 * atomic operation.
573 */
574 page_unfreeze_refs(page, 1);
575 return 1;
576 }
577 return 0;
578 }
580 /**
581 * putback_lru_page - put previously isolated page onto appropriate LRU list
582 * @page: page to be put back to appropriate lru list
583 *
584 * Add previously isolated @page to appropriate LRU list.
585 * Page may still be unevictable for other reasons.
586 *
587 * lru_lock must not be held, interrupts must be enabled.
588 */
589 void putback_lru_page(struct page *page)
590 {
591 int lru;
592 int active = !!TestClearPageActive(page);
593 int was_unevictable = PageUnevictable(page);
595 VM_BUG_ON(PageLRU(page));
597 redo:
598 ClearPageUnevictable(page);
600 if (page_evictable(page)) {
601 /*
602 * For evictable pages, we can use the cache.
603 * In event of a race, worst case is we end up with an
604 * unevictable page on [in]active list.
605 * We know how to handle that.
606 */
607 lru = active + page_lru_base_type(page);
608 lru_cache_add_lru(page, lru);
609 } else {
610 /*
611 * Put unevictable pages directly on zone's unevictable
612 * list.
613 */
614 lru = LRU_UNEVICTABLE;
615 add_page_to_unevictable_list(page);
616 /*
617 * When racing with an mlock or AS_UNEVICTABLE clearing
618 * (page is unlocked) make sure that if the other thread
619 * does not observe our setting of PG_lru and fails
620 * isolation/check_move_unevictable_pages,
621 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
622 * the page back to the evictable list.
623 *
624 * The other side is TestClearPageMlocked() or shmem_lock().
625 */
626 smp_mb();
627 }
629 /*
630 * page's status can change while we move it among lru. If an evictable
631 * page is on unevictable list, it never be freed. To avoid that,
632 * check after we added it to the list, again.
633 */
634 if (lru == LRU_UNEVICTABLE && page_evictable(page)) {
635 if (!isolate_lru_page(page)) {
636 put_page(page);
637 goto redo;
638 }
639 /* This means someone else dropped this page from LRU
640 * So, it will be freed or putback to LRU again. There is
641 * nothing to do here.
642 */
643 }
645 if (was_unevictable && lru != LRU_UNEVICTABLE)
646 count_vm_event(UNEVICTABLE_PGRESCUED);
647 else if (!was_unevictable && lru == LRU_UNEVICTABLE)
648 count_vm_event(UNEVICTABLE_PGCULLED);
650 put_page(page); /* drop ref from isolate */
651 }
653 enum page_references {
654 PAGEREF_RECLAIM,
655 PAGEREF_RECLAIM_CLEAN,
656 PAGEREF_KEEP,
657 PAGEREF_ACTIVATE,
658 };
660 static enum page_references page_check_references(struct page *page,
661 struct scan_control *sc)
662 {
663 int referenced_ptes, referenced_page;
664 unsigned long vm_flags;
666 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
667 &vm_flags);
668 referenced_page = TestClearPageReferenced(page);
670 /*
671 * Mlock lost the isolation race with us. Let try_to_unmap()
672 * move the page to the unevictable list.
673 */
674 if (vm_flags & VM_LOCKED)
675 return PAGEREF_RECLAIM;
677 if (referenced_ptes) {
678 if (PageSwapBacked(page))
679 return PAGEREF_ACTIVATE;
680 /*
681 * All mapped pages start out with page table
682 * references from the instantiating fault, so we need
683 * to look twice if a mapped file page is used more
684 * than once.
685 *
686 * Mark it and spare it for another trip around the
687 * inactive list. Another page table reference will
688 * lead to its activation.
689 *
690 * Note: the mark is set for activated pages as well
691 * so that recently deactivated but used pages are
692 * quickly recovered.
693 */
694 SetPageReferenced(page);
696 if (referenced_page || referenced_ptes > 1)
697 return PAGEREF_ACTIVATE;
699 /*
700 * Activate file-backed executable pages after first usage.
701 */
702 if (vm_flags & VM_EXEC)
703 return PAGEREF_ACTIVATE;
705 return PAGEREF_KEEP;
706 }
708 /* Reclaim if clean, defer dirty pages to writeback */
709 if (referenced_page && !PageSwapBacked(page))
710 return PAGEREF_RECLAIM_CLEAN;
712 return PAGEREF_RECLAIM;
713 }
715 /*
716 * shrink_page_list() returns the number of reclaimed pages
717 */
718 static unsigned long shrink_page_list(struct list_head *page_list,
719 struct zone *zone,
720 struct scan_control *sc,
721 enum ttu_flags ttu_flags,
722 unsigned long *ret_nr_dirty,
723 unsigned long *ret_nr_writeback,
724 bool force_reclaim)
725 {
726 LIST_HEAD(ret_pages);
727 LIST_HEAD(free_pages);
728 int pgactivate = 0;
729 unsigned long nr_dirty = 0;
730 unsigned long nr_congested = 0;
731 unsigned long nr_reclaimed = 0;
732 unsigned long nr_writeback = 0;
734 cond_resched();
736 mem_cgroup_uncharge_start();
737 while (!list_empty(page_list)) {
738 struct address_space *mapping;
739 struct page *page;
740 int may_enter_fs;
741 enum page_references references = PAGEREF_RECLAIM_CLEAN;
743 cond_resched();
745 page = lru_to_page(page_list);
746 list_del(&page->lru);
748 if (!trylock_page(page))
749 goto keep;
751 VM_BUG_ON(PageActive(page));
752 VM_BUG_ON(page_zone(page) != zone);
754 sc->nr_scanned++;
756 if (unlikely(!page_evictable(page)))
757 goto cull_mlocked;
759 if (!sc->may_unmap && page_mapped(page))
760 goto keep_locked;
762 /* Double the slab pressure for mapped and swapcache pages */
763 if (page_mapped(page) || PageSwapCache(page))
764 sc->nr_scanned++;
766 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
767 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
769 if (PageWriteback(page)) {
770 /*
771 * memcg doesn't have any dirty pages throttling so we
772 * could easily OOM just because too many pages are in
773 * writeback and there is nothing else to reclaim.
774 *
775 * Check __GFP_IO, certainly because a loop driver
776 * thread might enter reclaim, and deadlock if it waits
777 * on a page for which it is needed to do the write
778 * (loop masks off __GFP_IO|__GFP_FS for this reason);
779 * but more thought would probably show more reasons.
780 *
781 * Don't require __GFP_FS, since we're not going into
782 * the FS, just waiting on its writeback completion.
783 * Worryingly, ext4 gfs2 and xfs allocate pages with
784 * grab_cache_page_write_begin(,,AOP_FLAG_NOFS), so
785 * testing may_enter_fs here is liable to OOM on them.
786 */
787 if (global_reclaim(sc) ||
788 !PageReclaim(page) || !(sc->gfp_mask & __GFP_IO)) {
789 /*
790 * This is slightly racy - end_page_writeback()
791 * might have just cleared PageReclaim, then
792 * setting PageReclaim here end up interpreted
793 * as PageReadahead - but that does not matter
794 * enough to care. What we do want is for this
795 * page to have PageReclaim set next time memcg
796 * reclaim reaches the tests above, so it will
797 * then wait_on_page_writeback() to avoid OOM;
798 * and it's also appropriate in global reclaim.
799 */
800 SetPageReclaim(page);
801 nr_writeback++;
802 goto keep_locked;
803 }
804 wait_on_page_writeback(page);
805 }
807 if (!force_reclaim)
808 references = page_check_references(page, sc);
810 switch (references) {
811 case PAGEREF_ACTIVATE:
812 goto activate_locked;
813 case PAGEREF_KEEP:
814 goto keep_locked;
815 case PAGEREF_RECLAIM:
816 case PAGEREF_RECLAIM_CLEAN:
817 ; /* try to reclaim the page below */
818 }
820 /*
821 * Anonymous process memory has backing store?
822 * Try to allocate it some swap space here.
823 */
824 if (PageAnon(page) && !PageSwapCache(page)) {
825 if (!(sc->gfp_mask & __GFP_IO))
826 goto keep_locked;
827 if (!add_to_swap(page))
828 goto activate_locked;
829 may_enter_fs = 1;
830 }
832 mapping = page_mapping(page);
834 /*
835 * The page is mapped into the page tables of one or more
836 * processes. Try to unmap it here.
837 */
838 if (page_mapped(page) && mapping) {
839 switch (try_to_unmap(page, ttu_flags)) {
840 case SWAP_FAIL:
841 goto activate_locked;
842 case SWAP_AGAIN:
843 goto keep_locked;
844 case SWAP_MLOCK:
845 goto cull_mlocked;
846 case SWAP_SUCCESS:
847 ; /* try to free the page below */
848 }
849 }
851 if (PageDirty(page)) {
852 nr_dirty++;
854 /*
855 * Only kswapd can writeback filesystem pages to
856 * avoid risk of stack overflow but do not writeback
857 * unless under significant pressure.
858 */
859 if (page_is_file_cache(page) &&
860 (!current_is_kswapd() ||
861 sc->priority >= DEF_PRIORITY - 2)) {
862 /*
863 * Immediately reclaim when written back.
864 * Similar in principal to deactivate_page()
865 * except we already have the page isolated
866 * and know it's dirty
867 */
868 inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE);
869 SetPageReclaim(page);
871 goto keep_locked;
872 }
874 if (references == PAGEREF_RECLAIM_CLEAN)
875 goto keep_locked;
876 if (!may_enter_fs)
877 goto keep_locked;
878 if (!sc->may_writepage)
879 goto keep_locked;
881 /* Page is dirty, try to write it out here */
882 switch (pageout(page, mapping, sc)) {
883 case PAGE_KEEP:
884 nr_congested++;
885 goto keep_locked;
886 case PAGE_ACTIVATE:
887 goto activate_locked;
888 case PAGE_SUCCESS:
889 if (PageWriteback(page))
890 goto keep;
891 if (PageDirty(page))
892 goto keep;
894 /*
895 * A synchronous write - probably a ramdisk. Go
896 * ahead and try to reclaim the page.
897 */
898 if (!trylock_page(page))
899 goto keep;
900 if (PageDirty(page) || PageWriteback(page))
901 goto keep_locked;
902 mapping = page_mapping(page);
903 case PAGE_CLEAN:
904 ; /* try to free the page below */
905 }
906 }
908 /*
909 * If the page has buffers, try to free the buffer mappings
910 * associated with this page. If we succeed we try to free
911 * the page as well.
912 *
913 * We do this even if the page is PageDirty().
914 * try_to_release_page() does not perform I/O, but it is
915 * possible for a page to have PageDirty set, but it is actually
916 * clean (all its buffers are clean). This happens if the
917 * buffers were written out directly, with submit_bh(). ext3
918 * will do this, as well as the blockdev mapping.
919 * try_to_release_page() will discover that cleanness and will
920 * drop the buffers and mark the page clean - it can be freed.
921 *
922 * Rarely, pages can have buffers and no ->mapping. These are
923 * the pages which were not successfully invalidated in
924 * truncate_complete_page(). We try to drop those buffers here
925 * and if that worked, and the page is no longer mapped into
926 * process address space (page_count == 1) it can be freed.
927 * Otherwise, leave the page on the LRU so it is swappable.
928 */
929 if (page_has_private(page)) {
930 if (!try_to_release_page(page, sc->gfp_mask))
931 goto activate_locked;
932 if (!mapping && page_count(page) == 1) {
933 unlock_page(page);
934 if (put_page_testzero(page))
935 goto free_it;
936 else {
937 /*
938 * rare race with speculative reference.
939 * the speculative reference will free
940 * this page shortly, so we may
941 * increment nr_reclaimed here (and
942 * leave it off the LRU).
943 */
944 nr_reclaimed++;
945 continue;
946 }
947 }
948 }
950 if (!mapping || !__remove_mapping(mapping, page))
951 goto keep_locked;
953 /*
954 * At this point, we have no other references and there is
955 * no way to pick any more up (removed from LRU, removed
956 * from pagecache). Can use non-atomic bitops now (and
957 * we obviously don't have to worry about waking up a process
958 * waiting on the page lock, because there are no references.
959 */
960 __clear_page_locked(page);
961 free_it:
962 nr_reclaimed++;
964 /*
965 * Is there need to periodically free_page_list? It would
966 * appear not as the counts should be low
967 */
968 list_add(&page->lru, &free_pages);
969 continue;
971 cull_mlocked:
972 if (PageSwapCache(page))
973 try_to_free_swap(page);
974 unlock_page(page);
975 putback_lru_page(page);
976 continue;
978 activate_locked:
979 /* Not a candidate for swapping, so reclaim swap space. */
980 if (PageSwapCache(page) && vm_swap_full())
981 try_to_free_swap(page);
982 VM_BUG_ON(PageActive(page));
983 SetPageActive(page);
984 pgactivate++;
985 keep_locked:
986 unlock_page(page);
987 keep:
988 list_add(&page->lru, &ret_pages);
989 VM_BUG_ON(PageLRU(page) || PageUnevictable(page));
990 }
992 /*
993 * Tag a zone as congested if all the dirty pages encountered were
994 * backed by a congested BDI. In this case, reclaimers should just
995 * back off and wait for congestion to clear because further reclaim
996 * will encounter the same problem
997 */
998 if (nr_dirty && nr_dirty == nr_congested && global_reclaim(sc))
999 zone_set_flag(zone, ZONE_CONGESTED);
1001 free_hot_cold_page_list(&free_pages, 1);
1003 list_splice(&ret_pages, page_list);
1004 count_vm_events(PGACTIVATE, pgactivate);
1005 mem_cgroup_uncharge_end();
1006 *ret_nr_dirty += nr_dirty;
1007 *ret_nr_writeback += nr_writeback;
1008 return nr_reclaimed;
1009 }
1011 unsigned long reclaim_clean_pages_from_list(struct zone *zone,
1012 struct list_head *page_list)
1013 {
1014 struct scan_control sc = {
1015 .gfp_mask = GFP_KERNEL,
1016 .priority = DEF_PRIORITY,
1017 .may_unmap = 1,
1018 };
1019 unsigned long ret, dummy1, dummy2;
1020 struct page *page, *next;
1021 LIST_HEAD(clean_pages);
1023 list_for_each_entry_safe(page, next, page_list, lru) {
1024 if (page_is_file_cache(page) && !PageDirty(page)) {
1025 ClearPageActive(page);
1026 list_move(&page->lru, &clean_pages);
1027 }
1028 }
1030 ret = shrink_page_list(&clean_pages, zone, &sc,
1031 TTU_UNMAP|TTU_IGNORE_ACCESS,
1032 &dummy1, &dummy2, true);
1033 list_splice(&clean_pages, page_list);
1034 __mod_zone_page_state(zone, NR_ISOLATED_FILE, -ret);
1035 return ret;
1036 }
1038 /*
1039 * Attempt to remove the specified page from its LRU. Only take this page
1040 * if it is of the appropriate PageActive status. Pages which are being
1041 * freed elsewhere are also ignored.
1042 *
1043 * page: page to consider
1044 * mode: one of the LRU isolation modes defined above
1045 *
1046 * returns 0 on success, -ve errno on failure.
1047 */
1048 int __isolate_lru_page(struct page *page, isolate_mode_t mode)
1049 {
1050 int ret = -EINVAL;
1052 /* Only take pages on the LRU. */
1053 if (!PageLRU(page))
1054 return ret;
1056 /* Compaction should not handle unevictable pages but CMA can do so */
1057 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1058 return ret;
1060 ret = -EBUSY;
1062 /*
1063 * To minimise LRU disruption, the caller can indicate that it only
1064 * wants to isolate pages it will be able to operate on without
1065 * blocking - clean pages for the most part.
1066 *
1067 * ISOLATE_CLEAN means that only clean pages should be isolated. This
1068 * is used by reclaim when it is cannot write to backing storage
1069 *
1070 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1071 * that it is possible to migrate without blocking
1072 */
1073 if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
1074 /* All the caller can do on PageWriteback is block */
1075 if (PageWriteback(page))
1076 return ret;
1078 if (PageDirty(page)) {
1079 struct address_space *mapping;
1081 /* ISOLATE_CLEAN means only clean pages */
1082 if (mode & ISOLATE_CLEAN)
1083 return ret;
1085 /*
1086 * Only pages without mappings or that have a
1087 * ->migratepage callback are possible to migrate
1088 * without blocking
1089 */
1090 mapping = page_mapping(page);
1091 if (mapping && !mapping->a_ops->migratepage)
1092 return ret;
1093 }
1094 }
1096 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1097 return ret;
1099 if (likely(get_page_unless_zero(page))) {
1100 /*
1101 * Be careful not to clear PageLRU until after we're
1102 * sure the page is not being freed elsewhere -- the
1103 * page release code relies on it.
1104 */
1105 ClearPageLRU(page);
1106 ret = 0;
1107 }
1109 return ret;
1110 }
1112 /*
1113 * zone->lru_lock is heavily contended. Some of the functions that
1114 * shrink the lists perform better by taking out a batch of pages
1115 * and working on them outside the LRU lock.
1116 *
1117 * For pagecache intensive workloads, this function is the hottest
1118 * spot in the kernel (apart from copy_*_user functions).
1119 *
1120 * Appropriate locks must be held before calling this function.
1121 *
1122 * @nr_to_scan: The number of pages to look through on the list.
1123 * @lruvec: The LRU vector to pull pages from.
1124 * @dst: The temp list to put pages on to.
1125 * @nr_scanned: The number of pages that were scanned.
1126 * @sc: The scan_control struct for this reclaim session
1127 * @mode: One of the LRU isolation modes
1128 * @lru: LRU list id for isolating
1129 *
1130 * returns how many pages were moved onto *@dst.
1131 */
1132 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
1133 struct lruvec *lruvec, struct list_head *dst,
1134 unsigned long *nr_scanned, struct scan_control *sc,
1135 isolate_mode_t mode, enum lru_list lru)
1136 {
1137 struct list_head *src = &lruvec->lists[lru];
1138 unsigned long nr_taken = 0;
1139 unsigned long scan;
1141 for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
1142 struct page *page;
1143 int nr_pages;
1145 page = lru_to_page(src);
1146 prefetchw_prev_lru_page(page, src, flags);
1148 VM_BUG_ON(!PageLRU(page));
1150 switch (__isolate_lru_page(page, mode)) {
1151 case 0:
1152 nr_pages = hpage_nr_pages(page);
1153 mem_cgroup_update_lru_size(lruvec, lru, -nr_pages);
1154 list_move(&page->lru, dst);
1155 nr_taken += nr_pages;
1156 break;
1158 case -EBUSY:
1159 /* else it is being freed elsewhere */
1160 list_move(&page->lru, src);
1161 continue;
1163 default:
1164 BUG();
1165 }
1166 }
1168 *nr_scanned = scan;
1169 trace_mm_vmscan_lru_isolate(sc->order, nr_to_scan, scan,
1170 nr_taken, mode, is_file_lru(lru));
1171 return nr_taken;
1172 }
1174 /**
1175 * isolate_lru_page - tries to isolate a page from its LRU list
1176 * @page: page to isolate from its LRU list
1177 *
1178 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
1179 * vmstat statistic corresponding to whatever LRU list the page was on.
1180 *
1181 * Returns 0 if the page was removed from an LRU list.
1182 * Returns -EBUSY if the page was not on an LRU list.
1183 *
1184 * The returned page will have PageLRU() cleared. If it was found on
1185 * the active list, it will have PageActive set. If it was found on
1186 * the unevictable list, it will have the PageUnevictable bit set. That flag
1187 * may need to be cleared by the caller before letting the page go.
1188 *
1189 * The vmstat statistic corresponding to the list on which the page was
1190 * found will be decremented.
1191 *
1192 * Restrictions:
1193 * (1) Must be called with an elevated refcount on the page. This is a
1194 * fundamentnal difference from isolate_lru_pages (which is called
1195 * without a stable reference).
1196 * (2) the lru_lock must not be held.
1197 * (3) interrupts must be enabled.
1198 */
1199 int isolate_lru_page(struct page *page)
1200 {
1201 int ret = -EBUSY;
1203 VM_BUG_ON(!page_count(page));
1205 if (PageLRU(page)) {
1206 struct zone *zone = page_zone(page);
1207 struct lruvec *lruvec;
1209 spin_lock_irq(&zone->lru_lock);
1210 lruvec = mem_cgroup_page_lruvec(page, zone);
1211 if (PageLRU(page)) {
1212 int lru = page_lru(page);
1213 get_page(page);
1214 ClearPageLRU(page);
1215 del_page_from_lru_list(page, lruvec, lru);
1216 ret = 0;
1217 }
1218 spin_unlock_irq(&zone->lru_lock);
1219 }
1220 return ret;
1221 }
1223 /*
1224 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1225 * then get resheduled. When there are massive number of tasks doing page
1226 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1227 * the LRU list will go small and be scanned faster than necessary, leading to
1228 * unnecessary swapping, thrashing and OOM.
1229 */
1230 static int too_many_isolated(struct zone *zone, int file,
1231 struct scan_control *sc)
1232 {
1233 unsigned long inactive, isolated;
1235 if (current_is_kswapd())
1236 return 0;
1238 if (!global_reclaim(sc))
1239 return 0;
1241 if (file) {
1242 inactive = zone_page_state(zone, NR_INACTIVE_FILE);
1243 isolated = zone_page_state(zone, NR_ISOLATED_FILE);
1244 } else {
1245 inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1246 isolated = zone_page_state(zone, NR_ISOLATED_ANON);
1247 }
1249 /*
1250 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
1251 * won't get blocked by normal direct-reclaimers, forming a circular
1252 * deadlock.
1253 */
1254 if ((sc->gfp_mask & GFP_IOFS) == GFP_IOFS)
1255 inactive >>= 3;
1257 return isolated > inactive;
1258 }
1260 static noinline_for_stack void
1261 putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
1262 {
1263 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1264 struct zone *zone = lruvec_zone(lruvec);
1265 LIST_HEAD(pages_to_free);
1267 /*
1268 * Put back any unfreeable pages.
1269 */
1270 while (!list_empty(page_list)) {
1271 struct page *page = lru_to_page(page_list);
1272 int lru;
1274 VM_BUG_ON(PageLRU(page));
1275 list_del(&page->lru);
1276 if (unlikely(!page_evictable(page))) {
1277 spin_unlock_irq(&zone->lru_lock);
1278 putback_lru_page(page);
1279 spin_lock_irq(&zone->lru_lock);
1280 continue;
1281 }
1283 lruvec = mem_cgroup_page_lruvec(page, zone);
1285 SetPageLRU(page);
1286 lru = page_lru(page);
1287 add_page_to_lru_list(page, lruvec, lru);
1289 if (is_active_lru(lru)) {
1290 int file = is_file_lru(lru);
1291 int numpages = hpage_nr_pages(page);
1292 reclaim_stat->recent_rotated[file] += numpages;
1293 }
1294 if (put_page_testzero(page)) {
1295 __ClearPageLRU(page);
1296 __ClearPageActive(page);
1297 del_page_from_lru_list(page, lruvec, lru);
1299 if (unlikely(PageCompound(page))) {
1300 spin_unlock_irq(&zone->lru_lock);
1301 (*get_compound_page_dtor(page))(page);
1302 spin_lock_irq(&zone->lru_lock);
1303 } else
1304 list_add(&page->lru, &pages_to_free);
1305 }
1306 }
1308 /*
1309 * To save our caller's stack, now use input list for pages to free.
1310 */
1311 list_splice(&pages_to_free, page_list);
1312 }
1314 /*
1315 * shrink_inactive_list() is a helper for shrink_zone(). It returns the number
1316 * of reclaimed pages
1317 */
1318 static noinline_for_stack unsigned long
1319 shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
1320 struct scan_control *sc, enum lru_list lru)
1321 {
1322 LIST_HEAD(page_list);
1323 unsigned long nr_scanned;
1324 unsigned long nr_reclaimed = 0;
1325 unsigned long nr_taken;
1326 unsigned long nr_dirty = 0;
1327 unsigned long nr_writeback = 0;
1328 isolate_mode_t isolate_mode = 0;
1329 int file = is_file_lru(lru);
1330 struct zone *zone = lruvec_zone(lruvec);
1331 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1333 while (unlikely(too_many_isolated(zone, file, sc))) {
1334 congestion_wait(BLK_RW_ASYNC, HZ/10);
1336 /* We are about to die and free our memory. Return now. */
1337 if (fatal_signal_pending(current))
1338 return SWAP_CLUSTER_MAX;
1339 }
1341 lru_add_drain();
1343 if (!sc->may_unmap)
1344 isolate_mode |= ISOLATE_UNMAPPED;
1345 if (!sc->may_writepage)
1346 isolate_mode |= ISOLATE_CLEAN;
1348 spin_lock_irq(&zone->lru_lock);
1350 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
1351 &nr_scanned, sc, isolate_mode, lru);
1353 __mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
1354 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
1356 if (global_reclaim(sc)) {
1357 zone->pages_scanned += nr_scanned;
1358 if (current_is_kswapd())
1359 __count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scanned);
1360 else
1361 __count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scanned);
1362 }
1363 spin_unlock_irq(&zone->lru_lock);
1365 if (nr_taken == 0)
1366 return 0;
1368 nr_reclaimed = shrink_page_list(&page_list, zone, sc, TTU_UNMAP,
1369 &nr_dirty, &nr_writeback, false);
1371 spin_lock_irq(&zone->lru_lock);
1373 reclaim_stat->recent_scanned[file] += nr_taken;
1375 if (global_reclaim(sc)) {
1376 if (current_is_kswapd())
1377 __count_zone_vm_events(PGSTEAL_KSWAPD, zone,
1378 nr_reclaimed);
1379 else
1380 __count_zone_vm_events(PGSTEAL_DIRECT, zone,
1381 nr_reclaimed);
1382 }
1384 putback_inactive_pages(lruvec, &page_list);
1386 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1388 spin_unlock_irq(&zone->lru_lock);
1390 free_hot_cold_page_list(&page_list, 1);
1392 /*
1393 * If reclaim is isolating dirty pages under writeback, it implies
1394 * that the long-lived page allocation rate is exceeding the page
1395 * laundering rate. Either the global limits are not being effective
1396 * at throttling processes due to the page distribution throughout
1397 * zones or there is heavy usage of a slow backing device. The
1398 * only option is to throttle from reclaim context which is not ideal
1399 * as there is no guarantee the dirtying process is throttled in the
1400 * same way balance_dirty_pages() manages.
1401 *
1402 * This scales the number of dirty pages that must be under writeback
1403 * before throttling depending on priority. It is a simple backoff
1404 * function that has the most effect in the range DEF_PRIORITY to
1405 * DEF_PRIORITY-2 which is the priority reclaim is considered to be
1406 * in trouble and reclaim is considered to be in trouble.
1407 *
1408 * DEF_PRIORITY 100% isolated pages must be PageWriteback to throttle
1409 * DEF_PRIORITY-1 50% must be PageWriteback
1410 * DEF_PRIORITY-2 25% must be PageWriteback, kswapd in trouble
1411 * ...
1412 * DEF_PRIORITY-6 For SWAP_CLUSTER_MAX isolated pages, throttle if any
1413 * isolated page is PageWriteback
1414 */
1415 if (nr_writeback && nr_writeback >=
1416 (nr_taken >> (DEF_PRIORITY - sc->priority)))
1417 wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10);
1419 trace_mm_vmscan_lru_shrink_inactive(zone->zone_pgdat->node_id,
1420 zone_idx(zone),
1421 nr_scanned, nr_reclaimed,
1422 sc->priority,
1423 trace_shrink_flags(file));
1424 return nr_reclaimed;
1425 }
1427 /*
1428 * This moves pages from the active list to the inactive list.
1429 *
1430 * We move them the other way if the page is referenced by one or more
1431 * processes, from rmap.
1432 *
1433 * If the pages are mostly unmapped, the processing is fast and it is
1434 * appropriate to hold zone->lru_lock across the whole operation. But if
1435 * the pages are mapped, the processing is slow (page_referenced()) so we
1436 * should drop zone->lru_lock around each page. It's impossible to balance
1437 * this, so instead we remove the pages from the LRU while processing them.
1438 * It is safe to rely on PG_active against the non-LRU pages in here because
1439 * nobody will play with that bit on a non-LRU page.
1440 *
1441 * The downside is that we have to touch page->_count against each page.
1442 * But we had to alter page->flags anyway.
1443 */
1445 static void move_active_pages_to_lru(struct lruvec *lruvec,
1446 struct list_head *list,
1447 struct list_head *pages_to_free,
1448 enum lru_list lru)
1449 {
1450 struct zone *zone = lruvec_zone(lruvec);
1451 unsigned long pgmoved = 0;
1452 struct page *page;
1453 int nr_pages;
1455 while (!list_empty(list)) {
1456 page = lru_to_page(list);
1457 lruvec = mem_cgroup_page_lruvec(page, zone);
1459 VM_BUG_ON(PageLRU(page));
1460 SetPageLRU(page);
1462 nr_pages = hpage_nr_pages(page);
1463 mem_cgroup_update_lru_size(lruvec, lru, nr_pages);
1464 list_move(&page->lru, &lruvec->lists[lru]);
1465 pgmoved += nr_pages;
1467 if (put_page_testzero(page)) {
1468 __ClearPageLRU(page);
1469 __ClearPageActive(page);
1470 del_page_from_lru_list(page, lruvec, lru);
1472 if (unlikely(PageCompound(page))) {
1473 spin_unlock_irq(&zone->lru_lock);
1474 (*get_compound_page_dtor(page))(page);
1475 spin_lock_irq(&zone->lru_lock);
1476 } else
1477 list_add(&page->lru, pages_to_free);
1478 }
1479 }
1480 __mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved);
1481 if (!is_active_lru(lru))
1482 __count_vm_events(PGDEACTIVATE, pgmoved);
1483 }
1485 static void shrink_active_list(unsigned long nr_to_scan,
1486 struct lruvec *lruvec,
1487 struct scan_control *sc,
1488 enum lru_list lru)
1489 {
1490 unsigned long nr_taken;
1491 unsigned long nr_scanned;
1492 unsigned long vm_flags;
1493 LIST_HEAD(l_hold); /* The pages which were snipped off */
1494 LIST_HEAD(l_active);
1495 LIST_HEAD(l_inactive);
1496 struct page *page;
1497 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1498 unsigned long nr_rotated = 0;
1499 isolate_mode_t isolate_mode = 0;
1500 int file = is_file_lru(lru);
1501 struct zone *zone = lruvec_zone(lruvec);
1503 lru_add_drain();
1505 if (!sc->may_unmap)
1506 isolate_mode |= ISOLATE_UNMAPPED;
1507 if (!sc->may_writepage)
1508 isolate_mode |= ISOLATE_CLEAN;
1510 spin_lock_irq(&zone->lru_lock);
1512 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
1513 &nr_scanned, sc, isolate_mode, lru);
1514 if (global_reclaim(sc))
1515 zone->pages_scanned += nr_scanned;
1517 reclaim_stat->recent_scanned[file] += nr_taken;
1519 __count_zone_vm_events(PGREFILL, zone, nr_scanned);
1520 __mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
1521 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
1522 spin_unlock_irq(&zone->lru_lock);
1524 while (!list_empty(&l_hold)) {
1525 cond_resched();
1526 page = lru_to_page(&l_hold);
1527 list_del(&page->lru);
1529 if (unlikely(!page_evictable(page))) {
1530 putback_lru_page(page);
1531 continue;
1532 }
1534 if (unlikely(buffer_heads_over_limit)) {
1535 if (page_has_private(page) && trylock_page(page)) {
1536 if (page_has_private(page))
1537 try_to_release_page(page, 0);
1538 unlock_page(page);
1539 }
1540 }
1542 if (page_referenced(page, 0, sc->target_mem_cgroup,
1543 &vm_flags)) {
1544 nr_rotated += hpage_nr_pages(page);
1545 /*
1546 * Identify referenced, file-backed active pages and
1547 * give them one more trip around the active list. So
1548 * that executable code get better chances to stay in
1549 * memory under moderate memory pressure. Anon pages
1550 * are not likely to be evicted by use-once streaming
1551 * IO, plus JVM can create lots of anon VM_EXEC pages,
1552 * so we ignore them here.
1553 */
1554 if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
1555 list_add(&page->lru, &l_active);
1556 continue;
1557 }
1558 }
1560 ClearPageActive(page); /* we are de-activating */
1561 list_add(&page->lru, &l_inactive);
1562 }
1564 /*
1565 * Move pages back to the lru list.
1566 */
1567 spin_lock_irq(&zone->lru_lock);
1568 /*
1569 * Count referenced pages from currently used mappings as rotated,
1570 * even though only some of them are actually re-activated. This
1571 * helps balance scan pressure between file and anonymous pages in
1572 * get_scan_ratio.
1573 */
1574 reclaim_stat->recent_rotated[file] += nr_rotated;
1576 move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
1577 move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1578 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1579 spin_unlock_irq(&zone->lru_lock);
1581 free_hot_cold_page_list(&l_hold, 1);
1582 }
1584 #ifdef CONFIG_SWAP
1585 static int inactive_anon_is_low_global(struct zone *zone)
1586 {
1587 unsigned long active, inactive;
1589 active = zone_page_state(zone, NR_ACTIVE_ANON);
1590 inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1592 if (inactive * zone->inactive_ratio < active)
1593 return 1;
1595 return 0;
1596 }
1598 /**
1599 * inactive_anon_is_low - check if anonymous pages need to be deactivated
1600 * @lruvec: LRU vector to check
1601 *
1602 * Returns true if the zone does not have enough inactive anon pages,
1603 * meaning some active anon pages need to be deactivated.
1604 */
1605 static int inactive_anon_is_low(struct lruvec *lruvec)
1606 {
1607 /*
1608 * If we don't have swap space, anonymous page deactivation
1609 * is pointless.
1610 */
1611 if (!total_swap_pages)
1612 return 0;
1614 if (!mem_cgroup_disabled())
1615 return mem_cgroup_inactive_anon_is_low(lruvec);
1617 return inactive_anon_is_low_global(lruvec_zone(lruvec));
1618 }
1619 #else
1620 static inline int inactive_anon_is_low(struct lruvec *lruvec)
1621 {
1622 return 0;
1623 }
1624 #endif
1626 static int inactive_file_is_low_global(struct zone *zone)
1627 {
1628 unsigned long active, inactive;
1630 active = zone_page_state(zone, NR_ACTIVE_FILE);
1631 inactive = zone_page_state(zone, NR_INACTIVE_FILE);
1633 return (active > inactive);
1634 }
1636 /**
1637 * inactive_file_is_low - check if file pages need to be deactivated
1638 * @lruvec: LRU vector to check
1639 *
1640 * When the system is doing streaming IO, memory pressure here
1641 * ensures that active file pages get deactivated, until more
1642 * than half of the file pages are on the inactive list.
1643 *
1644 * Once we get to that situation, protect the system's working
1645 * set from being evicted by disabling active file page aging.
1646 *
1647 * This uses a different ratio than the anonymous pages, because
1648 * the page cache uses a use-once replacement algorithm.
1649 */
1650 static int inactive_file_is_low(struct lruvec *lruvec)
1651 {
1652 if (!mem_cgroup_disabled())
1653 return mem_cgroup_inactive_file_is_low(lruvec);
1655 return inactive_file_is_low_global(lruvec_zone(lruvec));
1656 }
1658 static int inactive_list_is_low(struct lruvec *lruvec, enum lru_list lru)
1659 {
1660 if (is_file_lru(lru))
1661 return inactive_file_is_low(lruvec);
1662 else
1663 return inactive_anon_is_low(lruvec);
1664 }
1666 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
1667 struct lruvec *lruvec, struct scan_control *sc)
1668 {
1669 if (is_active_lru(lru)) {
1670 if (inactive_list_is_low(lruvec, lru))
1671 shrink_active_list(nr_to_scan, lruvec, sc, lru);
1672 return 0;
1673 }
1675 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
1676 }
1678 static int vmscan_swappiness(struct scan_control *sc)
1679 {
1680 if (global_reclaim(sc))
1681 return vm_swappiness;
1682 return mem_cgroup_swappiness(sc->target_mem_cgroup);
1683 }
1685 /*
1686 * Determine how aggressively the anon and file LRU lists should be
1687 * scanned. The relative value of each set of LRU lists is determined
1688 * by looking at the fraction of the pages scanned we did rotate back
1689 * onto the active list instead of evict.
1690 *
1691 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
1692 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
1693 */
1694 static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
1695 unsigned long *nr)
1696 {
1697 unsigned long anon, file, free;
1698 unsigned long anon_prio, file_prio;
1699 unsigned long ap, fp;
1700 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1701 u64 fraction[2], denominator;
1702 enum lru_list lru;
1703 int noswap = 0;
1704 bool force_scan = false;
1705 struct zone *zone = lruvec_zone(lruvec);
1707 /*
1708 * If the zone or memcg is small, nr[l] can be 0. This
1709 * results in no scanning on this priority and a potential
1710 * priority drop. Global direct reclaim can go to the next
1711 * zone and tends to have no problems. Global kswapd is for
1712 * zone balancing and it needs to scan a minimum amount. When
1713 * reclaiming for a memcg, a priority drop can cause high
1714 * latencies, so it's better to scan a minimum amount there as
1715 * well.
1716 */
1717 if (current_is_kswapd() && zone->all_unreclaimable)
1718 force_scan = true;
1719 if (!global_reclaim(sc))
1720 force_scan = true;
1722 /* If we have no swap space, do not bother scanning anon pages. */
1723 if (!sc->may_swap || (nr_swap_pages <= 0)) {
1724 noswap = 1;
1725 fraction[0] = 0;
1726 fraction[1] = 1;
1727 denominator = 1;
1728 goto out;
1729 }
1731 anon = get_lru_size(lruvec, LRU_ACTIVE_ANON) +
1732 get_lru_size(lruvec, LRU_INACTIVE_ANON);
1733 file = get_lru_size(lruvec, LRU_ACTIVE_FILE) +
1734 get_lru_size(lruvec, LRU_INACTIVE_FILE);
1736 if (global_reclaim(sc)) {
1737 free = zone_page_state(zone, NR_FREE_PAGES);
1738 if (unlikely(file + free <= high_wmark_pages(zone))) {
1739 /*
1740 * If we have very few page cache pages, force-scan
1741 * anon pages.
1742 */
1743 fraction[0] = 1;
1744 fraction[1] = 0;
1745 denominator = 1;
1746 goto out;
1747 } else if (!inactive_file_is_low_global(zone)) {
1748 /*
1749 * There is enough inactive page cache, do not
1750 * reclaim anything from the working set right now.
1751 */
1752 fraction[0] = 0;
1753 fraction[1] = 1;
1754 denominator = 1;
1755 goto out;
1756 }
1757 }
1759 /*
1760 * With swappiness at 100, anonymous and file have the same priority.
1761 * This scanning priority is essentially the inverse of IO cost.
1762 */
1763 anon_prio = vmscan_swappiness(sc);
1764 file_prio = 200 - anon_prio;
1766 /*
1767 * OK, so we have swap space and a fair amount of page cache
1768 * pages. We use the recently rotated / recently scanned
1769 * ratios to determine how valuable each cache is.
1770 *
1771 * Because workloads change over time (and to avoid overflow)
1772 * we keep these statistics as a floating average, which ends
1773 * up weighing recent references more than old ones.
1774 *
1775 * anon in [0], file in [1]
1776 */
1777 spin_lock_irq(&zone->lru_lock);
1778 if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
1779 reclaim_stat->recent_scanned[0] /= 2;
1780 reclaim_stat->recent_rotated[0] /= 2;
1781 }
1783 if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
1784 reclaim_stat->recent_scanned[1] /= 2;
1785 reclaim_stat->recent_rotated[1] /= 2;
1786 }
1788 /*
1789 * The amount of pressure on anon vs file pages is inversely
1790 * proportional to the fraction of recently scanned pages on
1791 * each list that were recently referenced and in active use.
1792 */
1793 ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
1794 ap /= reclaim_stat->recent_rotated[0] + 1;
1796 fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
1797 fp /= reclaim_stat->recent_rotated[1] + 1;
1798 spin_unlock_irq(&zone->lru_lock);
1800 fraction[0] = ap;
1801 fraction[1] = fp;
1802 denominator = ap + fp + 1;
1803 out:
1804 for_each_evictable_lru(lru) {
1805 int file = is_file_lru(lru);
1806 unsigned long scan;
1808 scan = get_lru_size(lruvec, lru);
1809 if (sc->priority || noswap || !vmscan_swappiness(sc)) {
1810 scan >>= sc->priority;
1811 if (!scan && force_scan)
1812 scan = SWAP_CLUSTER_MAX;
1813 scan = div64_u64(scan * fraction[file], denominator);
1814 }
1815 nr[lru] = scan;
1816 }
1817 }
1819 /* Use reclaim/compaction for costly allocs or under memory pressure */
1820 static bool in_reclaim_compaction(struct scan_control *sc)
1821 {
1822 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
1823 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
1824 sc->priority < DEF_PRIORITY - 2))
1825 return true;
1827 return false;
1828 }
1830 /*
1831 * Reclaim/compaction is used for high-order allocation requests. It reclaims
1832 * order-0 pages before compacting the zone. should_continue_reclaim() returns
1833 * true if more pages should be reclaimed such that when the page allocator
1834 * calls try_to_compact_zone() that it will have enough free pages to succeed.
1835 * It will give up earlier than that if there is difficulty reclaiming pages.
1836 */
1837 static inline bool should_continue_reclaim(struct lruvec *lruvec,
1838 unsigned long nr_reclaimed,
1839 unsigned long nr_scanned,
1840 struct scan_control *sc)
1841 {
1842 unsigned long pages_for_compaction;
1843 unsigned long inactive_lru_pages;
1845 /* If not in reclaim/compaction mode, stop */
1846 if (!in_reclaim_compaction(sc))
1847 return false;
1849 /* Consider stopping depending on scan and reclaim activity */
1850 if (sc->gfp_mask & __GFP_REPEAT) {
1851 /*
1852 * For __GFP_REPEAT allocations, stop reclaiming if the
1853 * full LRU list has been scanned and we are still failing
1854 * to reclaim pages. This full LRU scan is potentially
1855 * expensive but a __GFP_REPEAT caller really wants to succeed
1856 */
1857 if (!nr_reclaimed && !nr_scanned)
1858 return false;
1859 } else {
1860 /*
1861 * For non-__GFP_REPEAT allocations which can presumably
1862 * fail without consequence, stop if we failed to reclaim
1863 * any pages from the last SWAP_CLUSTER_MAX number of
1864 * pages that were scanned. This will return to the
1865 * caller faster at the risk reclaim/compaction and
1866 * the resulting allocation attempt fails
1867 */
1868 if (!nr_reclaimed)
1869 return false;
1870 }
1872 /*
1873 * If we have not reclaimed enough pages for compaction and the
1874 * inactive lists are large enough, continue reclaiming
1875 */
1876 pages_for_compaction = (2UL << sc->order);
1877 inactive_lru_pages = get_lru_size(lruvec, LRU_INACTIVE_FILE);
1878 if (nr_swap_pages > 0)
1879 inactive_lru_pages += get_lru_size(lruvec, LRU_INACTIVE_ANON);
1880 if (sc->nr_reclaimed < pages_for_compaction &&
1881 inactive_lru_pages > pages_for_compaction)
1882 return true;
1884 /* If compaction would go ahead or the allocation would succeed, stop */
1885 switch (compaction_suitable(lruvec_zone(lruvec), sc->order)) {
1886 case COMPACT_PARTIAL:
1887 case COMPACT_CONTINUE:
1888 return false;
1889 default:
1890 return true;
1891 }
1892 }
1894 /*
1895 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
1896 */
1897 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
1898 {
1899 unsigned long nr[NR_LRU_LISTS];
1900 unsigned long nr_to_scan;
1901 enum lru_list lru;
1902 unsigned long nr_reclaimed, nr_scanned;
1903 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
1904 struct blk_plug plug;
1906 restart:
1907 nr_reclaimed = 0;
1908 nr_scanned = sc->nr_scanned;
1909 get_scan_count(lruvec, sc, nr);
1911 blk_start_plug(&plug);
1912 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
1913 nr[LRU_INACTIVE_FILE]) {
1914 for_each_evictable_lru(lru) {
1915 if (nr[lru]) {
1916 nr_to_scan = min_t(unsigned long,
1917 nr[lru], SWAP_CLUSTER_MAX);
1918 nr[lru] -= nr_to_scan;
1920 nr_reclaimed += shrink_list(lru, nr_to_scan,
1921 lruvec, sc);
1922 }
1923 }
1924 /*
1925 * On large memory systems, scan >> priority can become
1926 * really large. This is fine for the starting priority;
1927 * we want to put equal scanning pressure on each zone.
1928 * However, if the VM has a harder time of freeing pages,
1929 * with multiple processes reclaiming pages, the total
1930 * freeing target can get unreasonably large.
1931 */
1932 if (nr_reclaimed >= nr_to_reclaim &&
1933 sc->priority < DEF_PRIORITY)
1934 break;
1935 }
1936 blk_finish_plug(&plug);
1937 sc->nr_reclaimed += nr_reclaimed;
1939 /*
1940 * Even if we did not try to evict anon pages at all, we want to
1941 * rebalance the anon lru active/inactive ratio.
1942 */
1943 if (inactive_anon_is_low(lruvec))
1944 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
1945 sc, LRU_ACTIVE_ANON);
1947 /* reclaim/compaction might need reclaim to continue */
1948 if (should_continue_reclaim(lruvec, nr_reclaimed,
1949 sc->nr_scanned - nr_scanned, sc))
1950 goto restart;
1952 throttle_vm_writeout(sc->gfp_mask);
1953 }
1955 static void shrink_zone(struct zone *zone, struct scan_control *sc)
1956 {
1957 struct mem_cgroup *root = sc->target_mem_cgroup;
1958 struct mem_cgroup_reclaim_cookie reclaim = {
1959 .zone = zone,
1960 .priority = sc->priority,
1961 };
1962 struct mem_cgroup *memcg;
1964 memcg = mem_cgroup_iter(root, NULL, &reclaim);
1965 do {
1966 struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
1968 shrink_lruvec(lruvec, sc);
1970 /*
1971 * Limit reclaim has historically picked one memcg and
1972 * scanned it with decreasing priority levels until
1973 * nr_to_reclaim had been reclaimed. This priority
1974 * cycle is thus over after a single memcg.
1975 *
1976 * Direct reclaim and kswapd, on the other hand, have
1977 * to scan all memory cgroups to fulfill the overall
1978 * scan target for the zone.
1979 */
1980 if (!global_reclaim(sc)) {
1981 mem_cgroup_iter_break(root, memcg);
1982 break;
1983 }
1984 memcg = mem_cgroup_iter(root, memcg, &reclaim);
1985 } while (memcg);
1986 }
1988 /* Returns true if compaction should go ahead for a high-order request */
1989 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
1990 {
1991 unsigned long balance_gap, watermark;
1992 bool watermark_ok;
1994 /* Do not consider compaction for orders reclaim is meant to satisfy */
1995 if (sc->order <= PAGE_ALLOC_COSTLY_ORDER)
1996 return false;
1998 /*
1999 * Compaction takes time to run and there are potentially other
2000 * callers using the pages just freed. Continue reclaiming until
2001 * there is a buffer of free pages available to give compaction
2002 * a reasonable chance of completing and allocating the page
2003 */
2004 balance_gap = min(low_wmark_pages(zone),
2005 (zone->present_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
2006 KSWAPD_ZONE_BALANCE_GAP_RATIO);
2007 watermark = high_wmark_pages(zone) + balance_gap + (2UL << sc->order);
2008 watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, 0, 0);
2010 /*
2011 * If compaction is deferred, reclaim up to a point where
2012 * compaction will have a chance of success when re-enabled
2013 */
2014 if (compaction_deferred(zone, sc->order))
2015 return watermark_ok;
2017 /* If compaction is not ready to start, keep reclaiming */
2018 if (!compaction_suitable(zone, sc->order))
2019 return false;
2021 return watermark_ok;
2022 }
2024 /*
2025 * This is the direct reclaim path, for page-allocating processes. We only
2026 * try to reclaim pages from zones which will satisfy the caller's allocation
2027 * request.
2028 *
2029 * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
2030 * Because:
2031 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
2032 * allocation or
2033 * b) The target zone may be at high_wmark_pages(zone) but the lower zones
2034 * must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
2035 * zone defense algorithm.
2036 *
2037 * If a zone is deemed to be full of pinned pages then just give it a light
2038 * scan then give up on it.
2039 *
2040 * This function returns true if a zone is being reclaimed for a costly
2041 * high-order allocation and compaction is ready to begin. This indicates to
2042 * the caller that it should consider retrying the allocation instead of
2043 * further reclaim.
2044 */
2045 static bool shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
2046 {
2047 struct zoneref *z;
2048 struct zone *zone;
2049 unsigned long nr_soft_reclaimed;
2050 unsigned long nr_soft_scanned;
2051 bool aborted_reclaim = false;
2053 /*
2054 * If the number of buffer_heads in the machine exceeds the maximum
2055 * allowed level, force direct reclaim to scan the highmem zone as
2056 * highmem pages could be pinning lowmem pages storing buffer_heads
2057 */
2058 if (buffer_heads_over_limit)
2059 sc->gfp_mask |= __GFP_HIGHMEM;
2061 for_each_zone_zonelist_nodemask(zone, z, zonelist,
2062 gfp_zone(sc->gfp_mask), sc->nodemask) {
2063 if (!populated_zone(zone))
2064 continue;
2065 /*
2066 * Take care memory controller reclaiming has small influence
2067 * to global LRU.
2068 */
2069 if (global_reclaim(sc)) {
2070 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2071 continue;
2072 if (zone->all_unreclaimable &&
2073 sc->priority != DEF_PRIORITY)
2074 continue; /* Let kswapd poll it */
2075 if (IS_ENABLED(CONFIG_COMPACTION)) {
2076 /*
2077 * If we already have plenty of memory free for
2078 * compaction in this zone, don't free any more.
2079 * Even though compaction is invoked for any
2080 * non-zero order, only frequent costly order
2081 * reclamation is disruptive enough to become a
2082 * noticeable problem, like transparent huge
2083 * page allocations.
2084 */
2085 if (compaction_ready(zone, sc)) {
2086 aborted_reclaim = true;
2087 continue;
2088 }
2089 }
2090 /*
2091 * This steals pages from memory cgroups over softlimit
2092 * and returns the number of reclaimed pages and
2093 * scanned pages. This works for global memory pressure
2094 * and balancing, not for a memcg's limit.
2095 */
2096 nr_soft_scanned = 0;
2097 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
2098 sc->order, sc->gfp_mask,
2099 &nr_soft_scanned);
2100 sc->nr_reclaimed += nr_soft_reclaimed;
2101 sc->nr_scanned += nr_soft_scanned;
2102 /* need some check for avoid more shrink_zone() */
2103 }
2105 shrink_zone(zone, sc);
2106 }
2108 return aborted_reclaim;
2109 }
2111 static bool zone_reclaimable(struct zone *zone)
2112 {
2113 return zone->pages_scanned < zone_reclaimable_pages(zone) * 6;
2114 }
2116 /* All zones in zonelist are unreclaimable? */
2117 static bool all_unreclaimable(struct zonelist *zonelist,
2118 struct scan_control *sc)
2119 {
2120 struct zoneref *z;
2121 struct zone *zone;
2123 for_each_zone_zonelist_nodemask(zone, z, zonelist,
2124 gfp_zone(sc->gfp_mask), sc->nodemask) {
2125 if (!populated_zone(zone))
2126 continue;
2127 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2128 continue;
2129 if (!zone->all_unreclaimable)
2130 return false;
2131 }
2133 return true;
2134 }
2136 /*
2137 * This is the main entry point to direct page reclaim.
2138 *
2139 * If a full scan of the inactive list fails to free enough memory then we
2140 * are "out of memory" and something needs to be killed.
2141 *
2142 * If the caller is !__GFP_FS then the probability of a failure is reasonably
2143 * high - the zone may be full of dirty or under-writeback pages, which this
2144 * caller can't do much about. We kick the writeback threads and take explicit
2145 * naps in the hope that some of these pages can be written. But if the
2146 * allocating task holds filesystem locks which prevent writeout this might not
2147 * work, and the allocation attempt will fail.
2148 *
2149 * returns: 0, if no pages reclaimed
2150 * else, the number of pages reclaimed
2151 */
2152 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
2153 struct scan_control *sc,
2154 struct shrink_control *shrink)
2155 {
2156 unsigned long total_scanned = 0;
2157 struct reclaim_state *reclaim_state = current->reclaim_state;
2158 struct zoneref *z;
2159 struct zone *zone;
2160 unsigned long writeback_threshold;
2161 bool aborted_reclaim;
2163 delayacct_freepages_start();
2165 if (global_reclaim(sc))
2166 count_vm_event(ALLOCSTALL);
2168 do {
2169 sc->nr_scanned = 0;
2170 aborted_reclaim = shrink_zones(zonelist, sc);
2172 /*
2173 * Don't shrink slabs when reclaiming memory from
2174 * over limit cgroups
2175 */
2176 if (global_reclaim(sc)) {
2177 unsigned long lru_pages = 0;
2178 for_each_zone_zonelist(zone, z, zonelist,
2179 gfp_zone(sc->gfp_mask)) {
2180 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2181 continue;
2183 lru_pages += zone_reclaimable_pages(zone);
2184 }
2186 shrink_slab(shrink, sc->nr_scanned, lru_pages);
2187 if (reclaim_state) {
2188 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
2189 reclaim_state->reclaimed_slab = 0;
2190 }
2191 }
2192 total_scanned += sc->nr_scanned;
2193 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
2194 goto out;
2196 /*
2197 * Try to write back as many pages as we just scanned. This
2198 * tends to cause slow streaming writers to write data to the
2199 * disk smoothly, at the dirtying rate, which is nice. But
2200 * that's undesirable in laptop mode, where we *want* lumpy
2201 * writeout. So in laptop mode, write out the whole world.
2202 */
2203 writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
2204 if (total_scanned > writeback_threshold) {
2205 wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
2206 WB_REASON_TRY_TO_FREE_PAGES);
2207 sc->may_writepage = 1;
2208 }
2210 /* Take a nap, wait for some writeback to complete */
2211 if (!sc->hibernation_mode && sc->nr_scanned &&
2212 sc->priority < DEF_PRIORITY - 2) {
2213 struct zone *preferred_zone;
2215 first_zones_zonelist(zonelist, gfp_zone(sc->gfp_mask),
2216 &cpuset_current_mems_allowed,
2217 &preferred_zone);
2218 wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/10);
2219 }
2220 } while (--sc->priority >= 0);
2222 out:
2223 delayacct_freepages_end();
2225 if (sc->nr_reclaimed)
2226 return sc->nr_reclaimed;
2228 /*
2229 * As hibernation is going on, kswapd is freezed so that it can't mark
2230 * the zone into all_unreclaimable. Thus bypassing all_unreclaimable
2231 * check.
2232 */
2233 if (oom_killer_disabled)
2234 return 0;
2236 /* Aborted reclaim to try compaction? don't OOM, then */
2237 if (aborted_reclaim)
2238 return 1;
2240 /* top priority shrink_zones still had more to do? don't OOM, then */
2241 if (global_reclaim(sc) && !all_unreclaimable(zonelist, sc))
2242 return 1;
2244 return 0;
2245 }
2247 static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
2248 {
2249 struct zone *zone;
2250 unsigned long pfmemalloc_reserve = 0;
2251 unsigned long free_pages = 0;
2252 int i;
2253 bool wmark_ok;
2255 for (i = 0; i <= ZONE_NORMAL; i++) {
2256 zone = &pgdat->node_zones[i];
2257 pfmemalloc_reserve += min_wmark_pages(zone);
2258 free_pages += zone_page_state(zone, NR_FREE_PAGES);
2259 }
2261 wmark_ok = free_pages > pfmemalloc_reserve / 2;
2263 /* kswapd must be awake if processes are being throttled */
2264 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
2265 pgdat->classzone_idx = min(pgdat->classzone_idx,
2266 (enum zone_type)ZONE_NORMAL);
2267 wake_up_interruptible(&pgdat->kswapd_wait);
2268 }
2270 return wmark_ok;
2271 }
2273 /*
2274 * Throttle direct reclaimers if backing storage is backed by the network
2275 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
2276 * depleted. kswapd will continue to make progress and wake the processes
2277 * when the low watermark is reached.
2278 *
2279 * Returns true if a fatal signal was delivered during throttling. If this
2280 * happens, the page allocator should not consider triggering the OOM killer.
2281 */
2282 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
2283 nodemask_t *nodemask)
2284 {
2285 struct zone *zone;
2286 int high_zoneidx = gfp_zone(gfp_mask);
2287 pg_data_t *pgdat;
2289 /*
2290 * Kernel threads should not be throttled as they may be indirectly
2291 * responsible for cleaning pages necessary for reclaim to make forward
2292 * progress. kjournald for example may enter direct reclaim while
2293 * committing a transaction where throttling it could forcing other
2294 * processes to block on log_wait_commit().
2295 */
2296 if (current->flags & PF_KTHREAD)
2297 goto out;
2299 /*
2300 * If a fatal signal is pending, this process should not throttle.
2301 * It should return quickly so it can exit and free its memory
2302 */
2303 if (fatal_signal_pending(current))
2304 goto out;
2306 /* Check if the pfmemalloc reserves are ok */
2307 first_zones_zonelist(zonelist, high_zoneidx, NULL, &zone);
2308 pgdat = zone->zone_pgdat;
2309 if (pfmemalloc_watermark_ok(pgdat))
2310 goto out;
2312 /* Account for the throttling */
2313 count_vm_event(PGSCAN_DIRECT_THROTTLE);
2315 /*
2316 * If the caller cannot enter the filesystem, it's possible that it
2317 * is due to the caller holding an FS lock or performing a journal
2318 * transaction in the case of a filesystem like ext[3|4]. In this case,
2319 * it is not safe to block on pfmemalloc_wait as kswapd could be
2320 * blocked waiting on the same lock. Instead, throttle for up to a
2321 * second before continuing.
2322 */
2323 if (!(gfp_mask & __GFP_FS)) {
2324 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
2325 pfmemalloc_watermark_ok(pgdat), HZ);
2327 goto check_pending;
2328 }
2330 /* Throttle until kswapd wakes the process */
2331 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
2332 pfmemalloc_watermark_ok(pgdat));
2334 check_pending:
2335 if (fatal_signal_pending(current))
2336 return true;
2338 out:
2339 return false;
2340 }
2342 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2343 gfp_t gfp_mask, nodemask_t *nodemask)
2344 {
2345 unsigned long nr_reclaimed;
2346 struct scan_control sc = {
2347 .gfp_mask = gfp_mask,
2348 .may_writepage = !laptop_mode,
2349 .nr_to_reclaim = SWAP_CLUSTER_MAX,
2350 .may_unmap = 1,
2351 .may_swap = 1,
2352 .order = order,
2353 .priority = DEF_PRIORITY,
2354 .target_mem_cgroup = NULL,
2355 .nodemask = nodemask,
2356 };
2357 struct shrink_control shrink = {
2358 .gfp_mask = sc.gfp_mask,
2359 };
2361 /*
2362 * Do not enter reclaim if fatal signal was delivered while throttled.
2363 * 1 is returned so that the page allocator does not OOM kill at this
2364 * point.
2365 */
2366 if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
2367 return 1;
2369 trace_mm_vmscan_direct_reclaim_begin(order,
2370 sc.may_writepage,
2371 gfp_mask);
2373 nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
2375 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
2377 return nr_reclaimed;
2378 }
2380 #ifdef CONFIG_MEMCG
2382 unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg,
2383 gfp_t gfp_mask, bool noswap,
2384 struct zone *zone,
2385 unsigned long *nr_scanned)
2386 {
2387 struct scan_control sc = {
2388 .nr_scanned = 0,
2389 .nr_to_reclaim = SWAP_CLUSTER_MAX,
2390 .may_writepage = !laptop_mode,
2391 .may_unmap = 1,
2392 .may_swap = !noswap,
2393 .order = 0,
2394 .priority = 0,
2395 .target_mem_cgroup = memcg,
2396 };
2397 struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
2399 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2400 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2402 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
2403 sc.may_writepage,
2404 sc.gfp_mask);
2406 /*
2407 * NOTE: Although we can get the priority field, using it
2408 * here is not a good idea, since it limits the pages we can scan.
2409 * if we don't reclaim here, the shrink_zone from balance_pgdat
2410 * will pick up pages from other mem cgroup's as well. We hack
2411 * the priority and make it zero.
2412 */
2413 shrink_lruvec(lruvec, &sc);
2415 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
2417 *nr_scanned = sc.nr_scanned;
2418 return sc.nr_reclaimed;
2419 }
2421 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
2422 gfp_t gfp_mask,
2423 bool noswap)
2424 {
2425 struct zonelist *zonelist;
2426 unsigned long nr_reclaimed;
2427 int nid;
2428 struct scan_control sc = {
2429 .may_writepage = !laptop_mode,
2430 .may_unmap = 1,
2431 .may_swap = !noswap,
2432 .nr_to_reclaim = SWAP_CLUSTER_MAX,
2433 .order = 0,
2434 .priority = DEF_PRIORITY,
2435 .target_mem_cgroup = memcg,
2436 .nodemask = NULL, /* we don't care the placement */
2437 .gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2438 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
2439 };
2440 struct shrink_control shrink = {
2441 .gfp_mask = sc.gfp_mask,
2442 };
2444 /*
2445 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
2446 * take care of from where we get pages. So the node where we start the
2447 * scan does not need to be the current node.
2448 */
2449 nid = mem_cgroup_select_victim_node(memcg);
2451 zonelist = NODE_DATA(nid)->node_zonelists;
2453 trace_mm_vmscan_memcg_reclaim_begin(0,
2454 sc.may_writepage,
2455 sc.gfp_mask);
2457 nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
2459 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
2461 return nr_reclaimed;
2462 }
2463 #endif
2465 static void age_active_anon(struct zone *zone, struct scan_control *sc)
2466 {
2467 struct mem_cgroup *memcg;
2469 if (!total_swap_pages)
2470 return;
2472 memcg = mem_cgroup_iter(NULL, NULL, NULL);
2473 do {
2474 struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
2476 if (inactive_anon_is_low(lruvec))
2477 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
2478 sc, LRU_ACTIVE_ANON);
2480 memcg = mem_cgroup_iter(NULL, memcg, NULL);
2481 } while (memcg);
2482 }
2484 static bool zone_balanced(struct zone *zone, int order,
2485 unsigned long balance_gap, int classzone_idx)
2486 {
2487 if (!zone_watermark_ok_safe(zone, order, high_wmark_pages(zone) +
2488 balance_gap, classzone_idx, 0))
2489 return false;
2491 if (IS_ENABLED(CONFIG_COMPACTION) && order &&
2492 !compaction_suitable(zone, order))
2493 return false;
2495 return true;
2496 }
2498 /*
2499 * pgdat_balanced() is used when checking if a node is balanced.
2500 *
2501 * For order-0, all zones must be balanced!
2502 *
2503 * For high-order allocations only zones that meet watermarks and are in a
2504 * zone allowed by the callers classzone_idx are added to balanced_pages. The
2505 * total of balanced pages must be at least 25% of the zones allowed by
2506 * classzone_idx for the node to be considered balanced. Forcing all zones to
2507 * be balanced for high orders can cause excessive reclaim when there are
2508 * imbalanced zones.
2509 * The choice of 25% is due to
2510 * o a 16M DMA zone that is balanced will not balance a zone on any
2511 * reasonable sized machine
2512 * o On all other machines, the top zone must be at least a reasonable
2513 * percentage of the middle zones. For example, on 32-bit x86, highmem
2514 * would need to be at least 256M for it to be balance a whole node.
2515 * Similarly, on x86-64 the Normal zone would need to be at least 1G
2516 * to balance a node on its own. These seemed like reasonable ratios.
2517 */
2518 static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
2519 {
2520 unsigned long present_pages = 0;
2521 unsigned long balanced_pages = 0;
2522 int i;
2524 /* Check the watermark levels */
2525 for (i = 0; i <= classzone_idx; i++) {
2526 struct zone *zone = pgdat->node_zones + i;
2528 if (!populated_zone(zone))
2529 continue;
2531 present_pages += zone->present_pages;
2533 /*
2534 * A special case here:
2535 *
2536 * balance_pgdat() skips over all_unreclaimable after
2537 * DEF_PRIORITY. Effectively, it considers them balanced so
2538 * they must be considered balanced here as well!
2539 */
2540 if (zone->all_unreclaimable) {
2541 balanced_pages += zone->present_pages;
2542 continue;
2543 }
2545 if (zone_balanced(zone, order, 0, i))
2546 balanced_pages += zone->present_pages;
2547 else if (!order)
2548 return false;
2549 }
2551 if (order)
2552 return balanced_pages >= (present_pages >> 2);
2553 else
2554 return true;
2555 }
2557 /*
2558 * Prepare kswapd for sleeping. This verifies that there are no processes
2559 * waiting in throttle_direct_reclaim() and that watermarks have been met.
2560 *
2561 * Returns true if kswapd is ready to sleep
2562 */
2563 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, long remaining,
2564 int classzone_idx)
2565 {
2566 /* If a direct reclaimer woke kswapd within HZ/10, it's premature */
2567 if (remaining)
2568 return false;
2570 /*
2571 * There is a potential race between when kswapd checks its watermarks
2572 * and a process gets throttled. There is also a potential race if
2573 * processes get throttled, kswapd wakes, a large process exits therby
2574 * balancing the zones that causes kswapd to miss a wakeup. If kswapd
2575 * is going to sleep, no process should be sleeping on pfmemalloc_wait
2576 * so wake them now if necessary. If necessary, processes will wake
2577 * kswapd and get throttled again
2578 */
2579 if (waitqueue_active(&pgdat->pfmemalloc_wait)) {
2580 wake_up(&pgdat->pfmemalloc_wait);
2581 return false;
2582 }
2584 return pgdat_balanced(pgdat, order, classzone_idx);
2585 }
2587 /*
2588 * For kswapd, balance_pgdat() will work across all this node's zones until
2589 * they are all at high_wmark_pages(zone).
2590 *
2591 * Returns the final order kswapd was reclaiming at
2592 *
2593 * There is special handling here for zones which are full of pinned pages.
2594 * This can happen if the pages are all mlocked, or if they are all used by
2595 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
2596 * What we do is to detect the case where all pages in the zone have been
2597 * scanned twice and there has been zero successful reclaim. Mark the zone as
2598 * dead and from now on, only perform a short scan. Basically we're polling
2599 * the zone for when the problem goes away.
2600 *
2601 * kswapd scans the zones in the highmem->normal->dma direction. It skips
2602 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
2603 * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
2604 * lower zones regardless of the number of free pages in the lower zones. This
2605 * interoperates with the page allocator fallback scheme to ensure that aging
2606 * of pages is balanced across the zones.
2607 */
2608 static unsigned long balance_pgdat(pg_data_t *pgdat, int order,
2609 int *classzone_idx)
2610 {
2611 struct zone *unbalanced_zone;
2612 int i;
2613 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
2614 unsigned long total_scanned;
2615 struct reclaim_state *reclaim_state = current->reclaim_state;
2616 unsigned long nr_soft_reclaimed;
2617 unsigned long nr_soft_scanned;
2618 struct scan_control sc = {
2619 .gfp_mask = GFP_KERNEL,
2620 .may_unmap = 1,
2621 .may_swap = 1,
2622 /*
2623 * kswapd doesn't want to be bailed out while reclaim. because
2624 * we want to put equal scanning pressure on each zone.
2625 */
2626 .nr_to_reclaim = ULONG_MAX,
2627 .order = order,
2628 .target_mem_cgroup = NULL,
2629 };
2630 struct shrink_control shrink = {
2631 .gfp_mask = sc.gfp_mask,
2632 };
2633 loop_again:
2634 total_scanned = 0;
2635 sc.priority = DEF_PRIORITY;
2636 sc.nr_reclaimed = 0;
2637 sc.may_writepage = !laptop_mode;
2638 count_vm_event(PAGEOUTRUN);
2640 do {
2641 unsigned long lru_pages = 0;
2642 int has_under_min_watermark_zone = 0;
2644 unbalanced_zone = NULL;
2646 /*
2647 * Scan in the highmem->dma direction for the highest
2648 * zone which needs scanning
2649 */
2650 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
2651 struct zone *zone = pgdat->node_zones + i;
2653 if (!populated_zone(zone))
2654 continue;
2656 if (zone->all_unreclaimable &&
2657 sc.priority != DEF_PRIORITY)
2658 continue;
2660 /*
2661 * Do some background aging of the anon list, to give
2662 * pages a chance to be referenced before reclaiming.
2663 */
2664 age_active_anon(zone, &sc);
2666 /*
2667 * If the number of buffer_heads in the machine
2668 * exceeds the maximum allowed level and this node
2669 * has a highmem zone, force kswapd to reclaim from
2670 * it to relieve lowmem pressure.
2671 */
2672 if (buffer_heads_over_limit && is_highmem_idx(i)) {
2673 end_zone = i;
2674 break;
2675 }
2677 if (!zone_balanced(zone, order, 0, 0)) {
2678 end_zone = i;
2679 break;
2680 } else {
2681 /* If balanced, clear the congested flag */
2682 zone_clear_flag(zone, ZONE_CONGESTED);
2683 }
2684 }
2685 if (i < 0)
2686 goto out;
2688 for (i = 0; i <= end_zone; i++) {
2689 struct zone *zone = pgdat->node_zones + i;
2691 lru_pages += zone_reclaimable_pages(zone);
2692 }
2694 /*
2695 * Now scan the zone in the dma->highmem direction, stopping
2696 * at the last zone which needs scanning.
2697 *
2698 * We do this because the page allocator works in the opposite
2699 * direction. This prevents the page allocator from allocating
2700 * pages behind kswapd's direction of progress, which would
2701 * cause too much scanning of the lower zones.
2702 */
2703 for (i = 0; i <= end_zone; i++) {
2704 struct zone *zone = pgdat->node_zones + i;
2705 int nr_slab, testorder;
2706 unsigned long balance_gap;
2708 if (!populated_zone(zone))
2709 continue;
2711 if (zone->all_unreclaimable &&
2712 sc.priority != DEF_PRIORITY)
2713 continue;
2715 sc.nr_scanned = 0;
2717 nr_soft_scanned = 0;
2718 /*
2719 * Call soft limit reclaim before calling shrink_zone.
2720 */
2721 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
2722 order, sc.gfp_mask,
2723 &nr_soft_scanned);
2724 sc.nr_reclaimed += nr_soft_reclaimed;
2725 total_scanned += nr_soft_scanned;
2727 /*
2728 * We put equal pressure on every zone, unless
2729 * one zone has way too many pages free
2730 * already. The "too many pages" is defined
2731 * as the high wmark plus a "gap" where the
2732 * gap is either the low watermark or 1%
2733 * of the zone, whichever is smaller.
2734 */
2735 balance_gap = min(low_wmark_pages(zone),
2736 (zone->present_pages +
2737 KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
2738 KSWAPD_ZONE_BALANCE_GAP_RATIO);
2739 /*
2740 * Kswapd reclaims only single pages with compaction
2741 * enabled. Trying too hard to reclaim until contiguous
2742 * free pages have become available can hurt performance
2743 * by evicting too much useful data from memory.
2744 * Do not reclaim more than needed for compaction.
2745 */
2746 testorder = order;
2747 if (IS_ENABLED(CONFIG_COMPACTION) && order &&
2748 compaction_suitable(zone, order) !=
2749 COMPACT_SKIPPED)
2750 testorder = 0;
2752 if ((buffer_heads_over_limit && is_highmem_idx(i)) ||
2753 !zone_balanced(zone, testorder,
2754 balance_gap, end_zone)) {
2755 shrink_zone(zone, &sc);
2757 reclaim_state->reclaimed_slab = 0;
2758 nr_slab = shrink_slab(&shrink, sc.nr_scanned, lru_pages);
2759 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
2760 total_scanned += sc.nr_scanned;
2762 if (nr_slab == 0 && !zone_reclaimable(zone))
2763 zone->all_unreclaimable = 1;
2764 }
2766 /*
2767 * If we've done a decent amount of scanning and
2768 * the reclaim ratio is low, start doing writepage
2769 * even in laptop mode
2770 */
2771 if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
2772 total_scanned > sc.nr_reclaimed + sc.nr_reclaimed / 2)
2773 sc.may_writepage = 1;
2775 if (zone->all_unreclaimable) {
2776 if (end_zone && end_zone == i)
2777 end_zone--;
2778 continue;
2779 }
2781 if (!zone_balanced(zone, testorder, 0, end_zone)) {
2782 unbalanced_zone = zone;
2783 /*
2784 * We are still under min water mark. This
2785 * means that we have a GFP_ATOMIC allocation
2786 * failure risk. Hurry up!
2787 */
2788 if (!zone_watermark_ok_safe(zone, order,
2789 min_wmark_pages(zone), end_zone, 0))
2790 has_under_min_watermark_zone = 1;
2791 } else {
2792 /*
2793 * If a zone reaches its high watermark,
2794 * consider it to be no longer congested. It's
2795 * possible there are dirty pages backed by
2796 * congested BDIs but as pressure is relieved,
2797 * speculatively avoid congestion waits
2798 */
2799 zone_clear_flag(zone, ZONE_CONGESTED);
2800 }
2802 }
2804 /*
2805 * If the low watermark is met there is no need for processes
2806 * to be throttled on pfmemalloc_wait as they should not be
2807 * able to safely make forward progress. Wake them
2808 */
2809 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
2810 pfmemalloc_watermark_ok(pgdat))
2811 wake_up(&pgdat->pfmemalloc_wait);
2813 if (pgdat_balanced(pgdat, order, *classzone_idx))
2814 break; /* kswapd: all done */
2815 /*
2816 * OK, kswapd is getting into trouble. Take a nap, then take
2817 * another pass across the zones.
2818 */
2819 if (total_scanned && (sc.priority < DEF_PRIORITY - 2)) {
2820 if (has_under_min_watermark_zone)
2821 count_vm_event(KSWAPD_SKIP_CONGESTION_WAIT);
2822 else if (unbalanced_zone)
2823 wait_iff_congested(unbalanced_zone, BLK_RW_ASYNC, HZ/10);
2824 }
2826 /*
2827 * We do this so kswapd doesn't build up large priorities for
2828 * example when it is freeing in parallel with allocators. It
2829 * matches the direct reclaim path behaviour in terms of impact
2830 * on zone->*_priority.
2831 */
2832 if (sc.nr_reclaimed >= SWAP_CLUSTER_MAX)
2833 break;
2834 } while (--sc.priority >= 0);
2835 out:
2837 if (!pgdat_balanced(pgdat, order, *classzone_idx)) {
2838 cond_resched();
2840 try_to_freeze();
2842 /*
2843 * Fragmentation may mean that the system cannot be
2844 * rebalanced for high-order allocations in all zones.
2845 * At this point, if nr_reclaimed < SWAP_CLUSTER_MAX,
2846 * it means the zones have been fully scanned and are still
2847 * not balanced. For high-order allocations, there is
2848 * little point trying all over again as kswapd may
2849 * infinite loop.
2850 *
2851 * Instead, recheck all watermarks at order-0 as they
2852 * are the most important. If watermarks are ok, kswapd will go
2853 * back to sleep. High-order users can still perform direct
2854 * reclaim if they wish.
2855 */
2856 if (sc.nr_reclaimed < SWAP_CLUSTER_MAX)
2857 order = sc.order = 0;
2859 goto loop_again;
2860 }
2862 /*
2863 * If kswapd was reclaiming at a higher order, it has the option of
2864 * sleeping without all zones being balanced. Before it does, it must
2865 * ensure that the watermarks for order-0 on *all* zones are met and
2866 * that the congestion flags are cleared. The congestion flag must
2867 * be cleared as kswapd is the only mechanism that clears the flag
2868 * and it is potentially going to sleep here.
2869 */
2870 if (order) {
2871 int zones_need_compaction = 1;
2873 for (i = 0; i <= end_zone; i++) {
2874 struct zone *zone = pgdat->node_zones + i;
2876 if (!populated_zone(zone))
2877 continue;
2879 /* Check if the memory needs to be defragmented. */
2880 if (zone_watermark_ok(zone, order,
2881 low_wmark_pages(zone), *classzone_idx, 0))
2882 zones_need_compaction = 0;
2883 }
2885 if (zones_need_compaction)
2886 compact_pgdat(pgdat, order);
2887 }
2889 /*
2890 * Return the order we were reclaiming at so prepare_kswapd_sleep()
2891 * makes a decision on the order we were last reclaiming at. However,
2892 * if another caller entered the allocator slow path while kswapd
2893 * was awake, order will remain at the higher level
2894 */
2895 *classzone_idx = end_zone;
2896 return order;
2897 }
2899 static void kswapd_try_to_sleep(pg_data_t *pgdat, int order, int classzone_idx)
2900 {
2901 long remaining = 0;
2902 DEFINE_WAIT(wait);
2904 if (freezing(current) || kthread_should_stop())
2905 return;
2907 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
2909 /* Try to sleep for a short interval */
2910 if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
2911 remaining = schedule_timeout(HZ/10);
2912 finish_wait(&pgdat->kswapd_wait, &wait);
2913 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
2914 }
2916 /*
2917 * After a short sleep, check if it was a premature sleep. If not, then
2918 * go fully to sleep until explicitly woken up.
2919 */
2920 if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
2921 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
2923 /*
2924 * vmstat counters are not perfectly accurate and the estimated
2925 * value for counters such as NR_FREE_PAGES can deviate from the
2926 * true value by nr_online_cpus * threshold. To avoid the zone
2927 * watermarks being breached while under pressure, we reduce the
2928 * per-cpu vmstat threshold while kswapd is awake and restore
2929 * them before going back to sleep.
2930 */
2931 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
2933 /*
2934 * Compaction records what page blocks it recently failed to
2935 * isolate pages from and skips them in the future scanning.
2936 * When kswapd is going to sleep, it is reasonable to assume
2937 * that pages and compaction may succeed so reset the cache.
2938 */
2939 reset_isolation_suitable(pgdat);
2941 if (!kthread_should_stop())
2942 schedule();
2944 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
2945 } else {
2946 if (remaining)
2947 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
2948 else
2949 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
2950 }
2951 finish_wait(&pgdat->kswapd_wait, &wait);
2952 }
2954 /*
2955 * The background pageout daemon, started as a kernel thread
2956 * from the init process.
2957 *
2958 * This basically trickles out pages so that we have _some_
2959 * free memory available even if there is no other activity
2960 * that frees anything up. This is needed for things like routing
2961 * etc, where we otherwise might have all activity going on in
2962 * asynchronous contexts that cannot page things out.
2963 *
2964 * If there are applications that are active memory-allocators
2965 * (most normal use), this basically shouldn't matter.
2966 */
2967 static int kswapd(void *p)
2968 {
2969 unsigned long order, new_order;
2970 unsigned balanced_order;
2971 int classzone_idx, new_classzone_idx;
2972 int balanced_classzone_idx;
2973 pg_data_t *pgdat = (pg_data_t*)p;
2974 struct task_struct *tsk = current;
2976 struct reclaim_state reclaim_state = {
2977 .reclaimed_slab = 0,
2978 };
2979 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
2981 lockdep_set_current_reclaim_state(GFP_KERNEL);
2983 if (!cpumask_empty(cpumask))
2984 set_cpus_allowed_ptr(tsk, cpumask);
2985 current->reclaim_state = &reclaim_state;
2987 /*
2988 * Tell the memory management that we're a "memory allocator",
2989 * and that if we need more memory we should get access to it
2990 * regardless (see "__alloc_pages()"). "kswapd" should
2991 * never get caught in the normal page freeing logic.
2992 *
2993 * (Kswapd normally doesn't need memory anyway, but sometimes
2994 * you need a small amount of memory in order to be able to
2995 * page out something else, and this flag essentially protects
2996 * us from recursively trying to free more memory as we're
2997 * trying to free the first piece of memory in the first place).
2998 */
2999 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
3000 set_freezable();
3002 order = new_order = 0;
3003 balanced_order = 0;
3004 classzone_idx = new_classzone_idx = pgdat->nr_zones - 1;
3005 balanced_classzone_idx = classzone_idx;
3006 for ( ; ; ) {
3007 bool ret;
3009 /*
3010 * If the last balance_pgdat was unsuccessful it's unlikely a
3011 * new request of a similar or harder type will succeed soon
3012 * so consider going to sleep on the basis we reclaimed at
3013 */
3014 if (balanced_classzone_idx >= new_classzone_idx &&
3015 balanced_order == new_order) {
3016 new_order = pgdat->kswapd_max_order;
3017 new_classzone_idx = pgdat->classzone_idx;
3018 pgdat->kswapd_max_order = 0;
3019 pgdat->classzone_idx = pgdat->nr_zones - 1;
3020 }
3022 if (order < new_order || classzone_idx > new_classzone_idx) {
3023 /*
3024 * Don't sleep if someone wants a larger 'order'
3025 * allocation or has tigher zone constraints
3026 */
3027 order = new_order;
3028 classzone_idx = new_classzone_idx;
3029 } else {
3030 kswapd_try_to_sleep(pgdat, balanced_order,
3031 balanced_classzone_idx);
3032 order = pgdat->kswapd_max_order;
3033 classzone_idx = pgdat->classzone_idx;
3034 new_order = order;
3035 new_classzone_idx = classzone_idx;
3036 pgdat->kswapd_max_order = 0;
3037 pgdat->classzone_idx = pgdat->nr_zones - 1;
3038 }
3040 ret = try_to_freeze();
3041 if (kthread_should_stop())
3042 break;
3044 /*
3045 * We can speed up thawing tasks if we don't call balance_pgdat
3046 * after returning from the refrigerator
3047 */
3048 if (!ret) {
3049 trace_mm_vmscan_kswapd_wake(pgdat->node_id, order);
3050 balanced_classzone_idx = classzone_idx;
3051 balanced_order = balance_pgdat(pgdat, order,
3052 &balanced_classzone_idx);
3053 }
3054 }
3056 current->reclaim_state = NULL;
3057 return 0;
3058 }
3060 /*
3061 * A zone is low on free memory, so wake its kswapd task to service it.
3062 */
3063 void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
3064 {
3065 pg_data_t *pgdat;
3067 if (!populated_zone(zone))
3068 return;
3070 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
3071 return;
3072 pgdat = zone->zone_pgdat;
3073 if (pgdat->kswapd_max_order < order) {
3074 pgdat->kswapd_max_order = order;
3075 pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx);
3076 }
3077 if (!waitqueue_active(&pgdat->kswapd_wait))
3078 return;
3079 if (zone_watermark_ok_safe(zone, order, low_wmark_pages(zone), 0, 0))
3080 return;
3082 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
3083 wake_up_interruptible(&pgdat->kswapd_wait);
3084 }
3086 /*
3087 * The reclaimable count would be mostly accurate.
3088 * The less reclaimable pages may be
3089 * - mlocked pages, which will be moved to unevictable list when encountered
3090 * - mapped pages, which may require several travels to be reclaimed
3091 * - dirty pages, which is not "instantly" reclaimable
3092 */
3093 unsigned long global_reclaimable_pages(void)
3094 {
3095 int nr;
3097 nr = global_page_state(NR_ACTIVE_FILE) +
3098 global_page_state(NR_INACTIVE_FILE);
3100 if (nr_swap_pages > 0)
3101 nr += global_page_state(NR_ACTIVE_ANON) +
3102 global_page_state(NR_INACTIVE_ANON);
3104 return nr;
3105 }
3107 unsigned long zone_reclaimable_pages(struct zone *zone)
3108 {
3109 int nr;
3111 nr = zone_page_state(zone, NR_ACTIVE_FILE) +
3112 zone_page_state(zone, NR_INACTIVE_FILE);
3114 if (nr_swap_pages > 0)
3115 nr += zone_page_state(zone, NR_ACTIVE_ANON) +
3116 zone_page_state(zone, NR_INACTIVE_ANON);
3118 return nr;
3119 }
3121 #ifdef CONFIG_HIBERNATION
3122 /*
3123 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3124 * freed pages.
3125 *
3126 * Rather than trying to age LRUs the aim is to preserve the overall
3127 * LRU order by reclaiming preferentially
3128 * inactive > active > active referenced > active mapped
3129 */
3130 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
3131 {
3132 struct reclaim_state reclaim_state;
3133 struct scan_control sc = {
3134 .gfp_mask = GFP_HIGHUSER_MOVABLE,
3135 .may_swap = 1,
3136 .may_unmap = 1,
3137 .may_writepage = 1,
3138 .nr_to_reclaim = nr_to_reclaim,
3139 .hibernation_mode = 1,
3140 .order = 0,
3141 .priority = DEF_PRIORITY,
3142 };
3143 struct shrink_control shrink = {
3144 .gfp_mask = sc.gfp_mask,
3145 };
3146 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
3147 struct task_struct *p = current;
3148 unsigned long nr_reclaimed;
3150 p->flags |= PF_MEMALLOC;
3151 lockdep_set_current_reclaim_state(sc.gfp_mask);
3152 reclaim_state.reclaimed_slab = 0;
3153 p->reclaim_state = &reclaim_state;
3155 nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
3157 p->reclaim_state = NULL;
3158 lockdep_clear_current_reclaim_state();
3159 p->flags &= ~PF_MEMALLOC;
3161 return nr_reclaimed;
3162 }
3163 #endif /* CONFIG_HIBERNATION */
3165 /* It's optimal to keep kswapds on the same CPUs as their memory, but
3166 not required for correctness. So if the last cpu in a node goes
3167 away, we get changed to run anywhere: as the first one comes back,
3168 restore their cpu bindings. */
3169 static int cpu_callback(struct notifier_block *nfb, unsigned long action,
3170 void *hcpu)
3171 {
3172 int nid;
3174 if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
3175 for_each_node_state(nid, N_MEMORY) {
3176 pg_data_t *pgdat = NODE_DATA(nid);
3177 const struct cpumask *mask;
3179 mask = cpumask_of_node(pgdat->node_id);
3181 if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
3182 /* One of our CPUs online: restore mask */
3183 set_cpus_allowed_ptr(pgdat->kswapd, mask);
3184 }
3185 }
3186 return NOTIFY_OK;
3187 }
3189 /*
3190 * This kswapd start function will be called by init and node-hot-add.
3191 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
3192 */
3193 int kswapd_run(int nid)
3194 {
3195 pg_data_t *pgdat = NODE_DATA(nid);
3196 int ret = 0;
3198 if (pgdat->kswapd)
3199 return 0;
3201 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
3202 if (IS_ERR(pgdat->kswapd)) {
3203 /* failure at boot is fatal */
3204 BUG_ON(system_state == SYSTEM_BOOTING);
3205 pgdat->kswapd = NULL;
3206 pr_err("Failed to start kswapd on node %d\n", nid);
3207 ret = PTR_ERR(pgdat->kswapd);
3208 }
3209 return ret;
3210 }
3212 /*
3213 * Called by memory hotplug when all memory in a node is offlined. Caller must
3214 * hold lock_memory_hotplug().
3215 */
3216 void kswapd_stop(int nid)
3217 {
3218 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
3220 if (kswapd) {
3221 kthread_stop(kswapd);
3222 NODE_DATA(nid)->kswapd = NULL;
3223 }
3224 }
3226 static int __init kswapd_init(void)
3227 {
3228 int nid;
3230 swap_setup();
3231 for_each_node_state(nid, N_MEMORY)
3232 kswapd_run(nid);
3233 hotcpu_notifier(cpu_callback, 0);
3234 return 0;
3235 }
3237 module_init(kswapd_init)
3239 #ifdef CONFIG_NUMA
3240 /*
3241 * Zone reclaim mode
3242 *
3243 * If non-zero call zone_reclaim when the number of free pages falls below
3244 * the watermarks.
3245 */
3246 int zone_reclaim_mode __read_mostly;
3248 #define RECLAIM_OFF 0
3249 #define RECLAIM_ZONE (1<<0) /* Run shrink_inactive_list on the zone */
3250 #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
3251 #define RECLAIM_SWAP (1<<2) /* Swap pages out during reclaim */
3253 /*
3254 * Priority for ZONE_RECLAIM. This determines the fraction of pages
3255 * of a node considered for each zone_reclaim. 4 scans 1/16th of
3256 * a zone.
3257 */
3258 #define ZONE_RECLAIM_PRIORITY 4
3260 /*
3261 * Percentage of pages in a zone that must be unmapped for zone_reclaim to
3262 * occur.
3263 */
3264 int sysctl_min_unmapped_ratio = 1;
3266 /*
3267 * If the number of slab pages in a zone grows beyond this percentage then
3268 * slab reclaim needs to occur.
3269 */
3270 int sysctl_min_slab_ratio = 5;
3272 static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
3273 {
3274 unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
3275 unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
3276 zone_page_state(zone, NR_ACTIVE_FILE);
3278 /*
3279 * It's possible for there to be more file mapped pages than
3280 * accounted for by the pages on the file LRU lists because
3281 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
3282 */
3283 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
3284 }
3286 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
3287 static long zone_pagecache_reclaimable(struct zone *zone)
3288 {
3289 long nr_pagecache_reclaimable;
3290 long delta = 0;
3292 /*
3293 * If RECLAIM_SWAP is set, then all file pages are considered
3294 * potentially reclaimable. Otherwise, we have to worry about
3295 * pages like swapcache and zone_unmapped_file_pages() provides
3296 * a better estimate
3297 */
3298 if (zone_reclaim_mode & RECLAIM_SWAP)
3299 nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
3300 else
3301 nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
3303 /* If we can't clean pages, remove dirty pages from consideration */
3304 if (!(zone_reclaim_mode & RECLAIM_WRITE))
3305 delta += zone_page_state(zone, NR_FILE_DIRTY);
3307 /* Watch for any possible underflows due to delta */
3308 if (unlikely(delta > nr_pagecache_reclaimable))
3309 delta = nr_pagecache_reclaimable;
3311 return nr_pagecache_reclaimable - delta;
3312 }
3314 /*
3315 * Try to free up some pages from this zone through reclaim.
3316 */
3317 static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
3318 {
3319 /* Minimum pages needed in order to stay on node */
3320 const unsigned long nr_pages = 1 << order;
3321 struct task_struct *p = current;
3322 struct reclaim_state reclaim_state;
3323 struct scan_control sc = {
3324 .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
3325 .may_unmap = !!(zone_reclaim_mode & RECLAIM_SWAP),
3326 .may_swap = 1,
3327 .nr_to_reclaim = max_t(unsigned long, nr_pages,
3328 SWAP_CLUSTER_MAX),
3329 .gfp_mask = gfp_mask,
3330 .order = order,
3331 .priority = ZONE_RECLAIM_PRIORITY,
3332 };
3333 struct shrink_control shrink = {
3334 .gfp_mask = sc.gfp_mask,
3335 };
3336 unsigned long nr_slab_pages0, nr_slab_pages1;
3338 cond_resched();
3339 /*
3340 * We need to be able to allocate from the reserves for RECLAIM_SWAP
3341 * and we also need to be able to write out pages for RECLAIM_WRITE
3342 * and RECLAIM_SWAP.
3343 */
3344 p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
3345 lockdep_set_current_reclaim_state(gfp_mask);
3346 reclaim_state.reclaimed_slab = 0;
3347 p->reclaim_state = &reclaim_state;
3349 if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
3350 /*
3351 * Free memory by calling shrink zone with increasing
3352 * priorities until we have enough memory freed.
3353 */
3354 do {
3355 shrink_zone(zone, &sc);
3356 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
3357 }
3359 nr_slab_pages0 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
3360 if (nr_slab_pages0 > zone->min_slab_pages) {
3361 /*
3362 * shrink_slab() does not currently allow us to determine how
3363 * many pages were freed in this zone. So we take the current
3364 * number of slab pages and shake the slab until it is reduced
3365 * by the same nr_pages that we used for reclaiming unmapped
3366 * pages.
3367 *
3368 * Note that shrink_slab will free memory on all zones and may
3369 * take a long time.
3370 */
3371 for (;;) {
3372 unsigned long lru_pages = zone_reclaimable_pages(zone);
3374 /* No reclaimable slab or very low memory pressure */
3375 if (!shrink_slab(&shrink, sc.nr_scanned, lru_pages))
3376 break;
3378 /* Freed enough memory */
3379 nr_slab_pages1 = zone_page_state(zone,
3380 NR_SLAB_RECLAIMABLE);
3381 if (nr_slab_pages1 + nr_pages <= nr_slab_pages0)
3382 break;
3383 }
3385 /*
3386 * Update nr_reclaimed by the number of slab pages we
3387 * reclaimed from this zone.
3388 */
3389 nr_slab_pages1 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
3390 if (nr_slab_pages1 < nr_slab_pages0)
3391 sc.nr_reclaimed += nr_slab_pages0 - nr_slab_pages1;
3392 }
3394 p->reclaim_state = NULL;
3395 current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
3396 lockdep_clear_current_reclaim_state();
3397 return sc.nr_reclaimed >= nr_pages;
3398 }
3400 int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
3401 {
3402 int node_id;
3403 int ret;
3405 /*
3406 * Zone reclaim reclaims unmapped file backed pages and
3407 * slab pages if we are over the defined limits.
3408 *
3409 * A small portion of unmapped file backed pages is needed for
3410 * file I/O otherwise pages read by file I/O will be immediately
3411 * thrown out if the zone is overallocated. So we do not reclaim
3412 * if less than a specified percentage of the zone is used by
3413 * unmapped file backed pages.
3414 */
3415 if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
3416 zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
3417 return ZONE_RECLAIM_FULL;
3419 if (zone->all_unreclaimable)
3420 return ZONE_RECLAIM_FULL;
3422 /*
3423 * Do not scan if the allocation should not be delayed.
3424 */
3425 if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
3426 return ZONE_RECLAIM_NOSCAN;
3428 /*
3429 * Only run zone reclaim on the local zone or on zones that do not
3430 * have associated processors. This will favor the local processor
3431 * over remote processors and spread off node memory allocations
3432 * as wide as possible.
3433 */
3434 node_id = zone_to_nid(zone);
3435 if (node_state(node_id, N_CPU) && node_id != numa_node_id())
3436 return ZONE_RECLAIM_NOSCAN;
3438 if (zone_test_and_set_flag(zone, ZONE_RECLAIM_LOCKED))
3439 return ZONE_RECLAIM_NOSCAN;
3441 ret = __zone_reclaim(zone, gfp_mask, order);
3442 zone_clear_flag(zone, ZONE_RECLAIM_LOCKED);
3444 if (!ret)
3445 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
3447 return ret;
3448 }
3449 #endif
3451 /*
3452 * page_evictable - test whether a page is evictable
3453 * @page: the page to test
3454 *
3455 * Test whether page is evictable--i.e., should be placed on active/inactive
3456 * lists vs unevictable list.
3457 *
3458 * Reasons page might not be evictable:
3459 * (1) page's mapping marked unevictable
3460 * (2) page is part of an mlocked VMA
3461 *
3462 */
3463 int page_evictable(struct page *page)
3464 {
3465 return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3466 }
3468 #ifdef CONFIG_SHMEM
3469 /**
3470 * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
3471 * @pages: array of pages to check
3472 * @nr_pages: number of pages to check
3473 *
3474 * Checks pages for evictability and moves them to the appropriate lru list.
3475 *
3476 * This function is only used for SysV IPC SHM_UNLOCK.
3477 */
3478 void check_move_unevictable_pages(struct page **pages, int nr_pages)
3479 {
3480 struct lruvec *lruvec;
3481 struct zone *zone = NULL;
3482 int pgscanned = 0;
3483 int pgrescued = 0;
3484 int i;
3486 for (i = 0; i < nr_pages; i++) {
3487 struct page *page = pages[i];
3488 struct zone *pagezone;
3490 pgscanned++;
3491 pagezone = page_zone(page);
3492 if (pagezone != zone) {
3493 if (zone)
3494 spin_unlock_irq(&zone->lru_lock);
3495 zone = pagezone;
3496 spin_lock_irq(&zone->lru_lock);
3497 }
3498 lruvec = mem_cgroup_page_lruvec(page, zone);
3500 if (!PageLRU(page) || !PageUnevictable(page))
3501 continue;
3503 if (page_evictable(page)) {
3504 enum lru_list lru = page_lru_base_type(page);
3506 VM_BUG_ON(PageActive(page));
3507 ClearPageUnevictable(page);
3508 del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3509 add_page_to_lru_list(page, lruvec, lru);
3510 pgrescued++;
3511 }
3512 }
3514 if (zone) {
3515 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
3516 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
3517 spin_unlock_irq(&zone->lru_lock);
3518 }
3519 }
3520 #endif /* CONFIG_SHMEM */
3522 static void warn_scan_unevictable_pages(void)
3523 {
3524 printk_once(KERN_WARNING
3525 "%s: The scan_unevictable_pages sysctl/node-interface has been "
3526 "disabled for lack of a legitimate use case. If you have "
3527 "one, please send an email to linux-mm@kvack.org.\n",
3528 current->comm);
3529 }
3531 /*
3532 * scan_unevictable_pages [vm] sysctl handler. On demand re-scan of
3533 * all nodes' unevictable lists for evictable pages
3534 */
3535 unsigned long scan_unevictable_pages;
3537 int scan_unevictable_handler(struct ctl_table *table, int write,
3538 void __user *buffer,
3539 size_t *length, loff_t *ppos)
3540 {
3541 warn_scan_unevictable_pages();
3542 proc_doulongvec_minmax(table, write, buffer, length, ppos);
3543 scan_unevictable_pages = 0;
3544 return 0;
3545 }
3547 #ifdef CONFIG_NUMA
3548 /*
3549 * per node 'scan_unevictable_pages' attribute. On demand re-scan of
3550 * a specified node's per zone unevictable lists for evictable pages.
3551 */
3553 static ssize_t read_scan_unevictable_node(struct device *dev,
3554 struct device_attribute *attr,
3555 char *buf)
3556 {
3557 warn_scan_unevictable_pages();
3558 return sprintf(buf, "0\n"); /* always zero; should fit... */
3559 }
3561 static ssize_t write_scan_unevictable_node(struct device *dev,
3562 struct device_attribute *attr,
3563 const char *buf, size_t count)
3564 {
3565 warn_scan_unevictable_pages();
3566 return 1;
3567 }
3570 static DEVICE_ATTR(scan_unevictable_pages, S_IRUGO | S_IWUSR,
3571 read_scan_unevictable_node,
3572 write_scan_unevictable_node);
3574 int scan_unevictable_register_node(struct node *node)
3575 {
3576 return device_create_file(&node->dev, &dev_attr_scan_unevictable_pages);
3577 }
3579 void scan_unevictable_unregister_node(struct node *node)
3580 {
3581 device_remove_file(&node->dev, &dev_attr_scan_unevictable_pages);
3582 }
3583 #endif