1 // SPDX-License-Identifier: GPL-2.0
5 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
7 * Swap reorganised 29.12.95, Stephen Tweedie.
8 * kswapd added: 7.1.96 sct
9 * Removed kswapd_ctl limits, and swap out as many pages as needed
10 * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
11 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
12 * Multiqueue VM started 5.8.00, Rik van Riel.
15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
18 #include <linux/sched/mm.h>
19 #include <linux/module.h>
20 #include <linux/gfp.h>
21 #include <linux/kernel_stat.h>
22 #include <linux/swap.h>
23 #include <linux/pagemap.h>
24 #include <linux/init.h>
25 #include <linux/highmem.h>
26 #include <linux/vmpressure.h>
27 #include <linux/vmstat.h>
28 #include <linux/file.h>
29 #include <linux/writeback.h>
30 #include <linux/blkdev.h>
31 #include <linux/buffer_head.h> /* for try_to_release_page(),
32 buffer_heads_over_limit */
33 #include <linux/mm_inline.h>
34 #include <linux/backing-dev.h>
35 #include <linux/rmap.h>
36 #include <linux/topology.h>
37 #include <linux/cpu.h>
38 #include <linux/cpuset.h>
39 #include <linux/compaction.h>
40 #include <linux/notifier.h>
41 #include <linux/rwsem.h>
42 #include <linux/delay.h>
43 #include <linux/kthread.h>
44 #include <linux/freezer.h>
45 #include <linux/memcontrol.h>
46 #include <linux/delayacct.h>
47 #include <linux/sysctl.h>
48 #include <linux/oom.h>
49 #include <linux/pagevec.h>
50 #include <linux/prefetch.h>
51 #include <linux/printk.h>
52 #include <linux/dax.h>
53 #include <linux/psi.h>
55 #include <asm/tlbflush.h>
56 #include <asm/div64.h>
58 #include <linux/swapops.h>
59 #include <linux/balloon_compaction.h>
63 #define CREATE_TRACE_POINTS
64 #include <trace/events/vmscan.h>
67 /* How many pages shrink_list() should reclaim */
68 unsigned long nr_to_reclaim;
71 * Nodemask of nodes allowed by the caller. If NULL, all nodes
77 * The memory cgroup that hit its limit and as a result is the
78 * primary target of this reclaim invocation.
80 struct mem_cgroup *target_mem_cgroup;
82 /* Can active pages be deactivated as part of reclaim? */
83 #define DEACTIVATE_ANON 1
84 #define DEACTIVATE_FILE 2
85 unsigned int may_deactivate:2;
86 unsigned int force_deactivate:1;
87 unsigned int skipped_deactivate:1;
89 /* Writepage batching in laptop mode; RECLAIM_WRITE */
90 unsigned int may_writepage:1;
92 /* Can mapped pages be reclaimed? */
93 unsigned int may_unmap:1;
95 /* Can pages be swapped as part of reclaim? */
96 unsigned int may_swap:1;
99 * Cgroups are not reclaimed below their configured memory.low,
100 * unless we threaten to OOM. If any cgroups are skipped due to
101 * memory.low and nothing was reclaimed, go back for memory.low.
103 unsigned int memcg_low_reclaim:1;
104 unsigned int memcg_low_skipped:1;
106 unsigned int hibernation_mode:1;
108 /* One of the zones is ready for compaction */
109 unsigned int compaction_ready:1;
111 /* There is easily reclaimable cold cache in the current node */
112 unsigned int cache_trim_mode:1;
114 /* The file pages on the current node are dangerously low */
115 unsigned int file_is_tiny:1;
117 /* Allocation order */
120 /* Scan (total_size >> priority) pages at once */
123 /* The highest zone to isolate pages for reclaim from */
126 /* This context's GFP mask */
129 /* Incremented by the number of inactive pages that were scanned */
130 unsigned long nr_scanned;
132 /* Number of pages freed so far during a call to shrink_zones() */
133 unsigned long nr_reclaimed;
137 unsigned int unqueued_dirty;
138 unsigned int congested;
139 unsigned int writeback;
140 unsigned int immediate;
141 unsigned int file_taken;
145 /* for recording the reclaimed slab by now */
146 struct reclaim_state reclaim_state;
149 #ifdef ARCH_HAS_PREFETCH
150 #define prefetch_prev_lru_page(_page, _base, _field) \
152 if ((_page)->lru.prev != _base) { \
155 prev = lru_to_page(&(_page->lru)); \
156 prefetch(&prev->_field); \
160 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
163 #ifdef ARCH_HAS_PREFETCHW
164 #define prefetchw_prev_lru_page(_page, _base, _field) \
166 if ((_page)->lru.prev != _base) { \
169 prev = lru_to_page(&(_page->lru)); \
170 prefetchw(&prev->_field); \
174 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
178 * From 0 .. 100. Higher means more swappy.
180 int vm_swappiness = 60;
182 * The total number of pages which are beyond the high watermark within all
185 unsigned long vm_total_pages;
187 static void set_task_reclaim_state(struct task_struct *task,
188 struct reclaim_state *rs)
190 /* Check for an overwrite */
191 WARN_ON_ONCE(rs && task->reclaim_state);
193 /* Check for the nulling of an already-nulled member */
194 WARN_ON_ONCE(!rs && !task->reclaim_state);
196 task->reclaim_state = rs;
199 static LIST_HEAD(shrinker_list);
200 static DECLARE_RWSEM(shrinker_rwsem);
204 * We allow subsystems to populate their shrinker-related
205 * LRU lists before register_shrinker_prepared() is called
206 * for the shrinker, since we don't want to impose
207 * restrictions on their internal registration order.
208 * In this case shrink_slab_memcg() may find corresponding
209 * bit is set in the shrinkers map.
211 * This value is used by the function to detect registering
212 * shrinkers and to skip do_shrink_slab() calls for them.
214 #define SHRINKER_REGISTERING ((struct shrinker *)~0UL)
216 static DEFINE_IDR(shrinker_idr);
217 static int shrinker_nr_max;
219 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
221 int id, ret = -ENOMEM;
223 down_write(&shrinker_rwsem);
224 /* This may call shrinker, so it must use down_read_trylock() */
225 id = idr_alloc(&shrinker_idr, SHRINKER_REGISTERING, 0, 0, GFP_KERNEL);
229 if (id >= shrinker_nr_max) {
230 if (memcg_expand_shrinker_maps(id)) {
231 idr_remove(&shrinker_idr, id);
235 shrinker_nr_max = id + 1;
240 up_write(&shrinker_rwsem);
244 static void unregister_memcg_shrinker(struct shrinker *shrinker)
246 int id = shrinker->id;
250 down_write(&shrinker_rwsem);
251 idr_remove(&shrinker_idr, id);
252 up_write(&shrinker_rwsem);
255 static bool cgroup_reclaim(struct scan_control *sc)
257 return sc->target_mem_cgroup;
261 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
262 * @sc: scan_control in question
264 * The normal page dirty throttling mechanism in balance_dirty_pages() is
265 * completely broken with the legacy memcg and direct stalling in
266 * shrink_page_list() is used for throttling instead, which lacks all the
267 * niceties such as fairness, adaptive pausing, bandwidth proportional
268 * allocation and configurability.
270 * This function tests whether the vmscan currently in progress can assume
271 * that the normal dirty throttling mechanism is operational.
273 static bool writeback_throttling_sane(struct scan_control *sc)
275 if (!cgroup_reclaim(sc))
277 #ifdef CONFIG_CGROUP_WRITEBACK
278 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
284 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
289 static void unregister_memcg_shrinker(struct shrinker *shrinker)
293 static bool cgroup_reclaim(struct scan_control *sc)
298 static bool writeback_throttling_sane(struct scan_control *sc)
305 * This misses isolated pages which are not accounted for to save counters.
306 * As the data only determines if reclaim or compaction continues, it is
307 * not expected that isolated pages will be a dominating factor.
309 unsigned long zone_reclaimable_pages(struct zone *zone)
313 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
314 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
315 if (get_nr_swap_pages() > 0)
316 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
317 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
323 * lruvec_lru_size - Returns the number of pages on the given LRU list.
324 * @lruvec: lru vector
326 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
328 unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, int zone_idx)
330 unsigned long size = 0;
333 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
334 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
336 if (!managed_zone(zone))
339 if (!mem_cgroup_disabled())
340 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
342 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
348 * Add a shrinker callback to be called from the vm.
350 int prealloc_shrinker(struct shrinker *shrinker)
352 unsigned int size = sizeof(*shrinker->nr_deferred);
354 if (shrinker->flags & SHRINKER_NUMA_AWARE)
357 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
358 if (!shrinker->nr_deferred)
361 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
362 if (prealloc_memcg_shrinker(shrinker))
369 kfree(shrinker->nr_deferred);
370 shrinker->nr_deferred = NULL;
374 void free_prealloced_shrinker(struct shrinker *shrinker)
376 if (!shrinker->nr_deferred)
379 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
380 unregister_memcg_shrinker(shrinker);
382 kfree(shrinker->nr_deferred);
383 shrinker->nr_deferred = NULL;
386 void register_shrinker_prepared(struct shrinker *shrinker)
388 down_write(&shrinker_rwsem);
389 list_add_tail(&shrinker->list, &shrinker_list);
391 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
392 idr_replace(&shrinker_idr, shrinker, shrinker->id);
394 up_write(&shrinker_rwsem);
397 int register_shrinker(struct shrinker *shrinker)
399 int err = prealloc_shrinker(shrinker);
403 register_shrinker_prepared(shrinker);
406 EXPORT_SYMBOL(register_shrinker);
411 void unregister_shrinker(struct shrinker *shrinker)
413 if (!shrinker->nr_deferred)
415 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
416 unregister_memcg_shrinker(shrinker);
417 down_write(&shrinker_rwsem);
418 list_del(&shrinker->list);
419 up_write(&shrinker_rwsem);
420 kfree(shrinker->nr_deferred);
421 shrinker->nr_deferred = NULL;
423 EXPORT_SYMBOL(unregister_shrinker);
425 #define SHRINK_BATCH 128
427 static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
428 struct shrinker *shrinker, int priority)
430 unsigned long freed = 0;
431 unsigned long long delta;
436 int nid = shrinkctl->nid;
437 long batch_size = shrinker->batch ? shrinker->batch
439 long scanned = 0, next_deferred;
441 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
444 freeable = shrinker->count_objects(shrinker, shrinkctl);
445 if (freeable == 0 || freeable == SHRINK_EMPTY)
449 * copy the current shrinker scan count into a local variable
450 * and zero it so that other concurrent shrinker invocations
451 * don't also do this scanning work.
453 nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
456 if (shrinker->seeks) {
457 delta = freeable >> priority;
459 do_div(delta, shrinker->seeks);
462 * These objects don't require any IO to create. Trim
463 * them aggressively under memory pressure to keep
464 * them from causing refetches in the IO caches.
466 delta = freeable / 2;
470 if (total_scan < 0) {
471 pr_err("shrink_slab: %pS negative objects to delete nr=%ld\n",
472 shrinker->scan_objects, total_scan);
473 total_scan = freeable;
476 next_deferred = total_scan;
479 * We need to avoid excessive windup on filesystem shrinkers
480 * due to large numbers of GFP_NOFS allocations causing the
481 * shrinkers to return -1 all the time. This results in a large
482 * nr being built up so when a shrink that can do some work
483 * comes along it empties the entire cache due to nr >>>
484 * freeable. This is bad for sustaining a working set in
487 * Hence only allow the shrinker to scan the entire cache when
488 * a large delta change is calculated directly.
490 if (delta < freeable / 4)
491 total_scan = min(total_scan, freeable / 2);
494 * Avoid risking looping forever due to too large nr value:
495 * never try to free more than twice the estimate number of
498 if (total_scan > freeable * 2)
499 total_scan = freeable * 2;
501 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
502 freeable, delta, total_scan, priority);
505 * Normally, we should not scan less than batch_size objects in one
506 * pass to avoid too frequent shrinker calls, but if the slab has less
507 * than batch_size objects in total and we are really tight on memory,
508 * we will try to reclaim all available objects, otherwise we can end
509 * up failing allocations although there are plenty of reclaimable
510 * objects spread over several slabs with usage less than the
513 * We detect the "tight on memory" situations by looking at the total
514 * number of objects we want to scan (total_scan). If it is greater
515 * than the total number of objects on slab (freeable), we must be
516 * scanning at high prio and therefore should try to reclaim as much as
519 while (total_scan >= batch_size ||
520 total_scan >= freeable) {
522 unsigned long nr_to_scan = min(batch_size, total_scan);
524 shrinkctl->nr_to_scan = nr_to_scan;
525 shrinkctl->nr_scanned = nr_to_scan;
526 ret = shrinker->scan_objects(shrinker, shrinkctl);
527 if (ret == SHRINK_STOP)
531 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
532 total_scan -= shrinkctl->nr_scanned;
533 scanned += shrinkctl->nr_scanned;
538 if (next_deferred >= scanned)
539 next_deferred -= scanned;
543 * move the unused scan count back into the shrinker in a
544 * manner that handles concurrent updates. If we exhausted the
545 * scan, there is no need to do an update.
547 if (next_deferred > 0)
548 new_nr = atomic_long_add_return(next_deferred,
549 &shrinker->nr_deferred[nid]);
551 new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
553 trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
558 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
559 struct mem_cgroup *memcg, int priority)
561 struct memcg_shrinker_map *map;
562 unsigned long ret, freed = 0;
565 if (!mem_cgroup_online(memcg))
568 if (!down_read_trylock(&shrinker_rwsem))
571 map = rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_map,
576 for_each_set_bit(i, map->map, shrinker_nr_max) {
577 struct shrink_control sc = {
578 .gfp_mask = gfp_mask,
582 struct shrinker *shrinker;
584 shrinker = idr_find(&shrinker_idr, i);
585 if (unlikely(!shrinker || shrinker == SHRINKER_REGISTERING)) {
587 clear_bit(i, map->map);
591 /* Call non-slab shrinkers even though kmem is disabled */
592 if (!memcg_kmem_enabled() &&
593 !(shrinker->flags & SHRINKER_NONSLAB))
596 ret = do_shrink_slab(&sc, shrinker, priority);
597 if (ret == SHRINK_EMPTY) {
598 clear_bit(i, map->map);
600 * After the shrinker reported that it had no objects to
601 * free, but before we cleared the corresponding bit in
602 * the memcg shrinker map, a new object might have been
603 * added. To make sure, we have the bit set in this
604 * case, we invoke the shrinker one more time and reset
605 * the bit if it reports that it is not empty anymore.
606 * The memory barrier here pairs with the barrier in
607 * memcg_set_shrinker_bit():
609 * list_lru_add() shrink_slab_memcg()
610 * list_add_tail() clear_bit()
612 * set_bit() do_shrink_slab()
614 smp_mb__after_atomic();
615 ret = do_shrink_slab(&sc, shrinker, priority);
616 if (ret == SHRINK_EMPTY)
619 memcg_set_shrinker_bit(memcg, nid, i);
623 if (rwsem_is_contended(&shrinker_rwsem)) {
629 up_read(&shrinker_rwsem);
632 #else /* CONFIG_MEMCG */
633 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
634 struct mem_cgroup *memcg, int priority)
638 #endif /* CONFIG_MEMCG */
641 * shrink_slab - shrink slab caches
642 * @gfp_mask: allocation context
643 * @nid: node whose slab caches to target
644 * @memcg: memory cgroup whose slab caches to target
645 * @priority: the reclaim priority
647 * Call the shrink functions to age shrinkable caches.
649 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
650 * unaware shrinkers will receive a node id of 0 instead.
652 * @memcg specifies the memory cgroup to target. Unaware shrinkers
653 * are called only if it is the root cgroup.
655 * @priority is sc->priority, we take the number of objects and >> by priority
656 * in order to get the scan target.
658 * Returns the number of reclaimed slab objects.
660 static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
661 struct mem_cgroup *memcg,
664 unsigned long ret, freed = 0;
665 struct shrinker *shrinker;
668 * The root memcg might be allocated even though memcg is disabled
669 * via "cgroup_disable=memory" boot parameter. This could make
670 * mem_cgroup_is_root() return false, then just run memcg slab
671 * shrink, but skip global shrink. This may result in premature
674 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
675 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
677 if (!down_read_trylock(&shrinker_rwsem))
680 list_for_each_entry(shrinker, &shrinker_list, list) {
681 struct shrink_control sc = {
682 .gfp_mask = gfp_mask,
687 ret = do_shrink_slab(&sc, shrinker, priority);
688 if (ret == SHRINK_EMPTY)
692 * Bail out if someone want to register a new shrinker to
693 * prevent the regsitration from being stalled for long periods
694 * by parallel ongoing shrinking.
696 if (rwsem_is_contended(&shrinker_rwsem)) {
702 up_read(&shrinker_rwsem);
708 void drop_slab_node(int nid)
713 struct mem_cgroup *memcg = NULL;
716 memcg = mem_cgroup_iter(NULL, NULL, NULL);
718 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
719 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
720 } while (freed > 10);
727 for_each_online_node(nid)
731 static inline int is_page_cache_freeable(struct page *page)
734 * A freeable page cache page is referenced only by the caller
735 * that isolated the page, the page cache and optional buffer
736 * heads at page->private.
738 int page_cache_pins = PageTransHuge(page) && PageSwapCache(page) ?
740 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
743 static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
745 if (current->flags & PF_SWAPWRITE)
747 if (!inode_write_congested(inode))
749 if (inode_to_bdi(inode) == current->backing_dev_info)
755 * We detected a synchronous write error writing a page out. Probably
756 * -ENOSPC. We need to propagate that into the address_space for a subsequent
757 * fsync(), msync() or close().
759 * The tricky part is that after writepage we cannot touch the mapping: nothing
760 * prevents it from being freed up. But we have a ref on the page and once
761 * that page is locked, the mapping is pinned.
763 * We're allowed to run sleeping lock_page() here because we know the caller has
766 static void handle_write_error(struct address_space *mapping,
767 struct page *page, int error)
770 if (page_mapping(page) == mapping)
771 mapping_set_error(mapping, error);
775 /* possible outcome of pageout() */
777 /* failed to write page out, page is locked */
779 /* move page to the active list, page is locked */
781 /* page has been sent to the disk successfully, page is unlocked */
783 /* page is clean and locked */
788 * pageout is called by shrink_page_list() for each dirty page.
789 * Calls ->writepage().
791 static pageout_t pageout(struct page *page, struct address_space *mapping,
792 struct scan_control *sc)
795 * If the page is dirty, only perform writeback if that write
796 * will be non-blocking. To prevent this allocation from being
797 * stalled by pagecache activity. But note that there may be
798 * stalls if we need to run get_block(). We could test
799 * PagePrivate for that.
801 * If this process is currently in __generic_file_write_iter() against
802 * this page's queue, we can perform writeback even if that
805 * If the page is swapcache, write it back even if that would
806 * block, for some throttling. This happens by accident, because
807 * swap_backing_dev_info is bust: it doesn't reflect the
808 * congestion state of the swapdevs. Easy to fix, if needed.
810 if (!is_page_cache_freeable(page))
814 * Some data journaling orphaned pages can have
815 * page->mapping == NULL while being dirty with clean buffers.
817 if (page_has_private(page)) {
818 if (try_to_free_buffers(page)) {
819 ClearPageDirty(page);
820 pr_info("%s: orphaned page\n", __func__);
826 if (mapping->a_ops->writepage == NULL)
827 return PAGE_ACTIVATE;
828 if (!may_write_to_inode(mapping->host, sc))
831 if (clear_page_dirty_for_io(page)) {
833 struct writeback_control wbc = {
834 .sync_mode = WB_SYNC_NONE,
835 .nr_to_write = SWAP_CLUSTER_MAX,
837 .range_end = LLONG_MAX,
841 SetPageReclaim(page);
842 res = mapping->a_ops->writepage(page, &wbc);
844 handle_write_error(mapping, page, res);
845 if (res == AOP_WRITEPAGE_ACTIVATE) {
846 ClearPageReclaim(page);
847 return PAGE_ACTIVATE;
850 if (!PageWriteback(page)) {
851 /* synchronous write or broken a_ops? */
852 ClearPageReclaim(page);
854 trace_mm_vmscan_writepage(page);
855 inc_node_page_state(page, NR_VMSCAN_WRITE);
863 * Same as remove_mapping, but if the page is removed from the mapping, it
864 * gets returned with a refcount of 0.
866 static int __remove_mapping(struct address_space *mapping, struct page *page,
867 bool reclaimed, struct mem_cgroup *target_memcg)
872 BUG_ON(!PageLocked(page));
873 BUG_ON(mapping != page_mapping(page));
875 xa_lock_irqsave(&mapping->i_pages, flags);
877 * The non racy check for a busy page.
879 * Must be careful with the order of the tests. When someone has
880 * a ref to the page, it may be possible that they dirty it then
881 * drop the reference. So if PageDirty is tested before page_count
882 * here, then the following race may occur:
884 * get_user_pages(&page);
885 * [user mapping goes away]
887 * !PageDirty(page) [good]
888 * SetPageDirty(page);
890 * !page_count(page) [good, discard it]
892 * [oops, our write_to data is lost]
894 * Reversing the order of the tests ensures such a situation cannot
895 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
896 * load is not satisfied before that of page->_refcount.
898 * Note that if SetPageDirty is always performed via set_page_dirty,
899 * and thus under the i_pages lock, then this ordering is not required.
901 refcount = 1 + compound_nr(page);
902 if (!page_ref_freeze(page, refcount))
904 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
905 if (unlikely(PageDirty(page))) {
906 page_ref_unfreeze(page, refcount);
910 if (PageSwapCache(page)) {
911 swp_entry_t swap = { .val = page_private(page) };
912 mem_cgroup_swapout(page, swap);
913 __delete_from_swap_cache(page, swap);
914 xa_unlock_irqrestore(&mapping->i_pages, flags);
915 put_swap_page(page, swap);
917 void (*freepage)(struct page *);
920 freepage = mapping->a_ops->freepage;
922 * Remember a shadow entry for reclaimed file cache in
923 * order to detect refaults, thus thrashing, later on.
925 * But don't store shadows in an address space that is
926 * already exiting. This is not just an optizimation,
927 * inode reclaim needs to empty out the radix tree or
928 * the nodes are lost. Don't plant shadows behind its
931 * We also don't store shadows for DAX mappings because the
932 * only page cache pages found in these are zero pages
933 * covering holes, and because we don't want to mix DAX
934 * exceptional entries and shadow exceptional entries in the
935 * same address_space.
937 if (reclaimed && page_is_file_cache(page) &&
938 !mapping_exiting(mapping) && !dax_mapping(mapping))
939 shadow = workingset_eviction(page, target_memcg);
940 __delete_from_page_cache(page, shadow);
941 xa_unlock_irqrestore(&mapping->i_pages, flags);
943 if (freepage != NULL)
950 xa_unlock_irqrestore(&mapping->i_pages, flags);
955 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
956 * someone else has a ref on the page, abort and return 0. If it was
957 * successfully detached, return 1. Assumes the caller has a single ref on
960 int remove_mapping(struct address_space *mapping, struct page *page)
962 if (__remove_mapping(mapping, page, false, NULL)) {
964 * Unfreezing the refcount with 1 rather than 2 effectively
965 * drops the pagecache ref for us without requiring another
968 page_ref_unfreeze(page, 1);
975 * putback_lru_page - put previously isolated page onto appropriate LRU list
976 * @page: page to be put back to appropriate lru list
978 * Add previously isolated @page to appropriate LRU list.
979 * Page may still be unevictable for other reasons.
981 * lru_lock must not be held, interrupts must be enabled.
983 void putback_lru_page(struct page *page)
986 put_page(page); /* drop ref from isolate */
989 enum page_references {
991 PAGEREF_RECLAIM_CLEAN,
996 static enum page_references page_check_references(struct page *page,
997 struct scan_control *sc)
999 int referenced_ptes, referenced_page;
1000 unsigned long vm_flags;
1002 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1004 referenced_page = TestClearPageReferenced(page);
1007 * Mlock lost the isolation race with us. Let try_to_unmap()
1008 * move the page to the unevictable list.
1010 if (vm_flags & VM_LOCKED)
1011 return PAGEREF_RECLAIM;
1013 if (referenced_ptes) {
1014 if (PageSwapBacked(page))
1015 return PAGEREF_ACTIVATE;
1017 * All mapped pages start out with page table
1018 * references from the instantiating fault, so we need
1019 * to look twice if a mapped file page is used more
1022 * Mark it and spare it for another trip around the
1023 * inactive list. Another page table reference will
1024 * lead to its activation.
1026 * Note: the mark is set for activated pages as well
1027 * so that recently deactivated but used pages are
1028 * quickly recovered.
1030 SetPageReferenced(page);
1032 if (referenced_page || referenced_ptes > 1)
1033 return PAGEREF_ACTIVATE;
1036 * Activate file-backed executable pages after first usage.
1038 if (vm_flags & VM_EXEC)
1039 return PAGEREF_ACTIVATE;
1041 return PAGEREF_KEEP;
1044 /* Reclaim if clean, defer dirty pages to writeback */
1045 if (referenced_page && !PageSwapBacked(page))
1046 return PAGEREF_RECLAIM_CLEAN;
1048 return PAGEREF_RECLAIM;
1051 /* Check if a page is dirty or under writeback */
1052 static void page_check_dirty_writeback(struct page *page,
1053 bool *dirty, bool *writeback)
1055 struct address_space *mapping;
1058 * Anonymous pages are not handled by flushers and must be written
1059 * from reclaim context. Do not stall reclaim based on them
1061 if (!page_is_file_cache(page) ||
1062 (PageAnon(page) && !PageSwapBacked(page))) {
1068 /* By default assume that the page flags are accurate */
1069 *dirty = PageDirty(page);
1070 *writeback = PageWriteback(page);
1072 /* Verify dirty/writeback state if the filesystem supports it */
1073 if (!page_has_private(page))
1076 mapping = page_mapping(page);
1077 if (mapping && mapping->a_ops->is_dirty_writeback)
1078 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1082 * shrink_page_list() returns the number of reclaimed pages
1084 static unsigned long shrink_page_list(struct list_head *page_list,
1085 struct pglist_data *pgdat,
1086 struct scan_control *sc,
1087 enum ttu_flags ttu_flags,
1088 struct reclaim_stat *stat,
1089 bool ignore_references)
1091 LIST_HEAD(ret_pages);
1092 LIST_HEAD(free_pages);
1093 unsigned nr_reclaimed = 0;
1094 unsigned pgactivate = 0;
1096 memset(stat, 0, sizeof(*stat));
1099 while (!list_empty(page_list)) {
1100 struct address_space *mapping;
1103 enum page_references references = PAGEREF_RECLAIM;
1104 bool dirty, writeback;
1105 unsigned int nr_pages;
1109 page = lru_to_page(page_list);
1110 list_del(&page->lru);
1112 if (!trylock_page(page))
1115 VM_BUG_ON_PAGE(PageActive(page), page);
1117 nr_pages = compound_nr(page);
1119 /* Account the number of base pages even though THP */
1120 sc->nr_scanned += nr_pages;
1122 if (unlikely(!page_evictable(page)))
1123 goto activate_locked;
1125 if (!sc->may_unmap && page_mapped(page))
1128 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1129 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1132 * The number of dirty pages determines if a node is marked
1133 * reclaim_congested which affects wait_iff_congested. kswapd
1134 * will stall and start writing pages if the tail of the LRU
1135 * is all dirty unqueued pages.
1137 page_check_dirty_writeback(page, &dirty, &writeback);
1138 if (dirty || writeback)
1141 if (dirty && !writeback)
1142 stat->nr_unqueued_dirty++;
1145 * Treat this page as congested if the underlying BDI is or if
1146 * pages are cycling through the LRU so quickly that the
1147 * pages marked for immediate reclaim are making it to the
1148 * end of the LRU a second time.
1150 mapping = page_mapping(page);
1151 if (((dirty || writeback) && mapping &&
1152 inode_write_congested(mapping->host)) ||
1153 (writeback && PageReclaim(page)))
1154 stat->nr_congested++;
1157 * If a page at the tail of the LRU is under writeback, there
1158 * are three cases to consider.
1160 * 1) If reclaim is encountering an excessive number of pages
1161 * under writeback and this page is both under writeback and
1162 * PageReclaim then it indicates that pages are being queued
1163 * for IO but are being recycled through the LRU before the
1164 * IO can complete. Waiting on the page itself risks an
1165 * indefinite stall if it is impossible to writeback the
1166 * page due to IO error or disconnected storage so instead
1167 * note that the LRU is being scanned too quickly and the
1168 * caller can stall after page list has been processed.
1170 * 2) Global or new memcg reclaim encounters a page that is
1171 * not marked for immediate reclaim, or the caller does not
1172 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1173 * not to fs). In this case mark the page for immediate
1174 * reclaim and continue scanning.
1176 * Require may_enter_fs because we would wait on fs, which
1177 * may not have submitted IO yet. And the loop driver might
1178 * enter reclaim, and deadlock if it waits on a page for
1179 * which it is needed to do the write (loop masks off
1180 * __GFP_IO|__GFP_FS for this reason); but more thought
1181 * would probably show more reasons.
1183 * 3) Legacy memcg encounters a page that is already marked
1184 * PageReclaim. memcg does not have any dirty pages
1185 * throttling so we could easily OOM just because too many
1186 * pages are in writeback and there is nothing else to
1187 * reclaim. Wait for the writeback to complete.
1189 * In cases 1) and 2) we activate the pages to get them out of
1190 * the way while we continue scanning for clean pages on the
1191 * inactive list and refilling from the active list. The
1192 * observation here is that waiting for disk writes is more
1193 * expensive than potentially causing reloads down the line.
1194 * Since they're marked for immediate reclaim, they won't put
1195 * memory pressure on the cache working set any longer than it
1196 * takes to write them to disk.
1198 if (PageWriteback(page)) {
1200 if (current_is_kswapd() &&
1201 PageReclaim(page) &&
1202 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1203 stat->nr_immediate++;
1204 goto activate_locked;
1207 } else if (writeback_throttling_sane(sc) ||
1208 !PageReclaim(page) || !may_enter_fs) {
1210 * This is slightly racy - end_page_writeback()
1211 * might have just cleared PageReclaim, then
1212 * setting PageReclaim here end up interpreted
1213 * as PageReadahead - but that does not matter
1214 * enough to care. What we do want is for this
1215 * page to have PageReclaim set next time memcg
1216 * reclaim reaches the tests above, so it will
1217 * then wait_on_page_writeback() to avoid OOM;
1218 * and it's also appropriate in global reclaim.
1220 SetPageReclaim(page);
1221 stat->nr_writeback++;
1222 goto activate_locked;
1227 wait_on_page_writeback(page);
1228 /* then go back and try same page again */
1229 list_add_tail(&page->lru, page_list);
1234 if (!ignore_references)
1235 references = page_check_references(page, sc);
1237 switch (references) {
1238 case PAGEREF_ACTIVATE:
1239 goto activate_locked;
1241 stat->nr_ref_keep += nr_pages;
1243 case PAGEREF_RECLAIM:
1244 case PAGEREF_RECLAIM_CLEAN:
1245 ; /* try to reclaim the page below */
1249 * Anonymous process memory has backing store?
1250 * Try to allocate it some swap space here.
1251 * Lazyfree page could be freed directly
1253 if (PageAnon(page) && PageSwapBacked(page)) {
1254 if (!PageSwapCache(page)) {
1255 if (!(sc->gfp_mask & __GFP_IO))
1257 if (PageTransHuge(page)) {
1258 /* cannot split THP, skip it */
1259 if (!can_split_huge_page(page, NULL))
1260 goto activate_locked;
1262 * Split pages without a PMD map right
1263 * away. Chances are some or all of the
1264 * tail pages can be freed without IO.
1266 if (!compound_mapcount(page) &&
1267 split_huge_page_to_list(page,
1269 goto activate_locked;
1271 if (!add_to_swap(page)) {
1272 if (!PageTransHuge(page))
1273 goto activate_locked_split;
1274 /* Fallback to swap normal pages */
1275 if (split_huge_page_to_list(page,
1277 goto activate_locked;
1278 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1279 count_vm_event(THP_SWPOUT_FALLBACK);
1281 if (!add_to_swap(page))
1282 goto activate_locked_split;
1287 /* Adding to swap updated mapping */
1288 mapping = page_mapping(page);
1290 } else if (unlikely(PageTransHuge(page))) {
1291 /* Split file THP */
1292 if (split_huge_page_to_list(page, page_list))
1297 * THP may get split above, need minus tail pages and update
1298 * nr_pages to avoid accounting tail pages twice.
1300 * The tail pages that are added into swap cache successfully
1303 if ((nr_pages > 1) && !PageTransHuge(page)) {
1304 sc->nr_scanned -= (nr_pages - 1);
1309 * The page is mapped into the page tables of one or more
1310 * processes. Try to unmap it here.
1312 if (page_mapped(page)) {
1313 enum ttu_flags flags = ttu_flags | TTU_BATCH_FLUSH;
1315 if (unlikely(PageTransHuge(page)))
1316 flags |= TTU_SPLIT_HUGE_PMD;
1317 if (!try_to_unmap(page, flags)) {
1318 stat->nr_unmap_fail += nr_pages;
1319 goto activate_locked;
1323 if (PageDirty(page)) {
1325 * Only kswapd can writeback filesystem pages
1326 * to avoid risk of stack overflow. But avoid
1327 * injecting inefficient single-page IO into
1328 * flusher writeback as much as possible: only
1329 * write pages when we've encountered many
1330 * dirty pages, and when we've already scanned
1331 * the rest of the LRU for clean pages and see
1332 * the same dirty pages again (PageReclaim).
1334 if (page_is_file_cache(page) &&
1335 (!current_is_kswapd() || !PageReclaim(page) ||
1336 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
1338 * Immediately reclaim when written back.
1339 * Similar in principal to deactivate_page()
1340 * except we already have the page isolated
1341 * and know it's dirty
1343 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
1344 SetPageReclaim(page);
1346 goto activate_locked;
1349 if (references == PAGEREF_RECLAIM_CLEAN)
1353 if (!sc->may_writepage)
1357 * Page is dirty. Flush the TLB if a writable entry
1358 * potentially exists to avoid CPU writes after IO
1359 * starts and then write it out here.
1361 try_to_unmap_flush_dirty();
1362 switch (pageout(page, mapping, sc)) {
1366 goto activate_locked;
1368 if (PageWriteback(page))
1370 if (PageDirty(page))
1374 * A synchronous write - probably a ramdisk. Go
1375 * ahead and try to reclaim the page.
1377 if (!trylock_page(page))
1379 if (PageDirty(page) || PageWriteback(page))
1381 mapping = page_mapping(page);
1383 ; /* try to free the page below */
1388 * If the page has buffers, try to free the buffer mappings
1389 * associated with this page. If we succeed we try to free
1392 * We do this even if the page is PageDirty().
1393 * try_to_release_page() does not perform I/O, but it is
1394 * possible for a page to have PageDirty set, but it is actually
1395 * clean (all its buffers are clean). This happens if the
1396 * buffers were written out directly, with submit_bh(). ext3
1397 * will do this, as well as the blockdev mapping.
1398 * try_to_release_page() will discover that cleanness and will
1399 * drop the buffers and mark the page clean - it can be freed.
1401 * Rarely, pages can have buffers and no ->mapping. These are
1402 * the pages which were not successfully invalidated in
1403 * truncate_complete_page(). We try to drop those buffers here
1404 * and if that worked, and the page is no longer mapped into
1405 * process address space (page_count == 1) it can be freed.
1406 * Otherwise, leave the page on the LRU so it is swappable.
1408 if (page_has_private(page)) {
1409 if (!try_to_release_page(page, sc->gfp_mask))
1410 goto activate_locked;
1411 if (!mapping && page_count(page) == 1) {
1413 if (put_page_testzero(page))
1417 * rare race with speculative reference.
1418 * the speculative reference will free
1419 * this page shortly, so we may
1420 * increment nr_reclaimed here (and
1421 * leave it off the LRU).
1429 if (PageAnon(page) && !PageSwapBacked(page)) {
1430 /* follow __remove_mapping for reference */
1431 if (!page_ref_freeze(page, 1))
1433 if (PageDirty(page)) {
1434 page_ref_unfreeze(page, 1);
1438 count_vm_event(PGLAZYFREED);
1439 count_memcg_page_event(page, PGLAZYFREED);
1440 } else if (!mapping || !__remove_mapping(mapping, page, true,
1441 sc->target_mem_cgroup))
1447 * THP may get swapped out in a whole, need account
1450 nr_reclaimed += nr_pages;
1453 * Is there need to periodically free_page_list? It would
1454 * appear not as the counts should be low
1456 if (unlikely(PageTransHuge(page)))
1457 (*get_compound_page_dtor(page))(page);
1459 list_add(&page->lru, &free_pages);
1462 activate_locked_split:
1464 * The tail pages that are failed to add into swap cache
1465 * reach here. Fixup nr_scanned and nr_pages.
1468 sc->nr_scanned -= (nr_pages - 1);
1472 /* Not a candidate for swapping, so reclaim swap space. */
1473 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1475 try_to_free_swap(page);
1476 VM_BUG_ON_PAGE(PageActive(page), page);
1477 if (!PageMlocked(page)) {
1478 int type = page_is_file_cache(page);
1479 SetPageActive(page);
1480 stat->nr_activate[type] += nr_pages;
1481 count_memcg_page_event(page, PGACTIVATE);
1486 list_add(&page->lru, &ret_pages);
1487 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
1490 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1492 mem_cgroup_uncharge_list(&free_pages);
1493 try_to_unmap_flush();
1494 free_unref_page_list(&free_pages);
1496 list_splice(&ret_pages, page_list);
1497 count_vm_events(PGACTIVATE, pgactivate);
1499 return nr_reclaimed;
1502 unsigned long reclaim_clean_pages_from_list(struct zone *zone,
1503 struct list_head *page_list)
1505 struct scan_control sc = {
1506 .gfp_mask = GFP_KERNEL,
1507 .priority = DEF_PRIORITY,
1510 struct reclaim_stat dummy_stat;
1512 struct page *page, *next;
1513 LIST_HEAD(clean_pages);
1515 list_for_each_entry_safe(page, next, page_list, lru) {
1516 if (page_is_file_cache(page) && !PageDirty(page) &&
1517 !__PageMovable(page) && !PageUnevictable(page)) {
1518 ClearPageActive(page);
1519 list_move(&page->lru, &clean_pages);
1523 ret = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1524 TTU_IGNORE_ACCESS, &dummy_stat, true);
1525 list_splice(&clean_pages, page_list);
1526 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
1531 * Attempt to remove the specified page from its LRU. Only take this page
1532 * if it is of the appropriate PageActive status. Pages which are being
1533 * freed elsewhere are also ignored.
1535 * page: page to consider
1536 * mode: one of the LRU isolation modes defined above
1538 * returns 0 on success, -ve errno on failure.
1540 int __isolate_lru_page(struct page *page, isolate_mode_t mode)
1544 /* Only take pages on the LRU. */
1548 /* Compaction should not handle unevictable pages but CMA can do so */
1549 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1555 * To minimise LRU disruption, the caller can indicate that it only
1556 * wants to isolate pages it will be able to operate on without
1557 * blocking - clean pages for the most part.
1559 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1560 * that it is possible to migrate without blocking
1562 if (mode & ISOLATE_ASYNC_MIGRATE) {
1563 /* All the caller can do on PageWriteback is block */
1564 if (PageWriteback(page))
1567 if (PageDirty(page)) {
1568 struct address_space *mapping;
1572 * Only pages without mappings or that have a
1573 * ->migratepage callback are possible to migrate
1574 * without blocking. However, we can be racing with
1575 * truncation so it's necessary to lock the page
1576 * to stabilise the mapping as truncation holds
1577 * the page lock until after the page is removed
1578 * from the page cache.
1580 if (!trylock_page(page))
1583 mapping = page_mapping(page);
1584 migrate_dirty = !mapping || mapping->a_ops->migratepage;
1591 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1594 if (likely(get_page_unless_zero(page))) {
1596 * Be careful not to clear PageLRU until after we're
1597 * sure the page is not being freed elsewhere -- the
1598 * page release code relies on it.
1609 * Update LRU sizes after isolating pages. The LRU size updates must
1610 * be complete before mem_cgroup_update_lru_size due to a santity check.
1612 static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1613 enum lru_list lru, unsigned long *nr_zone_taken)
1617 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1618 if (!nr_zone_taken[zid])
1621 __update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1623 mem_cgroup_update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1630 * pgdat->lru_lock is heavily contended. Some of the functions that
1631 * shrink the lists perform better by taking out a batch of pages
1632 * and working on them outside the LRU lock.
1634 * For pagecache intensive workloads, this function is the hottest
1635 * spot in the kernel (apart from copy_*_user functions).
1637 * Appropriate locks must be held before calling this function.
1639 * @nr_to_scan: The number of eligible pages to look through on the list.
1640 * @lruvec: The LRU vector to pull pages from.
1641 * @dst: The temp list to put pages on to.
1642 * @nr_scanned: The number of pages that were scanned.
1643 * @sc: The scan_control struct for this reclaim session
1644 * @mode: One of the LRU isolation modes
1645 * @lru: LRU list id for isolating
1647 * returns how many pages were moved onto *@dst.
1649 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
1650 struct lruvec *lruvec, struct list_head *dst,
1651 unsigned long *nr_scanned, struct scan_control *sc,
1654 struct list_head *src = &lruvec->lists[lru];
1655 unsigned long nr_taken = 0;
1656 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
1657 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
1658 unsigned long skipped = 0;
1659 unsigned long scan, total_scan, nr_pages;
1660 LIST_HEAD(pages_skipped);
1661 isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
1665 while (scan < nr_to_scan && !list_empty(src)) {
1668 page = lru_to_page(src);
1669 prefetchw_prev_lru_page(page, src, flags);
1671 VM_BUG_ON_PAGE(!PageLRU(page), page);
1673 nr_pages = compound_nr(page);
1674 total_scan += nr_pages;
1676 if (page_zonenum(page) > sc->reclaim_idx) {
1677 list_move(&page->lru, &pages_skipped);
1678 nr_skipped[page_zonenum(page)] += nr_pages;
1683 * Do not count skipped pages because that makes the function
1684 * return with no isolated pages if the LRU mostly contains
1685 * ineligible pages. This causes the VM to not reclaim any
1686 * pages, triggering a premature OOM.
1688 * Account all tail pages of THP. This would not cause
1689 * premature OOM since __isolate_lru_page() returns -EBUSY
1690 * only when the page is being freed somewhere else.
1693 switch (__isolate_lru_page(page, mode)) {
1695 nr_taken += nr_pages;
1696 nr_zone_taken[page_zonenum(page)] += nr_pages;
1697 list_move(&page->lru, dst);
1701 /* else it is being freed elsewhere */
1702 list_move(&page->lru, src);
1711 * Splice any skipped pages to the start of the LRU list. Note that
1712 * this disrupts the LRU order when reclaiming for lower zones but
1713 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1714 * scanning would soon rescan the same pages to skip and put the
1715 * system at risk of premature OOM.
1717 if (!list_empty(&pages_skipped)) {
1720 list_splice(&pages_skipped, src);
1721 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1722 if (!nr_skipped[zid])
1725 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
1726 skipped += nr_skipped[zid];
1729 *nr_scanned = total_scan;
1730 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1731 total_scan, skipped, nr_taken, mode, lru);
1732 update_lru_sizes(lruvec, lru, nr_zone_taken);
1737 * isolate_lru_page - tries to isolate a page from its LRU list
1738 * @page: page to isolate from its LRU list
1740 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
1741 * vmstat statistic corresponding to whatever LRU list the page was on.
1743 * Returns 0 if the page was removed from an LRU list.
1744 * Returns -EBUSY if the page was not on an LRU list.
1746 * The returned page will have PageLRU() cleared. If it was found on
1747 * the active list, it will have PageActive set. If it was found on
1748 * the unevictable list, it will have the PageUnevictable bit set. That flag
1749 * may need to be cleared by the caller before letting the page go.
1751 * The vmstat statistic corresponding to the list on which the page was
1752 * found will be decremented.
1756 * (1) Must be called with an elevated refcount on the page. This is a
1757 * fundamentnal difference from isolate_lru_pages (which is called
1758 * without a stable reference).
1759 * (2) the lru_lock must not be held.
1760 * (3) interrupts must be enabled.
1762 int isolate_lru_page(struct page *page)
1766 VM_BUG_ON_PAGE(!page_count(page), page);
1767 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
1769 if (PageLRU(page)) {
1770 pg_data_t *pgdat = page_pgdat(page);
1771 struct lruvec *lruvec;
1773 spin_lock_irq(&pgdat->lru_lock);
1774 lruvec = mem_cgroup_page_lruvec(page, pgdat);
1775 if (PageLRU(page)) {
1776 int lru = page_lru(page);
1779 del_page_from_lru_list(page, lruvec, lru);
1782 spin_unlock_irq(&pgdat->lru_lock);
1788 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1789 * then get resheduled. When there are massive number of tasks doing page
1790 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1791 * the LRU list will go small and be scanned faster than necessary, leading to
1792 * unnecessary swapping, thrashing and OOM.
1794 static int too_many_isolated(struct pglist_data *pgdat, int file,
1795 struct scan_control *sc)
1797 unsigned long inactive, isolated;
1799 if (current_is_kswapd())
1802 if (!writeback_throttling_sane(sc))
1806 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1807 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
1809 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1810 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
1814 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
1815 * won't get blocked by normal direct-reclaimers, forming a circular
1818 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
1821 return isolated > inactive;
1825 * This moves pages from @list to corresponding LRU list.
1827 * We move them the other way if the page is referenced by one or more
1828 * processes, from rmap.
1830 * If the pages are mostly unmapped, the processing is fast and it is
1831 * appropriate to hold zone_lru_lock across the whole operation. But if
1832 * the pages are mapped, the processing is slow (page_referenced()) so we
1833 * should drop zone_lru_lock around each page. It's impossible to balance
1834 * this, so instead we remove the pages from the LRU while processing them.
1835 * It is safe to rely on PG_active against the non-LRU pages in here because
1836 * nobody will play with that bit on a non-LRU page.
1838 * The downside is that we have to touch page->_refcount against each page.
1839 * But we had to alter page->flags anyway.
1841 * Returns the number of pages moved to the given lruvec.
1844 static unsigned noinline_for_stack move_pages_to_lru(struct lruvec *lruvec,
1845 struct list_head *list)
1847 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
1848 int nr_pages, nr_moved = 0;
1849 LIST_HEAD(pages_to_free);
1853 while (!list_empty(list)) {
1854 page = lru_to_page(list);
1855 VM_BUG_ON_PAGE(PageLRU(page), page);
1856 if (unlikely(!page_evictable(page))) {
1857 list_del(&page->lru);
1858 spin_unlock_irq(&pgdat->lru_lock);
1859 putback_lru_page(page);
1860 spin_lock_irq(&pgdat->lru_lock);
1863 lruvec = mem_cgroup_page_lruvec(page, pgdat);
1866 lru = page_lru(page);
1868 nr_pages = hpage_nr_pages(page);
1869 update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
1870 list_move(&page->lru, &lruvec->lists[lru]);
1872 if (put_page_testzero(page)) {
1873 __ClearPageLRU(page);
1874 __ClearPageActive(page);
1875 del_page_from_lru_list(page, lruvec, lru);
1877 if (unlikely(PageCompound(page))) {
1878 spin_unlock_irq(&pgdat->lru_lock);
1879 (*get_compound_page_dtor(page))(page);
1880 spin_lock_irq(&pgdat->lru_lock);
1882 list_add(&page->lru, &pages_to_free);
1884 nr_moved += nr_pages;
1889 * To save our caller's stack, now use input list for pages to free.
1891 list_splice(&pages_to_free, list);
1897 * If a kernel thread (such as nfsd for loop-back mounts) services
1898 * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1899 * In that case we should only throttle if the backing device it is
1900 * writing to is congested. In other cases it is safe to throttle.
1902 static int current_may_throttle(void)
1904 return !(current->flags & PF_LESS_THROTTLE) ||
1905 current->backing_dev_info == NULL ||
1906 bdi_write_congested(current->backing_dev_info);
1910 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
1911 * of reclaimed pages
1913 static noinline_for_stack unsigned long
1914 shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
1915 struct scan_control *sc, enum lru_list lru)
1917 LIST_HEAD(page_list);
1918 unsigned long nr_scanned;
1919 unsigned long nr_reclaimed = 0;
1920 unsigned long nr_taken;
1921 struct reclaim_stat stat;
1922 int file = is_file_lru(lru);
1923 enum vm_event_item item;
1924 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
1925 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1926 bool stalled = false;
1928 while (unlikely(too_many_isolated(pgdat, file, sc))) {
1932 /* wait a bit for the reclaimer. */
1936 /* We are about to die and free our memory. Return now. */
1937 if (fatal_signal_pending(current))
1938 return SWAP_CLUSTER_MAX;
1943 spin_lock_irq(&pgdat->lru_lock);
1945 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
1946 &nr_scanned, sc, lru);
1948 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
1949 reclaim_stat->recent_scanned[file] += nr_taken;
1951 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
1952 if (!cgroup_reclaim(sc))
1953 __count_vm_events(item, nr_scanned);
1954 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
1955 spin_unlock_irq(&pgdat->lru_lock);
1960 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, 0,
1963 spin_lock_irq(&pgdat->lru_lock);
1965 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
1966 if (!cgroup_reclaim(sc))
1967 __count_vm_events(item, nr_reclaimed);
1968 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
1969 reclaim_stat->recent_rotated[0] += stat.nr_activate[0];
1970 reclaim_stat->recent_rotated[1] += stat.nr_activate[1];
1972 move_pages_to_lru(lruvec, &page_list);
1974 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
1976 spin_unlock_irq(&pgdat->lru_lock);
1978 mem_cgroup_uncharge_list(&page_list);
1979 free_unref_page_list(&page_list);
1982 * If dirty pages are scanned that are not queued for IO, it
1983 * implies that flushers are not doing their job. This can
1984 * happen when memory pressure pushes dirty pages to the end of
1985 * the LRU before the dirty limits are breached and the dirty
1986 * data has expired. It can also happen when the proportion of
1987 * dirty pages grows not through writes but through memory
1988 * pressure reclaiming all the clean cache. And in some cases,
1989 * the flushers simply cannot keep up with the allocation
1990 * rate. Nudge the flusher threads in case they are asleep.
1992 if (stat.nr_unqueued_dirty == nr_taken)
1993 wakeup_flusher_threads(WB_REASON_VMSCAN);
1995 sc->nr.dirty += stat.nr_dirty;
1996 sc->nr.congested += stat.nr_congested;
1997 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
1998 sc->nr.writeback += stat.nr_writeback;
1999 sc->nr.immediate += stat.nr_immediate;
2000 sc->nr.taken += nr_taken;
2002 sc->nr.file_taken += nr_taken;
2004 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2005 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
2006 return nr_reclaimed;
2009 static void shrink_active_list(unsigned long nr_to_scan,
2010 struct lruvec *lruvec,
2011 struct scan_control *sc,
2014 unsigned long nr_taken;
2015 unsigned long nr_scanned;
2016 unsigned long vm_flags;
2017 LIST_HEAD(l_hold); /* The pages which were snipped off */
2018 LIST_HEAD(l_active);
2019 LIST_HEAD(l_inactive);
2021 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
2022 unsigned nr_deactivate, nr_activate;
2023 unsigned nr_rotated = 0;
2024 int file = is_file_lru(lru);
2025 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2029 spin_lock_irq(&pgdat->lru_lock);
2031 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2032 &nr_scanned, sc, lru);
2034 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2035 reclaim_stat->recent_scanned[file] += nr_taken;
2037 __count_vm_events(PGREFILL, nr_scanned);
2038 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
2040 spin_unlock_irq(&pgdat->lru_lock);
2042 while (!list_empty(&l_hold)) {
2044 page = lru_to_page(&l_hold);
2045 list_del(&page->lru);
2047 if (unlikely(!page_evictable(page))) {
2048 putback_lru_page(page);
2052 if (unlikely(buffer_heads_over_limit)) {
2053 if (page_has_private(page) && trylock_page(page)) {
2054 if (page_has_private(page))
2055 try_to_release_page(page, 0);
2060 if (page_referenced(page, 0, sc->target_mem_cgroup,
2062 nr_rotated += hpage_nr_pages(page);
2064 * Identify referenced, file-backed active pages and
2065 * give them one more trip around the active list. So
2066 * that executable code get better chances to stay in
2067 * memory under moderate memory pressure. Anon pages
2068 * are not likely to be evicted by use-once streaming
2069 * IO, plus JVM can create lots of anon VM_EXEC pages,
2070 * so we ignore them here.
2072 if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
2073 list_add(&page->lru, &l_active);
2078 ClearPageActive(page); /* we are de-activating */
2079 SetPageWorkingset(page);
2080 list_add(&page->lru, &l_inactive);
2084 * Move pages back to the lru list.
2086 spin_lock_irq(&pgdat->lru_lock);
2088 * Count referenced pages from currently used mappings as rotated,
2089 * even though only some of them are actually re-activated. This
2090 * helps balance scan pressure between file and anonymous pages in
2093 reclaim_stat->recent_rotated[file] += nr_rotated;
2095 nr_activate = move_pages_to_lru(lruvec, &l_active);
2096 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2097 /* Keep all free pages in l_active list */
2098 list_splice(&l_inactive, &l_active);
2100 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2101 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2103 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2104 spin_unlock_irq(&pgdat->lru_lock);
2106 mem_cgroup_uncharge_list(&l_active);
2107 free_unref_page_list(&l_active);
2108 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2109 nr_deactivate, nr_rotated, sc->priority, file);
2112 unsigned long reclaim_pages(struct list_head *page_list)
2115 unsigned long nr_reclaimed = 0;
2116 LIST_HEAD(node_page_list);
2117 struct reclaim_stat dummy_stat;
2119 struct scan_control sc = {
2120 .gfp_mask = GFP_KERNEL,
2121 .priority = DEF_PRIORITY,
2127 while (!list_empty(page_list)) {
2128 page = lru_to_page(page_list);
2130 nid = page_to_nid(page);
2131 INIT_LIST_HEAD(&node_page_list);
2134 if (nid == page_to_nid(page)) {
2135 ClearPageActive(page);
2136 list_move(&page->lru, &node_page_list);
2140 nr_reclaimed += shrink_page_list(&node_page_list,
2143 &dummy_stat, false);
2144 while (!list_empty(&node_page_list)) {
2145 page = lru_to_page(&node_page_list);
2146 list_del(&page->lru);
2147 putback_lru_page(page);
2153 if (!list_empty(&node_page_list)) {
2154 nr_reclaimed += shrink_page_list(&node_page_list,
2157 &dummy_stat, false);
2158 while (!list_empty(&node_page_list)) {
2159 page = lru_to_page(&node_page_list);
2160 list_del(&page->lru);
2161 putback_lru_page(page);
2165 return nr_reclaimed;
2168 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2169 struct lruvec *lruvec, struct scan_control *sc)
2171 if (is_active_lru(lru)) {
2172 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2173 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2175 sc->skipped_deactivate = 1;
2179 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2183 * The inactive anon list should be small enough that the VM never has
2184 * to do too much work.
2186 * The inactive file list should be small enough to leave most memory
2187 * to the established workingset on the scan-resistant active list,
2188 * but large enough to avoid thrashing the aggregate readahead window.
2190 * Both inactive lists should also be large enough that each inactive
2191 * page has a chance to be referenced again before it is reclaimed.
2193 * If that fails and refaulting is observed, the inactive list grows.
2195 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
2196 * on this LRU, maintained by the pageout code. An inactive_ratio
2197 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2200 * memory ratio inactive
2201 * -------------------------------------
2210 static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
2212 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
2213 unsigned long inactive, active;
2214 unsigned long inactive_ratio;
2217 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2218 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2220 gb = (inactive + active) >> (30 - PAGE_SHIFT);
2222 inactive_ratio = int_sqrt(10 * gb);
2226 return inactive * inactive_ratio < active;
2237 * Determine how aggressively the anon and file LRU lists should be
2238 * scanned. The relative value of each set of LRU lists is determined
2239 * by looking at the fraction of the pages scanned we did rotate back
2240 * onto the active list instead of evict.
2242 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2243 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
2245 static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2248 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2249 int swappiness = mem_cgroup_swappiness(memcg);
2250 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
2251 u64 fraction[ANON_AND_FILE];
2252 u64 denominator = 0; /* gcc */
2253 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2254 unsigned long anon_prio, file_prio;
2255 enum scan_balance scan_balance;
2256 unsigned long anon, file;
2257 unsigned long ap, fp;
2260 /* If we have no swap space, do not bother scanning anon pages. */
2261 if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
2262 scan_balance = SCAN_FILE;
2267 * Global reclaim will swap to prevent OOM even with no
2268 * swappiness, but memcg users want to use this knob to
2269 * disable swapping for individual groups completely when
2270 * using the memory controller's swap limit feature would be
2273 if (cgroup_reclaim(sc) && !swappiness) {
2274 scan_balance = SCAN_FILE;
2279 * Do not apply any pressure balancing cleverness when the
2280 * system is close to OOM, scan both anon and file equally
2281 * (unless the swappiness setting disagrees with swapping).
2283 if (!sc->priority && swappiness) {
2284 scan_balance = SCAN_EQUAL;
2289 * If the system is almost out of file pages, force-scan anon.
2291 if (sc->file_is_tiny) {
2292 scan_balance = SCAN_ANON;
2297 * If there is enough inactive page cache, we do not reclaim
2298 * anything from the anonymous working right now.
2300 if (sc->cache_trim_mode) {
2301 scan_balance = SCAN_FILE;
2305 scan_balance = SCAN_FRACT;
2308 * With swappiness at 100, anonymous and file have the same priority.
2309 * This scanning priority is essentially the inverse of IO cost.
2311 anon_prio = swappiness;
2312 file_prio = 200 - anon_prio;
2315 * OK, so we have swap space and a fair amount of page cache
2316 * pages. We use the recently rotated / recently scanned
2317 * ratios to determine how valuable each cache is.
2319 * Because workloads change over time (and to avoid overflow)
2320 * we keep these statistics as a floating average, which ends
2321 * up weighing recent references more than old ones.
2323 * anon in [0], file in [1]
2326 anon = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON, MAX_NR_ZONES) +
2327 lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, MAX_NR_ZONES);
2328 file = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE, MAX_NR_ZONES) +
2329 lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, MAX_NR_ZONES);
2331 spin_lock_irq(&pgdat->lru_lock);
2332 if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
2333 reclaim_stat->recent_scanned[0] /= 2;
2334 reclaim_stat->recent_rotated[0] /= 2;
2337 if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
2338 reclaim_stat->recent_scanned[1] /= 2;
2339 reclaim_stat->recent_rotated[1] /= 2;
2343 * The amount of pressure on anon vs file pages is inversely
2344 * proportional to the fraction of recently scanned pages on
2345 * each list that were recently referenced and in active use.
2347 ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
2348 ap /= reclaim_stat->recent_rotated[0] + 1;
2350 fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
2351 fp /= reclaim_stat->recent_rotated[1] + 1;
2352 spin_unlock_irq(&pgdat->lru_lock);
2356 denominator = ap + fp + 1;
2358 for_each_evictable_lru(lru) {
2359 int file = is_file_lru(lru);
2360 unsigned long lruvec_size;
2362 unsigned long protection;
2364 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2365 protection = mem_cgroup_protection(memcg,
2366 sc->memcg_low_reclaim);
2370 * Scale a cgroup's reclaim pressure by proportioning
2371 * its current usage to its memory.low or memory.min
2374 * This is important, as otherwise scanning aggression
2375 * becomes extremely binary -- from nothing as we
2376 * approach the memory protection threshold, to totally
2377 * nominal as we exceed it. This results in requiring
2378 * setting extremely liberal protection thresholds. It
2379 * also means we simply get no protection at all if we
2380 * set it too low, which is not ideal.
2382 * If there is any protection in place, we reduce scan
2383 * pressure by how much of the total memory used is
2384 * within protection thresholds.
2386 * There is one special case: in the first reclaim pass,
2387 * we skip over all groups that are within their low
2388 * protection. If that fails to reclaim enough pages to
2389 * satisfy the reclaim goal, we come back and override
2390 * the best-effort low protection. However, we still
2391 * ideally want to honor how well-behaved groups are in
2392 * that case instead of simply punishing them all
2393 * equally. As such, we reclaim them based on how much
2394 * memory they are using, reducing the scan pressure
2395 * again by how much of the total memory used is under
2398 unsigned long cgroup_size = mem_cgroup_size(memcg);
2400 /* Avoid TOCTOU with earlier protection check */
2401 cgroup_size = max(cgroup_size, protection);
2403 scan = lruvec_size - lruvec_size * protection /
2407 * Minimally target SWAP_CLUSTER_MAX pages to keep
2408 * reclaim moving forwards, avoiding decremeting
2409 * sc->priority further than desirable.
2411 scan = max(scan, SWAP_CLUSTER_MAX);
2416 scan >>= sc->priority;
2419 * If the cgroup's already been deleted, make sure to
2420 * scrape out the remaining cache.
2422 if (!scan && !mem_cgroup_online(memcg))
2423 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
2425 switch (scan_balance) {
2427 /* Scan lists relative to size */
2431 * Scan types proportional to swappiness and
2432 * their relative recent reclaim efficiency.
2433 * Make sure we don't miss the last page on
2434 * the offlined memory cgroups because of a
2437 scan = mem_cgroup_online(memcg) ?
2438 div64_u64(scan * fraction[file], denominator) :
2439 DIV64_U64_ROUND_UP(scan * fraction[file],
2444 /* Scan one type exclusively */
2445 if ((scan_balance == SCAN_FILE) != file)
2449 /* Look ma, no brain */
2457 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
2459 unsigned long nr[NR_LRU_LISTS];
2460 unsigned long targets[NR_LRU_LISTS];
2461 unsigned long nr_to_scan;
2463 unsigned long nr_reclaimed = 0;
2464 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
2465 struct blk_plug plug;
2468 get_scan_count(lruvec, sc, nr);
2470 /* Record the original scan target for proportional adjustments later */
2471 memcpy(targets, nr, sizeof(nr));
2474 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
2475 * event that can occur when there is little memory pressure e.g.
2476 * multiple streaming readers/writers. Hence, we do not abort scanning
2477 * when the requested number of pages are reclaimed when scanning at
2478 * DEF_PRIORITY on the assumption that the fact we are direct
2479 * reclaiming implies that kswapd is not keeping up and it is best to
2480 * do a batch of work at once. For memcg reclaim one check is made to
2481 * abort proportional reclaim if either the file or anon lru has already
2482 * dropped to zero at the first pass.
2484 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
2485 sc->priority == DEF_PRIORITY);
2487 blk_start_plug(&plug);
2488 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
2489 nr[LRU_INACTIVE_FILE]) {
2490 unsigned long nr_anon, nr_file, percentage;
2491 unsigned long nr_scanned;
2493 for_each_evictable_lru(lru) {
2495 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
2496 nr[lru] -= nr_to_scan;
2498 nr_reclaimed += shrink_list(lru, nr_to_scan,
2505 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2509 * For kswapd and memcg, reclaim at least the number of pages
2510 * requested. Ensure that the anon and file LRUs are scanned
2511 * proportionally what was requested by get_scan_count(). We
2512 * stop reclaiming one LRU and reduce the amount scanning
2513 * proportional to the original scan target.
2515 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2516 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2519 * It's just vindictive to attack the larger once the smaller
2520 * has gone to zero. And given the way we stop scanning the
2521 * smaller below, this makes sure that we only make one nudge
2522 * towards proportionality once we've got nr_to_reclaim.
2524 if (!nr_file || !nr_anon)
2527 if (nr_file > nr_anon) {
2528 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2529 targets[LRU_ACTIVE_ANON] + 1;
2531 percentage = nr_anon * 100 / scan_target;
2533 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2534 targets[LRU_ACTIVE_FILE] + 1;
2536 percentage = nr_file * 100 / scan_target;
2539 /* Stop scanning the smaller of the LRU */
2541 nr[lru + LRU_ACTIVE] = 0;
2544 * Recalculate the other LRU scan count based on its original
2545 * scan target and the percentage scanning already complete
2547 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2548 nr_scanned = targets[lru] - nr[lru];
2549 nr[lru] = targets[lru] * (100 - percentage) / 100;
2550 nr[lru] -= min(nr[lru], nr_scanned);
2553 nr_scanned = targets[lru] - nr[lru];
2554 nr[lru] = targets[lru] * (100 - percentage) / 100;
2555 nr[lru] -= min(nr[lru], nr_scanned);
2557 scan_adjusted = true;
2559 blk_finish_plug(&plug);
2560 sc->nr_reclaimed += nr_reclaimed;
2563 * Even if we did not try to evict anon pages at all, we want to
2564 * rebalance the anon lru active/inactive ratio.
2566 if (total_swap_pages && inactive_is_low(lruvec, LRU_INACTIVE_ANON))
2567 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
2568 sc, LRU_ACTIVE_ANON);
2571 /* Use reclaim/compaction for costly allocs or under memory pressure */
2572 static bool in_reclaim_compaction(struct scan_control *sc)
2574 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
2575 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
2576 sc->priority < DEF_PRIORITY - 2))
2583 * Reclaim/compaction is used for high-order allocation requests. It reclaims
2584 * order-0 pages before compacting the zone. should_continue_reclaim() returns
2585 * true if more pages should be reclaimed such that when the page allocator
2586 * calls try_to_compact_zone() that it will have enough free pages to succeed.
2587 * It will give up earlier than that if there is difficulty reclaiming pages.
2589 static inline bool should_continue_reclaim(struct pglist_data *pgdat,
2590 unsigned long nr_reclaimed,
2591 struct scan_control *sc)
2593 unsigned long pages_for_compaction;
2594 unsigned long inactive_lru_pages;
2597 /* If not in reclaim/compaction mode, stop */
2598 if (!in_reclaim_compaction(sc))
2602 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
2603 * number of pages that were scanned. This will return to the caller
2604 * with the risk reclaim/compaction and the resulting allocation attempt
2605 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
2606 * allocations through requiring that the full LRU list has been scanned
2607 * first, by assuming that zero delta of sc->nr_scanned means full LRU
2608 * scan, but that approximation was wrong, and there were corner cases
2609 * where always a non-zero amount of pages were scanned.
2614 /* If compaction would go ahead or the allocation would succeed, stop */
2615 for (z = 0; z <= sc->reclaim_idx; z++) {
2616 struct zone *zone = &pgdat->node_zones[z];
2617 if (!managed_zone(zone))
2620 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2621 case COMPACT_SUCCESS:
2622 case COMPACT_CONTINUE:
2625 /* check next zone */
2631 * If we have not reclaimed enough pages for compaction and the
2632 * inactive lists are large enough, continue reclaiming
2634 pages_for_compaction = compact_gap(sc->order);
2635 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
2636 if (get_nr_swap_pages() > 0)
2637 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
2639 return inactive_lru_pages > pages_for_compaction;
2642 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
2644 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
2645 struct mem_cgroup *memcg;
2647 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
2649 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
2650 unsigned long reclaimed;
2651 unsigned long scanned;
2653 switch (mem_cgroup_protected(target_memcg, memcg)) {
2654 case MEMCG_PROT_MIN:
2657 * If there is no reclaimable memory, OOM.
2660 case MEMCG_PROT_LOW:
2663 * Respect the protection only as long as
2664 * there is an unprotected supply
2665 * of reclaimable memory from other cgroups.
2667 if (!sc->memcg_low_reclaim) {
2668 sc->memcg_low_skipped = 1;
2671 memcg_memory_event(memcg, MEMCG_LOW);
2673 case MEMCG_PROT_NONE:
2675 * All protection thresholds breached. We may
2676 * still choose to vary the scan pressure
2677 * applied based on by how much the cgroup in
2678 * question has exceeded its protection
2679 * thresholds (see get_scan_count).
2684 reclaimed = sc->nr_reclaimed;
2685 scanned = sc->nr_scanned;
2687 shrink_lruvec(lruvec, sc);
2689 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
2692 /* Record the group's reclaim efficiency */
2693 vmpressure(sc->gfp_mask, memcg, false,
2694 sc->nr_scanned - scanned,
2695 sc->nr_reclaimed - reclaimed);
2697 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
2700 static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc)
2702 struct reclaim_state *reclaim_state = current->reclaim_state;
2703 unsigned long nr_reclaimed, nr_scanned;
2704 struct lruvec *target_lruvec;
2705 bool reclaimable = false;
2708 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2711 memset(&sc->nr, 0, sizeof(sc->nr));
2713 nr_reclaimed = sc->nr_reclaimed;
2714 nr_scanned = sc->nr_scanned;
2717 * Target desirable inactive:active list ratios for the anon
2718 * and file LRU lists.
2720 if (!sc->force_deactivate) {
2721 unsigned long refaults;
2723 if (inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2724 sc->may_deactivate |= DEACTIVATE_ANON;
2726 sc->may_deactivate &= ~DEACTIVATE_ANON;
2729 * When refaults are being observed, it means a new
2730 * workingset is being established. Deactivate to get
2731 * rid of any stale active pages quickly.
2733 refaults = lruvec_page_state(target_lruvec,
2734 WORKINGSET_ACTIVATE);
2735 if (refaults != target_lruvec->refaults ||
2736 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2737 sc->may_deactivate |= DEACTIVATE_FILE;
2739 sc->may_deactivate &= ~DEACTIVATE_FILE;
2741 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2744 * If we have plenty of inactive file pages that aren't
2745 * thrashing, try to reclaim those first before touching
2748 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2749 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2750 sc->cache_trim_mode = 1;
2752 sc->cache_trim_mode = 0;
2755 * Prevent the reclaimer from falling into the cache trap: as
2756 * cache pages start out inactive, every cache fault will tip
2757 * the scan balance towards the file LRU. And as the file LRU
2758 * shrinks, so does the window for rotation from references.
2759 * This means we have a runaway feedback loop where a tiny
2760 * thrashing file LRU becomes infinitely more attractive than
2761 * anon pages. Try to detect this based on file LRU size.
2763 if (!cgroup_reclaim(sc)) {
2764 unsigned long total_high_wmark = 0;
2765 unsigned long free, anon;
2768 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2769 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2770 node_page_state(pgdat, NR_INACTIVE_FILE);
2772 for (z = 0; z < MAX_NR_ZONES; z++) {
2773 struct zone *zone = &pgdat->node_zones[z];
2774 if (!managed_zone(zone))
2777 total_high_wmark += high_wmark_pages(zone);
2781 * Consider anon: if that's low too, this isn't a
2782 * runaway file reclaim problem, but rather just
2783 * extreme pressure. Reclaim as per usual then.
2785 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2788 file + free <= total_high_wmark &&
2789 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2790 anon >> sc->priority;
2793 shrink_node_memcgs(pgdat, sc);
2795 if (reclaim_state) {
2796 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
2797 reclaim_state->reclaimed_slab = 0;
2800 /* Record the subtree's reclaim efficiency */
2801 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
2802 sc->nr_scanned - nr_scanned,
2803 sc->nr_reclaimed - nr_reclaimed);
2805 if (sc->nr_reclaimed - nr_reclaimed)
2808 if (current_is_kswapd()) {
2810 * If reclaim is isolating dirty pages under writeback,
2811 * it implies that the long-lived page allocation rate
2812 * is exceeding the page laundering rate. Either the
2813 * global limits are not being effective at throttling
2814 * processes due to the page distribution throughout
2815 * zones or there is heavy usage of a slow backing
2816 * device. The only option is to throttle from reclaim
2817 * context which is not ideal as there is no guarantee
2818 * the dirtying process is throttled in the same way
2819 * balance_dirty_pages() manages.
2821 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
2822 * count the number of pages under pages flagged for
2823 * immediate reclaim and stall if any are encountered
2824 * in the nr_immediate check below.
2826 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
2827 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
2829 /* Allow kswapd to start writing pages during reclaim.*/
2830 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
2831 set_bit(PGDAT_DIRTY, &pgdat->flags);
2834 * If kswapd scans pages marked marked for immediate
2835 * reclaim and under writeback (nr_immediate), it
2836 * implies that pages are cycling through the LRU
2837 * faster than they are written so also forcibly stall.
2839 if (sc->nr.immediate)
2840 congestion_wait(BLK_RW_ASYNC, HZ/10);
2844 * Tag a node/memcg as congested if all the dirty pages
2845 * scanned were backed by a congested BDI and
2846 * wait_iff_congested will stall.
2848 * Legacy memcg will stall in page writeback so avoid forcibly
2849 * stalling in wait_iff_congested().
2851 if ((current_is_kswapd() ||
2852 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
2853 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
2854 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
2857 * Stall direct reclaim for IO completions if underlying BDIs
2858 * and node is congested. Allow kswapd to continue until it
2859 * starts encountering unqueued dirty pages or cycling through
2860 * the LRU too quickly.
2862 if (!current_is_kswapd() && current_may_throttle() &&
2863 !sc->hibernation_mode &&
2864 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
2865 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
2867 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
2872 * Kswapd gives up on balancing particular nodes after too
2873 * many failures to reclaim anything from them and goes to
2874 * sleep. On reclaim progress, reset the failure counter. A
2875 * successful direct reclaim run will revive a dormant kswapd.
2878 pgdat->kswapd_failures = 0;
2884 * Returns true if compaction should go ahead for a costly-order request, or
2885 * the allocation would already succeed without compaction. Return false if we
2886 * should reclaim first.
2888 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2890 unsigned long watermark;
2891 enum compact_result suitable;
2893 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2894 if (suitable == COMPACT_SUCCESS)
2895 /* Allocation should succeed already. Don't reclaim. */
2897 if (suitable == COMPACT_SKIPPED)
2898 /* Compaction cannot yet proceed. Do reclaim. */
2902 * Compaction is already possible, but it takes time to run and there
2903 * are potentially other callers using the pages just freed. So proceed
2904 * with reclaim to make a buffer of free pages available to give
2905 * compaction a reasonable chance of completing and allocating the page.
2906 * Note that we won't actually reclaim the whole buffer in one attempt
2907 * as the target watermark in should_continue_reclaim() is lower. But if
2908 * we are already above the high+gap watermark, don't reclaim at all.
2910 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
2912 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
2916 * This is the direct reclaim path, for page-allocating processes. We only
2917 * try to reclaim pages from zones which will satisfy the caller's allocation
2920 * If a zone is deemed to be full of pinned pages then just give it a light
2921 * scan then give up on it.
2923 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
2927 unsigned long nr_soft_reclaimed;
2928 unsigned long nr_soft_scanned;
2930 pg_data_t *last_pgdat = NULL;
2933 * If the number of buffer_heads in the machine exceeds the maximum
2934 * allowed level, force direct reclaim to scan the highmem zone as
2935 * highmem pages could be pinning lowmem pages storing buffer_heads
2937 orig_mask = sc->gfp_mask;
2938 if (buffer_heads_over_limit) {
2939 sc->gfp_mask |= __GFP_HIGHMEM;
2940 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
2943 for_each_zone_zonelist_nodemask(zone, z, zonelist,
2944 sc->reclaim_idx, sc->nodemask) {
2946 * Take care memory controller reclaiming has small influence
2949 if (!cgroup_reclaim(sc)) {
2950 if (!cpuset_zone_allowed(zone,
2951 GFP_KERNEL | __GFP_HARDWALL))
2955 * If we already have plenty of memory free for
2956 * compaction in this zone, don't free any more.
2957 * Even though compaction is invoked for any
2958 * non-zero order, only frequent costly order
2959 * reclamation is disruptive enough to become a
2960 * noticeable problem, like transparent huge
2963 if (IS_ENABLED(CONFIG_COMPACTION) &&
2964 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
2965 compaction_ready(zone, sc)) {
2966 sc->compaction_ready = true;
2971 * Shrink each node in the zonelist once. If the
2972 * zonelist is ordered by zone (not the default) then a
2973 * node may be shrunk multiple times but in that case
2974 * the user prefers lower zones being preserved.
2976 if (zone->zone_pgdat == last_pgdat)
2980 * This steals pages from memory cgroups over softlimit
2981 * and returns the number of reclaimed pages and
2982 * scanned pages. This works for global memory pressure
2983 * and balancing, not for a memcg's limit.
2985 nr_soft_scanned = 0;
2986 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
2987 sc->order, sc->gfp_mask,
2989 sc->nr_reclaimed += nr_soft_reclaimed;
2990 sc->nr_scanned += nr_soft_scanned;
2991 /* need some check for avoid more shrink_zone() */
2994 /* See comment about same check for global reclaim above */
2995 if (zone->zone_pgdat == last_pgdat)
2997 last_pgdat = zone->zone_pgdat;
2998 shrink_node(zone->zone_pgdat, sc);
3002 * Restore to original mask to avoid the impact on the caller if we
3003 * promoted it to __GFP_HIGHMEM.
3005 sc->gfp_mask = orig_mask;
3008 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
3010 struct lruvec *target_lruvec;
3011 unsigned long refaults;
3013 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
3014 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE);
3015 target_lruvec->refaults = refaults;
3019 * This is the main entry point to direct page reclaim.
3021 * If a full scan of the inactive list fails to free enough memory then we
3022 * are "out of memory" and something needs to be killed.
3024 * If the caller is !__GFP_FS then the probability of a failure is reasonably
3025 * high - the zone may be full of dirty or under-writeback pages, which this
3026 * caller can't do much about. We kick the writeback threads and take explicit
3027 * naps in the hope that some of these pages can be written. But if the
3028 * allocating task holds filesystem locks which prevent writeout this might not
3029 * work, and the allocation attempt will fail.
3031 * returns: 0, if no pages reclaimed
3032 * else, the number of pages reclaimed
3034 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
3035 struct scan_control *sc)
3037 int initial_priority = sc->priority;
3038 pg_data_t *last_pgdat;
3042 delayacct_freepages_start();
3044 if (!cgroup_reclaim(sc))
3045 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
3048 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
3051 shrink_zones(zonelist, sc);
3053 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
3056 if (sc->compaction_ready)
3060 * If we're getting trouble reclaiming, start doing
3061 * writepage even in laptop mode.
3063 if (sc->priority < DEF_PRIORITY - 2)
3064 sc->may_writepage = 1;
3065 } while (--sc->priority >= 0);
3068 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
3070 if (zone->zone_pgdat == last_pgdat)
3072 last_pgdat = zone->zone_pgdat;
3074 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
3076 if (cgroup_reclaim(sc)) {
3077 struct lruvec *lruvec;
3079 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
3081 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3085 delayacct_freepages_end();
3087 if (sc->nr_reclaimed)
3088 return sc->nr_reclaimed;
3090 /* Aborted reclaim to try compaction? don't OOM, then */
3091 if (sc->compaction_ready)
3095 * We make inactive:active ratio decisions based on the node's
3096 * composition of memory, but a restrictive reclaim_idx or a
3097 * memory.low cgroup setting can exempt large amounts of
3098 * memory from reclaim. Neither of which are very common, so
3099 * instead of doing costly eligibility calculations of the
3100 * entire cgroup subtree up front, we assume the estimates are
3101 * good, and retry with forcible deactivation if that fails.
3103 if (sc->skipped_deactivate) {
3104 sc->priority = initial_priority;
3105 sc->force_deactivate = 1;
3106 sc->skipped_deactivate = 0;
3110 /* Untapped cgroup reserves? Don't OOM, retry. */
3111 if (sc->memcg_low_skipped) {
3112 sc->priority = initial_priority;
3113 sc->force_deactivate = 0;
3114 sc->skipped_deactivate = 0;
3115 sc->memcg_low_reclaim = 1;
3116 sc->memcg_low_skipped = 0;
3123 static bool allow_direct_reclaim(pg_data_t *pgdat)
3126 unsigned long pfmemalloc_reserve = 0;
3127 unsigned long free_pages = 0;
3131 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3134 for (i = 0; i <= ZONE_NORMAL; i++) {
3135 zone = &pgdat->node_zones[i];
3136 if (!managed_zone(zone))
3139 if (!zone_reclaimable_pages(zone))
3142 pfmemalloc_reserve += min_wmark_pages(zone);
3143 free_pages += zone_page_state(zone, NR_FREE_PAGES);
3146 /* If there are no reserves (unexpected config) then do not throttle */
3147 if (!pfmemalloc_reserve)
3150 wmark_ok = free_pages > pfmemalloc_reserve / 2;
3152 /* kswapd must be awake if processes are being throttled */
3153 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
3154 pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
3155 (enum zone_type)ZONE_NORMAL);
3156 wake_up_interruptible(&pgdat->kswapd_wait);
3163 * Throttle direct reclaimers if backing storage is backed by the network
3164 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
3165 * depleted. kswapd will continue to make progress and wake the processes
3166 * when the low watermark is reached.
3168 * Returns true if a fatal signal was delivered during throttling. If this
3169 * happens, the page allocator should not consider triggering the OOM killer.
3171 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
3172 nodemask_t *nodemask)
3176 pg_data_t *pgdat = NULL;
3179 * Kernel threads should not be throttled as they may be indirectly
3180 * responsible for cleaning pages necessary for reclaim to make forward
3181 * progress. kjournald for example may enter direct reclaim while
3182 * committing a transaction where throttling it could forcing other
3183 * processes to block on log_wait_commit().
3185 if (current->flags & PF_KTHREAD)
3189 * If a fatal signal is pending, this process should not throttle.
3190 * It should return quickly so it can exit and free its memory
3192 if (fatal_signal_pending(current))
3196 * Check if the pfmemalloc reserves are ok by finding the first node
3197 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3198 * GFP_KERNEL will be required for allocating network buffers when
3199 * swapping over the network so ZONE_HIGHMEM is unusable.
3201 * Throttling is based on the first usable node and throttled processes
3202 * wait on a queue until kswapd makes progress and wakes them. There
3203 * is an affinity then between processes waking up and where reclaim
3204 * progress has been made assuming the process wakes on the same node.
3205 * More importantly, processes running on remote nodes will not compete
3206 * for remote pfmemalloc reserves and processes on different nodes
3207 * should make reasonable progress.
3209 for_each_zone_zonelist_nodemask(zone, z, zonelist,
3210 gfp_zone(gfp_mask), nodemask) {
3211 if (zone_idx(zone) > ZONE_NORMAL)
3214 /* Throttle based on the first usable node */
3215 pgdat = zone->zone_pgdat;
3216 if (allow_direct_reclaim(pgdat))
3221 /* If no zone was usable by the allocation flags then do not throttle */
3225 /* Account for the throttling */
3226 count_vm_event(PGSCAN_DIRECT_THROTTLE);
3229 * If the caller cannot enter the filesystem, it's possible that it
3230 * is due to the caller holding an FS lock or performing a journal
3231 * transaction in the case of a filesystem like ext[3|4]. In this case,
3232 * it is not safe to block on pfmemalloc_wait as kswapd could be
3233 * blocked waiting on the same lock. Instead, throttle for up to a
3234 * second before continuing.
3236 if (!(gfp_mask & __GFP_FS)) {
3237 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3238 allow_direct_reclaim(pgdat), HZ);
3243 /* Throttle until kswapd wakes the process */
3244 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3245 allow_direct_reclaim(pgdat));
3248 if (fatal_signal_pending(current))
3255 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3256 gfp_t gfp_mask, nodemask_t *nodemask)
3258 unsigned long nr_reclaimed;
3259 struct scan_control sc = {
3260 .nr_to_reclaim = SWAP_CLUSTER_MAX,
3261 .gfp_mask = current_gfp_context(gfp_mask),
3262 .reclaim_idx = gfp_zone(gfp_mask),
3264 .nodemask = nodemask,
3265 .priority = DEF_PRIORITY,
3266 .may_writepage = !laptop_mode,
3272 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3273 * Confirm they are large enough for max values.
3275 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3276 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3277 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3280 * Do not enter reclaim if fatal signal was delivered while throttled.
3281 * 1 is returned so that the page allocator does not OOM kill at this
3284 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
3287 set_task_reclaim_state(current, &sc.reclaim_state);
3288 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
3290 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3292 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
3293 set_task_reclaim_state(current, NULL);
3295 return nr_reclaimed;
3300 /* Only used by soft limit reclaim. Do not reuse for anything else. */
3301 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
3302 gfp_t gfp_mask, bool noswap,
3304 unsigned long *nr_scanned)
3306 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3307 struct scan_control sc = {
3308 .nr_to_reclaim = SWAP_CLUSTER_MAX,
3309 .target_mem_cgroup = memcg,
3310 .may_writepage = !laptop_mode,
3312 .reclaim_idx = MAX_NR_ZONES - 1,
3313 .may_swap = !noswap,
3316 WARN_ON_ONCE(!current->reclaim_state);
3318 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
3319 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3321 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
3325 * NOTE: Although we can get the priority field, using it
3326 * here is not a good idea, since it limits the pages we can scan.
3327 * if we don't reclaim here, the shrink_node from balance_pgdat
3328 * will pick up pages from other mem cgroup's as well. We hack
3329 * the priority and make it zero.
3331 shrink_lruvec(lruvec, &sc);
3333 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3335 *nr_scanned = sc.nr_scanned;
3337 return sc.nr_reclaimed;
3340 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3341 unsigned long nr_pages,
3345 struct zonelist *zonelist;
3346 unsigned long nr_reclaimed;
3347 unsigned long pflags;
3349 unsigned int noreclaim_flag;
3350 struct scan_control sc = {
3351 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
3352 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3353 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3354 .reclaim_idx = MAX_NR_ZONES - 1,
3355 .target_mem_cgroup = memcg,
3356 .priority = DEF_PRIORITY,
3357 .may_writepage = !laptop_mode,
3359 .may_swap = may_swap,
3362 set_task_reclaim_state(current, &sc.reclaim_state);
3364 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
3365 * take care of from where we get pages. So the node where we start the
3366 * scan does not need to be the current node.
3368 nid = mem_cgroup_select_victim_node(memcg);
3370 zonelist = &NODE_DATA(nid)->node_zonelists[ZONELIST_FALLBACK];
3372 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
3374 psi_memstall_enter(&pflags);
3375 noreclaim_flag = memalloc_noreclaim_save();
3377 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3379 memalloc_noreclaim_restore(noreclaim_flag);
3380 psi_memstall_leave(&pflags);
3382 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
3383 set_task_reclaim_state(current, NULL);
3385 return nr_reclaimed;
3389 static void age_active_anon(struct pglist_data *pgdat,
3390 struct scan_control *sc)
3392 struct mem_cgroup *memcg;
3393 struct lruvec *lruvec;
3395 if (!total_swap_pages)
3398 lruvec = mem_cgroup_lruvec(NULL, pgdat);
3399 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
3402 memcg = mem_cgroup_iter(NULL, NULL, NULL);
3404 lruvec = mem_cgroup_lruvec(memcg, pgdat);
3405 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
3406 sc, LRU_ACTIVE_ANON);
3407 memcg = mem_cgroup_iter(NULL, memcg, NULL);
3411 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int classzone_idx)
3417 * Check for watermark boosts top-down as the higher zones
3418 * are more likely to be boosted. Both watermarks and boosts
3419 * should not be checked at the time time as reclaim would
3420 * start prematurely when there is no boosting and a lower
3423 for (i = classzone_idx; i >= 0; i--) {
3424 zone = pgdat->node_zones + i;
3425 if (!managed_zone(zone))
3428 if (zone->watermark_boost)
3436 * Returns true if there is an eligible zone balanced for the request order
3439 static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
3442 unsigned long mark = -1;
3446 * Check watermarks bottom-up as lower zones are more likely to
3449 for (i = 0; i <= classzone_idx; i++) {
3450 zone = pgdat->node_zones + i;
3452 if (!managed_zone(zone))
3455 mark = high_wmark_pages(zone);
3456 if (zone_watermark_ok_safe(zone, order, mark, classzone_idx))
3461 * If a node has no populated zone within classzone_idx, it does not
3462 * need balancing by definition. This can happen if a zone-restricted
3463 * allocation tries to wake a remote kswapd.
3471 /* Clear pgdat state for congested, dirty or under writeback. */
3472 static void clear_pgdat_congested(pg_data_t *pgdat)
3474 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
3476 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3477 clear_bit(PGDAT_DIRTY, &pgdat->flags);
3478 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3482 * Prepare kswapd for sleeping. This verifies that there are no processes
3483 * waiting in throttle_direct_reclaim() and that watermarks have been met.
3485 * Returns true if kswapd is ready to sleep
3487 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3490 * The throttled processes are normally woken up in balance_pgdat() as
3491 * soon as allow_direct_reclaim() is true. But there is a potential
3492 * race between when kswapd checks the watermarks and a process gets
3493 * throttled. There is also a potential race if processes get
3494 * throttled, kswapd wakes, a large process exits thereby balancing the
3495 * zones, which causes kswapd to exit balance_pgdat() before reaching
3496 * the wake up checks. If kswapd is going to sleep, no process should
3497 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
3498 * the wake up is premature, processes will wake kswapd and get
3499 * throttled again. The difference from wake ups in balance_pgdat() is
3500 * that here we are under prepare_to_wait().
3502 if (waitqueue_active(&pgdat->pfmemalloc_wait))
3503 wake_up_all(&pgdat->pfmemalloc_wait);
3505 /* Hopeless node, leave it to direct reclaim */
3506 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3509 if (pgdat_balanced(pgdat, order, classzone_idx)) {
3510 clear_pgdat_congested(pgdat);
3518 * kswapd shrinks a node of pages that are at or below the highest usable
3519 * zone that is currently unbalanced.
3521 * Returns true if kswapd scanned at least the requested number of pages to
3522 * reclaim or if the lack of progress was due to pages under writeback.
3523 * This is used to determine if the scanning priority needs to be raised.
3525 static bool kswapd_shrink_node(pg_data_t *pgdat,
3526 struct scan_control *sc)
3531 /* Reclaim a number of pages proportional to the number of zones */
3532 sc->nr_to_reclaim = 0;
3533 for (z = 0; z <= sc->reclaim_idx; z++) {
3534 zone = pgdat->node_zones + z;
3535 if (!managed_zone(zone))
3538 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
3542 * Historically care was taken to put equal pressure on all zones but
3543 * now pressure is applied based on node LRU order.
3545 shrink_node(pgdat, sc);
3548 * Fragmentation may mean that the system cannot be rebalanced for
3549 * high-order allocations. If twice the allocation size has been
3550 * reclaimed then recheck watermarks only at order-0 to prevent
3551 * excessive reclaim. Assume that a process requested a high-order
3552 * can direct reclaim/compact.
3554 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
3557 return sc->nr_scanned >= sc->nr_to_reclaim;
3561 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
3562 * that are eligible for use by the caller until at least one zone is
3565 * Returns the order kswapd finished reclaiming at.
3567 * kswapd scans the zones in the highmem->normal->dma direction. It skips
3568 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
3569 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
3570 * or lower is eligible for reclaim until at least one usable zone is
3573 static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
3576 unsigned long nr_soft_reclaimed;
3577 unsigned long nr_soft_scanned;
3578 unsigned long pflags;
3579 unsigned long nr_boost_reclaim;
3580 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
3583 struct scan_control sc = {
3584 .gfp_mask = GFP_KERNEL,
3589 set_task_reclaim_state(current, &sc.reclaim_state);
3590 psi_memstall_enter(&pflags);
3591 __fs_reclaim_acquire();
3593 count_vm_event(PAGEOUTRUN);
3596 * Account for the reclaim boost. Note that the zone boost is left in
3597 * place so that parallel allocations that are near the watermark will
3598 * stall or direct reclaim until kswapd is finished.
3600 nr_boost_reclaim = 0;
3601 for (i = 0; i <= classzone_idx; i++) {
3602 zone = pgdat->node_zones + i;
3603 if (!managed_zone(zone))
3606 nr_boost_reclaim += zone->watermark_boost;
3607 zone_boosts[i] = zone->watermark_boost;
3609 boosted = nr_boost_reclaim;
3612 sc.priority = DEF_PRIORITY;
3614 unsigned long nr_reclaimed = sc.nr_reclaimed;
3615 bool raise_priority = true;
3619 sc.reclaim_idx = classzone_idx;
3622 * If the number of buffer_heads exceeds the maximum allowed
3623 * then consider reclaiming from all zones. This has a dual
3624 * purpose -- on 64-bit systems it is expected that
3625 * buffer_heads are stripped during active rotation. On 32-bit
3626 * systems, highmem pages can pin lowmem memory and shrinking
3627 * buffers can relieve lowmem pressure. Reclaim may still not
3628 * go ahead if all eligible zones for the original allocation
3629 * request are balanced to avoid excessive reclaim from kswapd.
3631 if (buffer_heads_over_limit) {
3632 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
3633 zone = pgdat->node_zones + i;
3634 if (!managed_zone(zone))
3643 * If the pgdat is imbalanced then ignore boosting and preserve
3644 * the watermarks for a later time and restart. Note that the
3645 * zone watermarks will be still reset at the end of balancing
3646 * on the grounds that the normal reclaim should be enough to
3647 * re-evaluate if boosting is required when kswapd next wakes.
3649 balanced = pgdat_balanced(pgdat, sc.order, classzone_idx);
3650 if (!balanced && nr_boost_reclaim) {
3651 nr_boost_reclaim = 0;
3656 * If boosting is not active then only reclaim if there are no
3657 * eligible zones. Note that sc.reclaim_idx is not used as
3658 * buffer_heads_over_limit may have adjusted it.
3660 if (!nr_boost_reclaim && balanced)
3663 /* Limit the priority of boosting to avoid reclaim writeback */
3664 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
3665 raise_priority = false;
3668 * Do not writeback or swap pages for boosted reclaim. The
3669 * intent is to relieve pressure not issue sub-optimal IO
3670 * from reclaim context. If no pages are reclaimed, the
3671 * reclaim will be aborted.
3673 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
3674 sc.may_swap = !nr_boost_reclaim;
3677 * Do some background aging of the anon list, to give
3678 * pages a chance to be referenced before reclaiming. All
3679 * pages are rotated regardless of classzone as this is
3680 * about consistent aging.
3682 age_active_anon(pgdat, &sc);
3685 * If we're getting trouble reclaiming, start doing writepage
3686 * even in laptop mode.
3688 if (sc.priority < DEF_PRIORITY - 2)
3689 sc.may_writepage = 1;
3691 /* Call soft limit reclaim before calling shrink_node. */
3693 nr_soft_scanned = 0;
3694 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
3695 sc.gfp_mask, &nr_soft_scanned);
3696 sc.nr_reclaimed += nr_soft_reclaimed;
3699 * There should be no need to raise the scanning priority if
3700 * enough pages are already being scanned that that high
3701 * watermark would be met at 100% efficiency.
3703 if (kswapd_shrink_node(pgdat, &sc))
3704 raise_priority = false;
3707 * If the low watermark is met there is no need for processes
3708 * to be throttled on pfmemalloc_wait as they should not be
3709 * able to safely make forward progress. Wake them
3711 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3712 allow_direct_reclaim(pgdat))
3713 wake_up_all(&pgdat->pfmemalloc_wait);
3715 /* Check if kswapd should be suspending */
3716 __fs_reclaim_release();
3717 ret = try_to_freeze();
3718 __fs_reclaim_acquire();
3719 if (ret || kthread_should_stop())
3723 * Raise priority if scanning rate is too low or there was no
3724 * progress in reclaiming pages
3726 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
3727 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
3730 * If reclaim made no progress for a boost, stop reclaim as
3731 * IO cannot be queued and it could be an infinite loop in
3732 * extreme circumstances.
3734 if (nr_boost_reclaim && !nr_reclaimed)
3737 if (raise_priority || !nr_reclaimed)
3739 } while (sc.priority >= 1);
3741 if (!sc.nr_reclaimed)
3742 pgdat->kswapd_failures++;
3745 /* If reclaim was boosted, account for the reclaim done in this pass */
3747 unsigned long flags;
3749 for (i = 0; i <= classzone_idx; i++) {
3750 if (!zone_boosts[i])
3753 /* Increments are under the zone lock */
3754 zone = pgdat->node_zones + i;
3755 spin_lock_irqsave(&zone->lock, flags);
3756 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
3757 spin_unlock_irqrestore(&zone->lock, flags);
3761 * As there is now likely space, wakeup kcompact to defragment
3764 wakeup_kcompactd(pgdat, pageblock_order, classzone_idx);
3767 snapshot_refaults(NULL, pgdat);
3768 __fs_reclaim_release();
3769 psi_memstall_leave(&pflags);
3770 set_task_reclaim_state(current, NULL);
3773 * Return the order kswapd stopped reclaiming at as
3774 * prepare_kswapd_sleep() takes it into account. If another caller
3775 * entered the allocator slow path while kswapd was awake, order will
3776 * remain at the higher level.
3782 * The pgdat->kswapd_classzone_idx is used to pass the highest zone index to be
3783 * reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is not
3784 * a valid index then either kswapd runs for first time or kswapd couldn't sleep
3785 * after previous reclaim attempt (node is still unbalanced). In that case
3786 * return the zone index of the previous kswapd reclaim cycle.
3788 static enum zone_type kswapd_classzone_idx(pg_data_t *pgdat,
3789 enum zone_type prev_classzone_idx)
3791 if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3792 return prev_classzone_idx;
3793 return pgdat->kswapd_classzone_idx;
3796 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
3797 unsigned int classzone_idx)
3802 if (freezing(current) || kthread_should_stop())
3805 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3808 * Try to sleep for a short interval. Note that kcompactd will only be
3809 * woken if it is possible to sleep for a short interval. This is
3810 * deliberate on the assumption that if reclaim cannot keep an
3811 * eligible zone balanced that it's also unlikely that compaction will
3814 if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3816 * Compaction records what page blocks it recently failed to
3817 * isolate pages from and skips them in the future scanning.
3818 * When kswapd is going to sleep, it is reasonable to assume
3819 * that pages and compaction may succeed so reset the cache.
3821 reset_isolation_suitable(pgdat);
3824 * We have freed the memory, now we should compact it to make
3825 * allocation of the requested order possible.
3827 wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
3829 remaining = schedule_timeout(HZ/10);
3832 * If woken prematurely then reset kswapd_classzone_idx and
3833 * order. The values will either be from a wakeup request or
3834 * the previous request that slept prematurely.
3837 pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
3838 pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
3841 finish_wait(&pgdat->kswapd_wait, &wait);
3842 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3846 * After a short sleep, check if it was a premature sleep. If not, then
3847 * go fully to sleep until explicitly woken up.
3850 prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3851 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3854 * vmstat counters are not perfectly accurate and the estimated
3855 * value for counters such as NR_FREE_PAGES can deviate from the
3856 * true value by nr_online_cpus * threshold. To avoid the zone
3857 * watermarks being breached while under pressure, we reduce the
3858 * per-cpu vmstat threshold while kswapd is awake and restore
3859 * them before going back to sleep.
3861 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
3863 if (!kthread_should_stop())
3866 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3869 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3871 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3873 finish_wait(&pgdat->kswapd_wait, &wait);
3877 * The background pageout daemon, started as a kernel thread
3878 * from the init process.
3880 * This basically trickles out pages so that we have _some_
3881 * free memory available even if there is no other activity
3882 * that frees anything up. This is needed for things like routing
3883 * etc, where we otherwise might have all activity going on in
3884 * asynchronous contexts that cannot page things out.
3886 * If there are applications that are active memory-allocators
3887 * (most normal use), this basically shouldn't matter.
3889 static int kswapd(void *p)
3891 unsigned int alloc_order, reclaim_order;
3892 unsigned int classzone_idx = MAX_NR_ZONES - 1;
3893 pg_data_t *pgdat = (pg_data_t*)p;
3894 struct task_struct *tsk = current;
3895 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
3897 if (!cpumask_empty(cpumask))
3898 set_cpus_allowed_ptr(tsk, cpumask);
3901 * Tell the memory management that we're a "memory allocator",
3902 * and that if we need more memory we should get access to it
3903 * regardless (see "__alloc_pages()"). "kswapd" should
3904 * never get caught in the normal page freeing logic.
3906 * (Kswapd normally doesn't need memory anyway, but sometimes
3907 * you need a small amount of memory in order to be able to
3908 * page out something else, and this flag essentially protects
3909 * us from recursively trying to free more memory as we're
3910 * trying to free the first piece of memory in the first place).
3912 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
3915 pgdat->kswapd_order = 0;
3916 pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
3920 alloc_order = reclaim_order = pgdat->kswapd_order;
3921 classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
3924 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
3927 /* Read the new order and classzone_idx */
3928 alloc_order = reclaim_order = pgdat->kswapd_order;
3929 classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
3930 pgdat->kswapd_order = 0;
3931 pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
3933 ret = try_to_freeze();
3934 if (kthread_should_stop())
3938 * We can speed up thawing tasks if we don't call balance_pgdat
3939 * after returning from the refrigerator
3945 * Reclaim begins at the requested order but if a high-order
3946 * reclaim fails then kswapd falls back to reclaiming for
3947 * order-0. If that happens, kswapd will consider sleeping
3948 * for the order it finished reclaiming at (reclaim_order)
3949 * but kcompactd is woken to compact for the original
3950 * request (alloc_order).
3952 trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
3954 reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
3955 if (reclaim_order < alloc_order)
3956 goto kswapd_try_sleep;
3959 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
3965 * A zone is low on free memory or too fragmented for high-order memory. If
3966 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
3967 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
3968 * has failed or is not needed, still wake up kcompactd if only compaction is
3971 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
3972 enum zone_type classzone_idx)
3976 if (!managed_zone(zone))
3979 if (!cpuset_zone_allowed(zone, gfp_flags))
3981 pgdat = zone->zone_pgdat;
3983 if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3984 pgdat->kswapd_classzone_idx = classzone_idx;
3986 pgdat->kswapd_classzone_idx = max(pgdat->kswapd_classzone_idx,
3988 pgdat->kswapd_order = max(pgdat->kswapd_order, order);
3989 if (!waitqueue_active(&pgdat->kswapd_wait))
3992 /* Hopeless node, leave it to direct reclaim if possible */
3993 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
3994 (pgdat_balanced(pgdat, order, classzone_idx) &&
3995 !pgdat_watermark_boosted(pgdat, classzone_idx))) {
3997 * There may be plenty of free memory available, but it's too
3998 * fragmented for high-order allocations. Wake up kcompactd
3999 * and rely on compaction_suitable() to determine if it's
4000 * needed. If it fails, it will defer subsequent attempts to
4001 * ratelimit its work.
4003 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
4004 wakeup_kcompactd(pgdat, order, classzone_idx);
4008 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, classzone_idx, order,
4010 wake_up_interruptible(&pgdat->kswapd_wait);
4013 #ifdef CONFIG_HIBERNATION
4015 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
4018 * Rather than trying to age LRUs the aim is to preserve the overall
4019 * LRU order by reclaiming preferentially
4020 * inactive > active > active referenced > active mapped
4022 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
4024 struct scan_control sc = {
4025 .nr_to_reclaim = nr_to_reclaim,
4026 .gfp_mask = GFP_HIGHUSER_MOVABLE,
4027 .reclaim_idx = MAX_NR_ZONES - 1,
4028 .priority = DEF_PRIORITY,
4032 .hibernation_mode = 1,
4034 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
4035 unsigned long nr_reclaimed;
4036 unsigned int noreclaim_flag;
4038 fs_reclaim_acquire(sc.gfp_mask);
4039 noreclaim_flag = memalloc_noreclaim_save();
4040 set_task_reclaim_state(current, &sc.reclaim_state);
4042 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4044 set_task_reclaim_state(current, NULL);
4045 memalloc_noreclaim_restore(noreclaim_flag);
4046 fs_reclaim_release(sc.gfp_mask);
4048 return nr_reclaimed;
4050 #endif /* CONFIG_HIBERNATION */
4052 /* It's optimal to keep kswapds on the same CPUs as their memory, but
4053 not required for correctness. So if the last cpu in a node goes
4054 away, we get changed to run anywhere: as the first one comes back,
4055 restore their cpu bindings. */
4056 static int kswapd_cpu_online(unsigned int cpu)
4060 for_each_node_state(nid, N_MEMORY) {
4061 pg_data_t *pgdat = NODE_DATA(nid);
4062 const struct cpumask *mask;
4064 mask = cpumask_of_node(pgdat->node_id);
4066 if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
4067 /* One of our CPUs online: restore mask */
4068 set_cpus_allowed_ptr(pgdat->kswapd, mask);
4074 * This kswapd start function will be called by init and node-hot-add.
4075 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
4077 int kswapd_run(int nid)
4079 pg_data_t *pgdat = NODE_DATA(nid);
4085 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
4086 if (IS_ERR(pgdat->kswapd)) {
4087 /* failure at boot is fatal */
4088 BUG_ON(system_state < SYSTEM_RUNNING);
4089 pr_err("Failed to start kswapd on node %d\n", nid);
4090 ret = PTR_ERR(pgdat->kswapd);
4091 pgdat->kswapd = NULL;
4097 * Called by memory hotplug when all memory in a node is offlined. Caller must
4098 * hold mem_hotplug_begin/end().
4100 void kswapd_stop(int nid)
4102 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
4105 kthread_stop(kswapd);
4106 NODE_DATA(nid)->kswapd = NULL;
4110 static int __init kswapd_init(void)
4115 for_each_node_state(nid, N_MEMORY)
4117 ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
4118 "mm/vmscan:online", kswapd_cpu_online,
4124 module_init(kswapd_init)
4130 * If non-zero call node_reclaim when the number of free pages falls below
4133 int node_reclaim_mode __read_mostly;
4135 #define RECLAIM_OFF 0
4136 #define RECLAIM_ZONE (1<<0) /* Run shrink_inactive_list on the zone */
4137 #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
4138 #define RECLAIM_UNMAP (1<<2) /* Unmap pages during reclaim */
4141 * Priority for NODE_RECLAIM. This determines the fraction of pages
4142 * of a node considered for each zone_reclaim. 4 scans 1/16th of
4145 #define NODE_RECLAIM_PRIORITY 4
4148 * Percentage of pages in a zone that must be unmapped for node_reclaim to
4151 int sysctl_min_unmapped_ratio = 1;
4154 * If the number of slab pages in a zone grows beyond this percentage then
4155 * slab reclaim needs to occur.
4157 int sysctl_min_slab_ratio = 5;
4159 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
4161 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
4162 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
4163 node_page_state(pgdat, NR_ACTIVE_FILE);
4166 * It's possible for there to be more file mapped pages than
4167 * accounted for by the pages on the file LRU lists because
4168 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
4170 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
4173 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4174 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
4176 unsigned long nr_pagecache_reclaimable;
4177 unsigned long delta = 0;
4180 * If RECLAIM_UNMAP is set, then all file pages are considered
4181 * potentially reclaimable. Otherwise, we have to worry about
4182 * pages like swapcache and node_unmapped_file_pages() provides
4185 if (node_reclaim_mode & RECLAIM_UNMAP)
4186 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
4188 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
4190 /* If we can't clean pages, remove dirty pages from consideration */
4191 if (!(node_reclaim_mode & RECLAIM_WRITE))
4192 delta += node_page_state(pgdat, NR_FILE_DIRTY);
4194 /* Watch for any possible underflows due to delta */
4195 if (unlikely(delta > nr_pagecache_reclaimable))
4196 delta = nr_pagecache_reclaimable;
4198 return nr_pagecache_reclaimable - delta;
4202 * Try to free up some pages from this node through reclaim.
4204 static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4206 /* Minimum pages needed in order to stay on node */
4207 const unsigned long nr_pages = 1 << order;
4208 struct task_struct *p = current;
4209 unsigned int noreclaim_flag;
4210 struct scan_control sc = {
4211 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4212 .gfp_mask = current_gfp_context(gfp_mask),
4214 .priority = NODE_RECLAIM_PRIORITY,
4215 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4216 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4218 .reclaim_idx = gfp_zone(gfp_mask),
4221 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4225 fs_reclaim_acquire(sc.gfp_mask);
4227 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4228 * and we also need to be able to write out pages for RECLAIM_WRITE
4229 * and RECLAIM_UNMAP.
4231 noreclaim_flag = memalloc_noreclaim_save();
4232 p->flags |= PF_SWAPWRITE;
4233 set_task_reclaim_state(p, &sc.reclaim_state);
4235 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
4237 * Free memory by calling shrink node with increasing
4238 * priorities until we have enough memory freed.
4241 shrink_node(pgdat, &sc);
4242 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
4245 set_task_reclaim_state(p, NULL);
4246 current->flags &= ~PF_SWAPWRITE;
4247 memalloc_noreclaim_restore(noreclaim_flag);
4248 fs_reclaim_release(sc.gfp_mask);
4250 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4252 return sc.nr_reclaimed >= nr_pages;
4255 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4260 * Node reclaim reclaims unmapped file backed pages and
4261 * slab pages if we are over the defined limits.
4263 * A small portion of unmapped file backed pages is needed for
4264 * file I/O otherwise pages read by file I/O will be immediately
4265 * thrown out if the node is overallocated. So we do not reclaim
4266 * if less than a specified percentage of the node is used by
4267 * unmapped file backed pages.
4269 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4270 node_page_state(pgdat, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
4271 return NODE_RECLAIM_FULL;
4274 * Do not scan if the allocation should not be delayed.
4276 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4277 return NODE_RECLAIM_NOSCAN;
4280 * Only run node reclaim on the local node or on nodes that do not
4281 * have associated processors. This will favor the local processor
4282 * over remote processors and spread off node memory allocations
4283 * as wide as possible.
4285 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4286 return NODE_RECLAIM_NOSCAN;
4288 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4289 return NODE_RECLAIM_NOSCAN;
4291 ret = __node_reclaim(pgdat, gfp_mask, order);
4292 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4295 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
4302 * page_evictable - test whether a page is evictable
4303 * @page: the page to test
4305 * Test whether page is evictable--i.e., should be placed on active/inactive
4306 * lists vs unevictable list.
4308 * Reasons page might not be evictable:
4309 * (1) page's mapping marked unevictable
4310 * (2) page is part of an mlocked VMA
4313 int page_evictable(struct page *page)
4317 /* Prevent address_space of inode and swap cache from being freed */
4319 ret = !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
4325 * check_move_unevictable_pages - check pages for evictability and move to
4326 * appropriate zone lru list
4327 * @pvec: pagevec with lru pages to check
4329 * Checks pages for evictability, if an evictable page is in the unevictable
4330 * lru list, moves it to the appropriate evictable lru list. This function
4331 * should be only used for lru pages.
4333 void check_move_unevictable_pages(struct pagevec *pvec)
4335 struct lruvec *lruvec;
4336 struct pglist_data *pgdat = NULL;
4341 for (i = 0; i < pvec->nr; i++) {
4342 struct page *page = pvec->pages[i];
4343 struct pglist_data *pagepgdat = page_pgdat(page);
4346 if (pagepgdat != pgdat) {
4348 spin_unlock_irq(&pgdat->lru_lock);
4350 spin_lock_irq(&pgdat->lru_lock);
4352 lruvec = mem_cgroup_page_lruvec(page, pgdat);
4354 if (!PageLRU(page) || !PageUnevictable(page))
4357 if (page_evictable(page)) {
4358 enum lru_list lru = page_lru_base_type(page);
4360 VM_BUG_ON_PAGE(PageActive(page), page);
4361 ClearPageUnevictable(page);
4362 del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
4363 add_page_to_lru_list(page, lruvec, lru);
4369 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
4370 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
4371 spin_unlock_irq(&pgdat->lru_lock);
4374 EXPORT_SYMBOL_GPL(check_move_unevictable_pages);