xref: /openbmc/linux/mm/vmscan.c (revision aa48e47e3906c332eaf1e5d7b58be11d3509ad9f)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  *  Swap reorganised 29.12.95, Stephen Tweedie.
61da177e4SLinus Torvalds  *  kswapd added: 7.1.96  sct
71da177e4SLinus Torvalds  *  Removed kswapd_ctl limits, and swap out as many pages as needed
81da177e4SLinus Torvalds  *  to bring the system back to freepages.high: 2.4.97, Rik van Riel.
91da177e4SLinus Torvalds  *  Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
101da177e4SLinus Torvalds  *  Multiqueue VM started 5.8.00, Rik van Riel.
111da177e4SLinus Torvalds  */
121da177e4SLinus Torvalds 
13b1de0d13SMitchel Humpherys #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14b1de0d13SMitchel Humpherys 
151da177e4SLinus Torvalds #include <linux/mm.h>
165b3cc15aSIngo Molnar #include <linux/sched/mm.h>
171da177e4SLinus Torvalds #include <linux/module.h>
185a0e3ad6STejun Heo #include <linux/gfp.h>
191da177e4SLinus Torvalds #include <linux/kernel_stat.h>
201da177e4SLinus Torvalds #include <linux/swap.h>
211da177e4SLinus Torvalds #include <linux/pagemap.h>
221da177e4SLinus Torvalds #include <linux/init.h>
231da177e4SLinus Torvalds #include <linux/highmem.h>
2470ddf637SAnton Vorontsov #include <linux/vmpressure.h>
25e129b5c2SAndrew Morton #include <linux/vmstat.h>
261da177e4SLinus Torvalds #include <linux/file.h>
271da177e4SLinus Torvalds #include <linux/writeback.h>
281da177e4SLinus Torvalds #include <linux/blkdev.h>
291da177e4SLinus Torvalds #include <linux/buffer_head.h>	/* for try_to_release_page(),
301da177e4SLinus Torvalds 					buffer_heads_over_limit */
311da177e4SLinus Torvalds #include <linux/mm_inline.h>
321da177e4SLinus Torvalds #include <linux/backing-dev.h>
331da177e4SLinus Torvalds #include <linux/rmap.h>
341da177e4SLinus Torvalds #include <linux/topology.h>
351da177e4SLinus Torvalds #include <linux/cpu.h>
361da177e4SLinus Torvalds #include <linux/cpuset.h>
373e7d3449SMel Gorman #include <linux/compaction.h>
381da177e4SLinus Torvalds #include <linux/notifier.h>
391da177e4SLinus Torvalds #include <linux/rwsem.h>
40248a0301SRafael J. Wysocki #include <linux/delay.h>
413218ae14SYasunori Goto #include <linux/kthread.h>
427dfb7103SNigel Cunningham #include <linux/freezer.h>
4366e1707bSBalbir Singh #include <linux/memcontrol.h>
44873b4771SKeika Kobayashi #include <linux/delayacct.h>
45af936a16SLee Schermerhorn #include <linux/sysctl.h>
46929bea7cSKOSAKI Motohiro #include <linux/oom.h>
4764e3d12fSKuo-Hsin Yang #include <linux/pagevec.h>
48268bb0ceSLinus Torvalds #include <linux/prefetch.h>
49b1de0d13SMitchel Humpherys #include <linux/printk.h>
50f9fe48beSRoss Zwisler #include <linux/dax.h>
51eb414681SJohannes Weiner #include <linux/psi.h>
521da177e4SLinus Torvalds 
531da177e4SLinus Torvalds #include <asm/tlbflush.h>
541da177e4SLinus Torvalds #include <asm/div64.h>
551da177e4SLinus Torvalds 
561da177e4SLinus Torvalds #include <linux/swapops.h>
57117aad1eSRafael Aquini #include <linux/balloon_compaction.h>
581da177e4SLinus Torvalds 
590f8053a5SNick Piggin #include "internal.h"
600f8053a5SNick Piggin 
6133906bc5SMel Gorman #define CREATE_TRACE_POINTS
6233906bc5SMel Gorman #include <trace/events/vmscan.h>
6333906bc5SMel Gorman 
641da177e4SLinus Torvalds struct scan_control {
6522fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6622fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
6722fba335SKOSAKI Motohiro 
68ee814fe2SJohannes Weiner 	/*
69ee814fe2SJohannes Weiner 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
70ee814fe2SJohannes Weiner 	 * are scanned.
71ee814fe2SJohannes Weiner 	 */
72ee814fe2SJohannes Weiner 	nodemask_t	*nodemask;
739e3b2f8cSKonstantin Khlebnikov 
745f53e762SKOSAKI Motohiro 	/*
75f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
76f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
77f16015fbSJohannes Weiner 	 */
78f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
7966e1707bSBalbir Singh 
807cf111bcSJohannes Weiner 	/*
817cf111bcSJohannes Weiner 	 * Scan pressure balancing between anon and file LRUs
827cf111bcSJohannes Weiner 	 */
837cf111bcSJohannes Weiner 	unsigned long	anon_cost;
847cf111bcSJohannes Weiner 	unsigned long	file_cost;
857cf111bcSJohannes Weiner 
86b91ac374SJohannes Weiner 	/* Can active pages be deactivated as part of reclaim? */
87b91ac374SJohannes Weiner #define DEACTIVATE_ANON 1
88b91ac374SJohannes Weiner #define DEACTIVATE_FILE 2
89b91ac374SJohannes Weiner 	unsigned int may_deactivate:2;
90b91ac374SJohannes Weiner 	unsigned int force_deactivate:1;
91b91ac374SJohannes Weiner 	unsigned int skipped_deactivate:1;
92b91ac374SJohannes Weiner 
931276ad68SJohannes Weiner 	/* Writepage batching in laptop mode; RECLAIM_WRITE */
94ee814fe2SJohannes Weiner 	unsigned int may_writepage:1;
95ee814fe2SJohannes Weiner 
96ee814fe2SJohannes Weiner 	/* Can mapped pages be reclaimed? */
97ee814fe2SJohannes Weiner 	unsigned int may_unmap:1;
98ee814fe2SJohannes Weiner 
99ee814fe2SJohannes Weiner 	/* Can pages be swapped as part of reclaim? */
100ee814fe2SJohannes Weiner 	unsigned int may_swap:1;
101ee814fe2SJohannes Weiner 
102d6622f63SYisheng Xie 	/*
103f56ce412SJohannes Weiner 	 * Cgroup memory below memory.low is protected as long as we
104f56ce412SJohannes Weiner 	 * don't threaten to OOM. If any cgroup is reclaimed at
105f56ce412SJohannes Weiner 	 * reduced force or passed over entirely due to its memory.low
106f56ce412SJohannes Weiner 	 * setting (memcg_low_skipped), and nothing is reclaimed as a
107f56ce412SJohannes Weiner 	 * result, then go back for one more cycle that reclaims the protected
108f56ce412SJohannes Weiner 	 * memory (memcg_low_reclaim) to avert OOM.
109d6622f63SYisheng Xie 	 */
110d6622f63SYisheng Xie 	unsigned int memcg_low_reclaim:1;
111d6622f63SYisheng Xie 	unsigned int memcg_low_skipped:1;
112241994edSJohannes Weiner 
113ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
114ee814fe2SJohannes Weiner 
115ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
116ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
117ee814fe2SJohannes Weiner 
118b91ac374SJohannes Weiner 	/* There is easily reclaimable cold cache in the current node */
119b91ac374SJohannes Weiner 	unsigned int cache_trim_mode:1;
120b91ac374SJohannes Weiner 
12153138ceaSJohannes Weiner 	/* The file pages on the current node are dangerously low */
12253138ceaSJohannes Weiner 	unsigned int file_is_tiny:1;
12353138ceaSJohannes Weiner 
124bb451fdfSGreg Thelen 	/* Allocation order */
125bb451fdfSGreg Thelen 	s8 order;
126bb451fdfSGreg Thelen 
127bb451fdfSGreg Thelen 	/* Scan (total_size >> priority) pages at once */
128bb451fdfSGreg Thelen 	s8 priority;
129bb451fdfSGreg Thelen 
130bb451fdfSGreg Thelen 	/* The highest zone to isolate pages for reclaim from */
131bb451fdfSGreg Thelen 	s8 reclaim_idx;
132bb451fdfSGreg Thelen 
133bb451fdfSGreg Thelen 	/* This context's GFP mask */
134bb451fdfSGreg Thelen 	gfp_t gfp_mask;
135bb451fdfSGreg Thelen 
136ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
137ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
138ee814fe2SJohannes Weiner 
139ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
140ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
141d108c772SAndrey Ryabinin 
142d108c772SAndrey Ryabinin 	struct {
143d108c772SAndrey Ryabinin 		unsigned int dirty;
144d108c772SAndrey Ryabinin 		unsigned int unqueued_dirty;
145d108c772SAndrey Ryabinin 		unsigned int congested;
146d108c772SAndrey Ryabinin 		unsigned int writeback;
147d108c772SAndrey Ryabinin 		unsigned int immediate;
148d108c772SAndrey Ryabinin 		unsigned int file_taken;
149d108c772SAndrey Ryabinin 		unsigned int taken;
150d108c772SAndrey Ryabinin 	} nr;
151e5ca8071SYafang Shao 
152e5ca8071SYafang Shao 	/* for recording the reclaimed slab by now */
153e5ca8071SYafang Shao 	struct reclaim_state reclaim_state;
1541da177e4SLinus Torvalds };
1551da177e4SLinus Torvalds 
1561da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1571da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1581da177e4SLinus Torvalds 	do {								\
1591da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1601da177e4SLinus Torvalds 			struct page *prev;				\
1611da177e4SLinus Torvalds 									\
1621da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1631da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1641da177e4SLinus Torvalds 		}							\
1651da177e4SLinus Torvalds 	} while (0)
1661da177e4SLinus Torvalds #else
1671da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1681da177e4SLinus Torvalds #endif
1691da177e4SLinus Torvalds 
1701da177e4SLinus Torvalds /*
171c843966cSJohannes Weiner  * From 0 .. 200.  Higher means more swappy.
1721da177e4SLinus Torvalds  */
1731da177e4SLinus Torvalds int vm_swappiness = 60;
1741da177e4SLinus Torvalds 
1750a432dcbSYang Shi static void set_task_reclaim_state(struct task_struct *task,
1760a432dcbSYang Shi 				   struct reclaim_state *rs)
1770a432dcbSYang Shi {
1780a432dcbSYang Shi 	/* Check for an overwrite */
1790a432dcbSYang Shi 	WARN_ON_ONCE(rs && task->reclaim_state);
1800a432dcbSYang Shi 
1810a432dcbSYang Shi 	/* Check for the nulling of an already-nulled member */
1820a432dcbSYang Shi 	WARN_ON_ONCE(!rs && !task->reclaim_state);
1830a432dcbSYang Shi 
1840a432dcbSYang Shi 	task->reclaim_state = rs;
1850a432dcbSYang Shi }
1860a432dcbSYang Shi 
1871da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1881da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1891da177e4SLinus Torvalds 
1900a432dcbSYang Shi #ifdef CONFIG_MEMCG
191a2fb1261SYang Shi static int shrinker_nr_max;
1922bfd3637SYang Shi 
1933c6f17e6SYang Shi /* The shrinker_info is expanded in a batch of BITS_PER_LONG */
194a2fb1261SYang Shi static inline int shrinker_map_size(int nr_items)
195a2fb1261SYang Shi {
196a2fb1261SYang Shi 	return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
197a2fb1261SYang Shi }
1982bfd3637SYang Shi 
1993c6f17e6SYang Shi static inline int shrinker_defer_size(int nr_items)
2003c6f17e6SYang Shi {
2013c6f17e6SYang Shi 	return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
2023c6f17e6SYang Shi }
2033c6f17e6SYang Shi 
204468ab843SYang Shi static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
205468ab843SYang Shi 						     int nid)
206468ab843SYang Shi {
207468ab843SYang Shi 	return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
208468ab843SYang Shi 					 lockdep_is_held(&shrinker_rwsem));
209468ab843SYang Shi }
210468ab843SYang Shi 
211e4262c4fSYang Shi static int expand_one_shrinker_info(struct mem_cgroup *memcg,
2123c6f17e6SYang Shi 				    int map_size, int defer_size,
2133c6f17e6SYang Shi 				    int old_map_size, int old_defer_size)
2142bfd3637SYang Shi {
215e4262c4fSYang Shi 	struct shrinker_info *new, *old;
2162bfd3637SYang Shi 	struct mem_cgroup_per_node *pn;
2172bfd3637SYang Shi 	int nid;
2183c6f17e6SYang Shi 	int size = map_size + defer_size;
2192bfd3637SYang Shi 
2202bfd3637SYang Shi 	for_each_node(nid) {
2212bfd3637SYang Shi 		pn = memcg->nodeinfo[nid];
222468ab843SYang Shi 		old = shrinker_info_protected(memcg, nid);
2232bfd3637SYang Shi 		/* Not yet online memcg */
2242bfd3637SYang Shi 		if (!old)
2252bfd3637SYang Shi 			return 0;
2262bfd3637SYang Shi 
2272bfd3637SYang Shi 		new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
2282bfd3637SYang Shi 		if (!new)
2292bfd3637SYang Shi 			return -ENOMEM;
2302bfd3637SYang Shi 
2313c6f17e6SYang Shi 		new->nr_deferred = (atomic_long_t *)(new + 1);
2323c6f17e6SYang Shi 		new->map = (void *)new->nr_deferred + defer_size;
2333c6f17e6SYang Shi 
2343c6f17e6SYang Shi 		/* map: set all old bits, clear all new bits */
2353c6f17e6SYang Shi 		memset(new->map, (int)0xff, old_map_size);
2363c6f17e6SYang Shi 		memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
2373c6f17e6SYang Shi 		/* nr_deferred: copy old values, clear all new values */
2383c6f17e6SYang Shi 		memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
2393c6f17e6SYang Shi 		memset((void *)new->nr_deferred + old_defer_size, 0,
2403c6f17e6SYang Shi 		       defer_size - old_defer_size);
2412bfd3637SYang Shi 
242e4262c4fSYang Shi 		rcu_assign_pointer(pn->shrinker_info, new);
24372673e86SYang Shi 		kvfree_rcu(old, rcu);
2442bfd3637SYang Shi 	}
2452bfd3637SYang Shi 
2462bfd3637SYang Shi 	return 0;
2472bfd3637SYang Shi }
2482bfd3637SYang Shi 
249e4262c4fSYang Shi void free_shrinker_info(struct mem_cgroup *memcg)
2502bfd3637SYang Shi {
2512bfd3637SYang Shi 	struct mem_cgroup_per_node *pn;
252e4262c4fSYang Shi 	struct shrinker_info *info;
2532bfd3637SYang Shi 	int nid;
2542bfd3637SYang Shi 
2552bfd3637SYang Shi 	for_each_node(nid) {
2562bfd3637SYang Shi 		pn = memcg->nodeinfo[nid];
257e4262c4fSYang Shi 		info = rcu_dereference_protected(pn->shrinker_info, true);
258e4262c4fSYang Shi 		kvfree(info);
259e4262c4fSYang Shi 		rcu_assign_pointer(pn->shrinker_info, NULL);
2602bfd3637SYang Shi 	}
2612bfd3637SYang Shi }
2622bfd3637SYang Shi 
263e4262c4fSYang Shi int alloc_shrinker_info(struct mem_cgroup *memcg)
2642bfd3637SYang Shi {
265e4262c4fSYang Shi 	struct shrinker_info *info;
2662bfd3637SYang Shi 	int nid, size, ret = 0;
2673c6f17e6SYang Shi 	int map_size, defer_size = 0;
2682bfd3637SYang Shi 
269d27cf2aaSYang Shi 	down_write(&shrinker_rwsem);
2703c6f17e6SYang Shi 	map_size = shrinker_map_size(shrinker_nr_max);
2713c6f17e6SYang Shi 	defer_size = shrinker_defer_size(shrinker_nr_max);
2723c6f17e6SYang Shi 	size = map_size + defer_size;
2732bfd3637SYang Shi 	for_each_node(nid) {
274e4262c4fSYang Shi 		info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
275e4262c4fSYang Shi 		if (!info) {
276e4262c4fSYang Shi 			free_shrinker_info(memcg);
2772bfd3637SYang Shi 			ret = -ENOMEM;
2782bfd3637SYang Shi 			break;
2792bfd3637SYang Shi 		}
2803c6f17e6SYang Shi 		info->nr_deferred = (atomic_long_t *)(info + 1);
2813c6f17e6SYang Shi 		info->map = (void *)info->nr_deferred + defer_size;
282e4262c4fSYang Shi 		rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
2832bfd3637SYang Shi 	}
284d27cf2aaSYang Shi 	up_write(&shrinker_rwsem);
2852bfd3637SYang Shi 
2862bfd3637SYang Shi 	return ret;
2872bfd3637SYang Shi }
2882bfd3637SYang Shi 
2893c6f17e6SYang Shi static inline bool need_expand(int nr_max)
2903c6f17e6SYang Shi {
2913c6f17e6SYang Shi 	return round_up(nr_max, BITS_PER_LONG) >
2923c6f17e6SYang Shi 	       round_up(shrinker_nr_max, BITS_PER_LONG);
2933c6f17e6SYang Shi }
2943c6f17e6SYang Shi 
295e4262c4fSYang Shi static int expand_shrinker_info(int new_id)
2962bfd3637SYang Shi {
2973c6f17e6SYang Shi 	int ret = 0;
298a2fb1261SYang Shi 	int new_nr_max = new_id + 1;
2993c6f17e6SYang Shi 	int map_size, defer_size = 0;
3003c6f17e6SYang Shi 	int old_map_size, old_defer_size = 0;
3012bfd3637SYang Shi 	struct mem_cgroup *memcg;
3022bfd3637SYang Shi 
3033c6f17e6SYang Shi 	if (!need_expand(new_nr_max))
304a2fb1261SYang Shi 		goto out;
3052bfd3637SYang Shi 
3062bfd3637SYang Shi 	if (!root_mem_cgroup)
307d27cf2aaSYang Shi 		goto out;
308d27cf2aaSYang Shi 
309d27cf2aaSYang Shi 	lockdep_assert_held(&shrinker_rwsem);
3102bfd3637SYang Shi 
3113c6f17e6SYang Shi 	map_size = shrinker_map_size(new_nr_max);
3123c6f17e6SYang Shi 	defer_size = shrinker_defer_size(new_nr_max);
3133c6f17e6SYang Shi 	old_map_size = shrinker_map_size(shrinker_nr_max);
3143c6f17e6SYang Shi 	old_defer_size = shrinker_defer_size(shrinker_nr_max);
3153c6f17e6SYang Shi 
3162bfd3637SYang Shi 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3172bfd3637SYang Shi 	do {
3183c6f17e6SYang Shi 		ret = expand_one_shrinker_info(memcg, map_size, defer_size,
3193c6f17e6SYang Shi 					       old_map_size, old_defer_size);
3202bfd3637SYang Shi 		if (ret) {
3212bfd3637SYang Shi 			mem_cgroup_iter_break(NULL, memcg);
322d27cf2aaSYang Shi 			goto out;
3232bfd3637SYang Shi 		}
3242bfd3637SYang Shi 	} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
325d27cf2aaSYang Shi out:
3262bfd3637SYang Shi 	if (!ret)
327a2fb1261SYang Shi 		shrinker_nr_max = new_nr_max;
328d27cf2aaSYang Shi 
3292bfd3637SYang Shi 	return ret;
3302bfd3637SYang Shi }
3312bfd3637SYang Shi 
3322bfd3637SYang Shi void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
3332bfd3637SYang Shi {
3342bfd3637SYang Shi 	if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
335e4262c4fSYang Shi 		struct shrinker_info *info;
3362bfd3637SYang Shi 
3372bfd3637SYang Shi 		rcu_read_lock();
338e4262c4fSYang Shi 		info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
3392bfd3637SYang Shi 		/* Pairs with smp mb in shrink_slab() */
3402bfd3637SYang Shi 		smp_mb__before_atomic();
341e4262c4fSYang Shi 		set_bit(shrinker_id, info->map);
3422bfd3637SYang Shi 		rcu_read_unlock();
3432bfd3637SYang Shi 	}
3442bfd3637SYang Shi }
3452bfd3637SYang Shi 
346b4c2b231SKirill Tkhai static DEFINE_IDR(shrinker_idr);
347b4c2b231SKirill Tkhai 
348b4c2b231SKirill Tkhai static int prealloc_memcg_shrinker(struct shrinker *shrinker)
349b4c2b231SKirill Tkhai {
350b4c2b231SKirill Tkhai 	int id, ret = -ENOMEM;
351b4c2b231SKirill Tkhai 
352476b30a0SYang Shi 	if (mem_cgroup_disabled())
353476b30a0SYang Shi 		return -ENOSYS;
354476b30a0SYang Shi 
355b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
356b4c2b231SKirill Tkhai 	/* This may call shrinker, so it must use down_read_trylock() */
35741ca668aSYang Shi 	id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
358b4c2b231SKirill Tkhai 	if (id < 0)
359b4c2b231SKirill Tkhai 		goto unlock;
360b4c2b231SKirill Tkhai 
3610a4465d3SKirill Tkhai 	if (id >= shrinker_nr_max) {
362e4262c4fSYang Shi 		if (expand_shrinker_info(id)) {
3630a4465d3SKirill Tkhai 			idr_remove(&shrinker_idr, id);
3640a4465d3SKirill Tkhai 			goto unlock;
3650a4465d3SKirill Tkhai 		}
3660a4465d3SKirill Tkhai 	}
367b4c2b231SKirill Tkhai 	shrinker->id = id;
368b4c2b231SKirill Tkhai 	ret = 0;
369b4c2b231SKirill Tkhai unlock:
370b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
371b4c2b231SKirill Tkhai 	return ret;
372b4c2b231SKirill Tkhai }
373b4c2b231SKirill Tkhai 
374b4c2b231SKirill Tkhai static void unregister_memcg_shrinker(struct shrinker *shrinker)
375b4c2b231SKirill Tkhai {
376b4c2b231SKirill Tkhai 	int id = shrinker->id;
377b4c2b231SKirill Tkhai 
378b4c2b231SKirill Tkhai 	BUG_ON(id < 0);
379b4c2b231SKirill Tkhai 
38041ca668aSYang Shi 	lockdep_assert_held(&shrinker_rwsem);
38141ca668aSYang Shi 
382b4c2b231SKirill Tkhai 	idr_remove(&shrinker_idr, id);
383b4c2b231SKirill Tkhai }
384b4c2b231SKirill Tkhai 
38586750830SYang Shi static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
38686750830SYang Shi 				   struct mem_cgroup *memcg)
38786750830SYang Shi {
38886750830SYang Shi 	struct shrinker_info *info;
38986750830SYang Shi 
39086750830SYang Shi 	info = shrinker_info_protected(memcg, nid);
39186750830SYang Shi 	return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
39286750830SYang Shi }
39386750830SYang Shi 
39486750830SYang Shi static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
39586750830SYang Shi 				  struct mem_cgroup *memcg)
39686750830SYang Shi {
39786750830SYang Shi 	struct shrinker_info *info;
39886750830SYang Shi 
39986750830SYang Shi 	info = shrinker_info_protected(memcg, nid);
40086750830SYang Shi 	return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
40186750830SYang Shi }
40286750830SYang Shi 
403a178015cSYang Shi void reparent_shrinker_deferred(struct mem_cgroup *memcg)
404a178015cSYang Shi {
405a178015cSYang Shi 	int i, nid;
406a178015cSYang Shi 	long nr;
407a178015cSYang Shi 	struct mem_cgroup *parent;
408a178015cSYang Shi 	struct shrinker_info *child_info, *parent_info;
409a178015cSYang Shi 
410a178015cSYang Shi 	parent = parent_mem_cgroup(memcg);
411a178015cSYang Shi 	if (!parent)
412a178015cSYang Shi 		parent = root_mem_cgroup;
413a178015cSYang Shi 
414a178015cSYang Shi 	/* Prevent from concurrent shrinker_info expand */
415a178015cSYang Shi 	down_read(&shrinker_rwsem);
416a178015cSYang Shi 	for_each_node(nid) {
417a178015cSYang Shi 		child_info = shrinker_info_protected(memcg, nid);
418a178015cSYang Shi 		parent_info = shrinker_info_protected(parent, nid);
419a178015cSYang Shi 		for (i = 0; i < shrinker_nr_max; i++) {
420a178015cSYang Shi 			nr = atomic_long_read(&child_info->nr_deferred[i]);
421a178015cSYang Shi 			atomic_long_add(nr, &parent_info->nr_deferred[i]);
422a178015cSYang Shi 		}
423a178015cSYang Shi 	}
424a178015cSYang Shi 	up_read(&shrinker_rwsem);
425a178015cSYang Shi }
426a178015cSYang Shi 
427b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
42889b5fae5SJohannes Weiner {
429b5ead35eSJohannes Weiner 	return sc->target_mem_cgroup;
43089b5fae5SJohannes Weiner }
43197c9341fSTejun Heo 
43297c9341fSTejun Heo /**
433b5ead35eSJohannes Weiner  * writeback_throttling_sane - is the usual dirty throttling mechanism available?
43497c9341fSTejun Heo  * @sc: scan_control in question
43597c9341fSTejun Heo  *
43697c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
43797c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
43897c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
43997c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
44097c9341fSTejun Heo  * allocation and configurability.
44197c9341fSTejun Heo  *
44297c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
44397c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
44497c9341fSTejun Heo  */
445b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
44697c9341fSTejun Heo {
447b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
44897c9341fSTejun Heo 		return true;
44997c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
45069234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
45197c9341fSTejun Heo 		return true;
45297c9341fSTejun Heo #endif
45397c9341fSTejun Heo 	return false;
45497c9341fSTejun Heo }
45591a45470SKAMEZAWA Hiroyuki #else
4560a432dcbSYang Shi static int prealloc_memcg_shrinker(struct shrinker *shrinker)
4570a432dcbSYang Shi {
458476b30a0SYang Shi 	return -ENOSYS;
4590a432dcbSYang Shi }
4600a432dcbSYang Shi 
4610a432dcbSYang Shi static void unregister_memcg_shrinker(struct shrinker *shrinker)
4620a432dcbSYang Shi {
4630a432dcbSYang Shi }
4640a432dcbSYang Shi 
46586750830SYang Shi static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
46686750830SYang Shi 				   struct mem_cgroup *memcg)
46786750830SYang Shi {
46886750830SYang Shi 	return 0;
46986750830SYang Shi }
47086750830SYang Shi 
47186750830SYang Shi static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
47286750830SYang Shi 				  struct mem_cgroup *memcg)
47386750830SYang Shi {
47486750830SYang Shi 	return 0;
47586750830SYang Shi }
47686750830SYang Shi 
477b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
47889b5fae5SJohannes Weiner {
479b5ead35eSJohannes Weiner 	return false;
48089b5fae5SJohannes Weiner }
48197c9341fSTejun Heo 
482b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
48397c9341fSTejun Heo {
48497c9341fSTejun Heo 	return true;
48597c9341fSTejun Heo }
48691a45470SKAMEZAWA Hiroyuki #endif
48791a45470SKAMEZAWA Hiroyuki 
48886750830SYang Shi static long xchg_nr_deferred(struct shrinker *shrinker,
48986750830SYang Shi 			     struct shrink_control *sc)
49086750830SYang Shi {
49186750830SYang Shi 	int nid = sc->nid;
49286750830SYang Shi 
49386750830SYang Shi 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
49486750830SYang Shi 		nid = 0;
49586750830SYang Shi 
49686750830SYang Shi 	if (sc->memcg &&
49786750830SYang Shi 	    (shrinker->flags & SHRINKER_MEMCG_AWARE))
49886750830SYang Shi 		return xchg_nr_deferred_memcg(nid, shrinker,
49986750830SYang Shi 					      sc->memcg);
50086750830SYang Shi 
50186750830SYang Shi 	return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
50286750830SYang Shi }
50386750830SYang Shi 
50486750830SYang Shi 
50586750830SYang Shi static long add_nr_deferred(long nr, struct shrinker *shrinker,
50686750830SYang Shi 			    struct shrink_control *sc)
50786750830SYang Shi {
50886750830SYang Shi 	int nid = sc->nid;
50986750830SYang Shi 
51086750830SYang Shi 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
51186750830SYang Shi 		nid = 0;
51286750830SYang Shi 
51386750830SYang Shi 	if (sc->memcg &&
51486750830SYang Shi 	    (shrinker->flags & SHRINKER_MEMCG_AWARE))
51586750830SYang Shi 		return add_nr_deferred_memcg(nr, nid, shrinker,
51686750830SYang Shi 					     sc->memcg);
51786750830SYang Shi 
51886750830SYang Shi 	return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
51986750830SYang Shi }
52086750830SYang Shi 
5215a1c84b4SMel Gorman /*
5225a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
5235a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
5245a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
5255a1c84b4SMel Gorman  */
5265a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
5275a1c84b4SMel Gorman {
5285a1c84b4SMel Gorman 	unsigned long nr;
5295a1c84b4SMel Gorman 
5305a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
5315a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
5325a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
5335a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
5345a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
5355a1c84b4SMel Gorman 
5365a1c84b4SMel Gorman 	return nr;
5375a1c84b4SMel Gorman }
5385a1c84b4SMel Gorman 
539fd538803SMichal Hocko /**
540fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
541fd538803SMichal Hocko  * @lruvec: lru vector
542fd538803SMichal Hocko  * @lru: lru to use
543fd538803SMichal Hocko  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
544fd538803SMichal Hocko  */
5452091339dSYu Zhao static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
5462091339dSYu Zhao 				     int zone_idx)
547c9f299d9SKOSAKI Motohiro {
548de3b0150SJohannes Weiner 	unsigned long size = 0;
549fd538803SMichal Hocko 	int zid;
550a3d8e054SKOSAKI Motohiro 
551de3b0150SJohannes Weiner 	for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
552fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
553fd538803SMichal Hocko 
554fd538803SMichal Hocko 		if (!managed_zone(zone))
555fd538803SMichal Hocko 			continue;
556fd538803SMichal Hocko 
557fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
558de3b0150SJohannes Weiner 			size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
559fd538803SMichal Hocko 		else
560de3b0150SJohannes Weiner 			size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
561c9f299d9SKOSAKI Motohiro 	}
562de3b0150SJohannes Weiner 	return size;
563b4536f0cSMichal Hocko }
564b4536f0cSMichal Hocko 
5651da177e4SLinus Torvalds /*
5661d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
5671da177e4SLinus Torvalds  */
5688e04944fSTetsuo Handa int prealloc_shrinker(struct shrinker *shrinker)
5691da177e4SLinus Torvalds {
570476b30a0SYang Shi 	unsigned int size;
571476b30a0SYang Shi 	int err;
5721d3d4437SGlauber Costa 
573476b30a0SYang Shi 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
574476b30a0SYang Shi 		err = prealloc_memcg_shrinker(shrinker);
575476b30a0SYang Shi 		if (err != -ENOSYS)
576476b30a0SYang Shi 			return err;
577476b30a0SYang Shi 
578476b30a0SYang Shi 		shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
579476b30a0SYang Shi 	}
580476b30a0SYang Shi 
581476b30a0SYang Shi 	size = sizeof(*shrinker->nr_deferred);
5821d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
5831d3d4437SGlauber Costa 		size *= nr_node_ids;
5841d3d4437SGlauber Costa 
5851d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
5861d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
5871d3d4437SGlauber Costa 		return -ENOMEM;
588b4c2b231SKirill Tkhai 
5898e04944fSTetsuo Handa 	return 0;
5908e04944fSTetsuo Handa }
5911d3d4437SGlauber Costa 
5928e04944fSTetsuo Handa void free_prealloced_shrinker(struct shrinker *shrinker)
5938e04944fSTetsuo Handa {
59441ca668aSYang Shi 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
59541ca668aSYang Shi 		down_write(&shrinker_rwsem);
596b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
59741ca668aSYang Shi 		up_write(&shrinker_rwsem);
598476b30a0SYang Shi 		return;
59941ca668aSYang Shi 	}
600b4c2b231SKirill Tkhai 
6018e04944fSTetsuo Handa 	kfree(shrinker->nr_deferred);
6028e04944fSTetsuo Handa 	shrinker->nr_deferred = NULL;
6038e04944fSTetsuo Handa }
6048e04944fSTetsuo Handa 
6058e04944fSTetsuo Handa void register_shrinker_prepared(struct shrinker *shrinker)
6068e04944fSTetsuo Handa {
6071da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
6081da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
60941ca668aSYang Shi 	shrinker->flags |= SHRINKER_REGISTERED;
6101da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
6118e04944fSTetsuo Handa }
6128e04944fSTetsuo Handa 
6138e04944fSTetsuo Handa int register_shrinker(struct shrinker *shrinker)
6148e04944fSTetsuo Handa {
6158e04944fSTetsuo Handa 	int err = prealloc_shrinker(shrinker);
6168e04944fSTetsuo Handa 
6178e04944fSTetsuo Handa 	if (err)
6188e04944fSTetsuo Handa 		return err;
6198e04944fSTetsuo Handa 	register_shrinker_prepared(shrinker);
6201d3d4437SGlauber Costa 	return 0;
6211da177e4SLinus Torvalds }
6228e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
6231da177e4SLinus Torvalds 
6241da177e4SLinus Torvalds /*
6251da177e4SLinus Torvalds  * Remove one
6261da177e4SLinus Torvalds  */
6278e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
6281da177e4SLinus Torvalds {
62941ca668aSYang Shi 	if (!(shrinker->flags & SHRINKER_REGISTERED))
630bb422a73STetsuo Handa 		return;
63141ca668aSYang Shi 
6321da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
6331da177e4SLinus Torvalds 	list_del(&shrinker->list);
63441ca668aSYang Shi 	shrinker->flags &= ~SHRINKER_REGISTERED;
63541ca668aSYang Shi 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
63641ca668aSYang Shi 		unregister_memcg_shrinker(shrinker);
6371da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
63841ca668aSYang Shi 
639ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
640bb422a73STetsuo Handa 	shrinker->nr_deferred = NULL;
6411da177e4SLinus Torvalds }
6428e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
6431da177e4SLinus Torvalds 
6441da177e4SLinus Torvalds #define SHRINK_BATCH 128
6451d3d4437SGlauber Costa 
646cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
6479092c71bSJosef Bacik 				    struct shrinker *shrinker, int priority)
6481da177e4SLinus Torvalds {
64924f7c6b9SDave Chinner 	unsigned long freed = 0;
6501da177e4SLinus Torvalds 	unsigned long long delta;
651635697c6SKonstantin Khlebnikov 	long total_scan;
652d5bc5fd3SVladimir Davydov 	long freeable;
653acf92b48SDave Chinner 	long nr;
654acf92b48SDave Chinner 	long new_nr;
655e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
656e9299f50SDave Chinner 					  : SHRINK_BATCH;
6575f33a080SShaohua Li 	long scanned = 0, next_deferred;
6581da177e4SLinus Torvalds 
659d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
6609b996468SKirill Tkhai 	if (freeable == 0 || freeable == SHRINK_EMPTY)
6619b996468SKirill Tkhai 		return freeable;
662635697c6SKonstantin Khlebnikov 
663acf92b48SDave Chinner 	/*
664acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
665acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
666acf92b48SDave Chinner 	 * don't also do this scanning work.
667acf92b48SDave Chinner 	 */
66886750830SYang Shi 	nr = xchg_nr_deferred(shrinker, shrinkctl);
669acf92b48SDave Chinner 
6704b85afbdSJohannes Weiner 	if (shrinker->seeks) {
6719092c71bSJosef Bacik 		delta = freeable >> priority;
6729092c71bSJosef Bacik 		delta *= 4;
6739092c71bSJosef Bacik 		do_div(delta, shrinker->seeks);
6744b85afbdSJohannes Weiner 	} else {
6754b85afbdSJohannes Weiner 		/*
6764b85afbdSJohannes Weiner 		 * These objects don't require any IO to create. Trim
6774b85afbdSJohannes Weiner 		 * them aggressively under memory pressure to keep
6784b85afbdSJohannes Weiner 		 * them from causing refetches in the IO caches.
6794b85afbdSJohannes Weiner 		 */
6804b85afbdSJohannes Weiner 		delta = freeable / 2;
6814b85afbdSJohannes Weiner 	}
682172b06c3SRoman Gushchin 
68318bb473eSYang Shi 	total_scan = nr >> priority;
684acf92b48SDave Chinner 	total_scan += delta;
68518bb473eSYang Shi 	total_scan = min(total_scan, (2 * freeable));
6861da177e4SLinus Torvalds 
68724f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
6889092c71bSJosef Bacik 				   freeable, delta, total_scan, priority);
68909576073SDave Chinner 
6900b1fb40aSVladimir Davydov 	/*
6910b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
6920b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
6930b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
6940b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
6950b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
6960b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
6970b1fb40aSVladimir Davydov 	 * batch_size.
6980b1fb40aSVladimir Davydov 	 *
6990b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
7000b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
701d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
7020b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
7030b1fb40aSVladimir Davydov 	 * possible.
7040b1fb40aSVladimir Davydov 	 */
7050b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
706d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
70724f7c6b9SDave Chinner 		unsigned long ret;
7080b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
7091da177e4SLinus Torvalds 
7100b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
711d460acb5SChris Wilson 		shrinkctl->nr_scanned = nr_to_scan;
71224f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
71324f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
7141da177e4SLinus Torvalds 			break;
71524f7c6b9SDave Chinner 		freed += ret;
71624f7c6b9SDave Chinner 
717d460acb5SChris Wilson 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
718d460acb5SChris Wilson 		total_scan -= shrinkctl->nr_scanned;
719d460acb5SChris Wilson 		scanned += shrinkctl->nr_scanned;
7201da177e4SLinus Torvalds 
7211da177e4SLinus Torvalds 		cond_resched();
7221da177e4SLinus Torvalds 	}
7231da177e4SLinus Torvalds 
72418bb473eSYang Shi 	/*
72518bb473eSYang Shi 	 * The deferred work is increased by any new work (delta) that wasn't
72618bb473eSYang Shi 	 * done, decreased by old deferred work that was done now.
72718bb473eSYang Shi 	 *
72818bb473eSYang Shi 	 * And it is capped to two times of the freeable items.
72918bb473eSYang Shi 	 */
73018bb473eSYang Shi 	next_deferred = max_t(long, (nr + delta - scanned), 0);
73118bb473eSYang Shi 	next_deferred = min(next_deferred, (2 * freeable));
73218bb473eSYang Shi 
733acf92b48SDave Chinner 	/*
734acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
73586750830SYang Shi 	 * manner that handles concurrent updates.
736acf92b48SDave Chinner 	 */
73786750830SYang Shi 	new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
738acf92b48SDave Chinner 
7398efb4b59SYang Shi 	trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
7401d3d4437SGlauber Costa 	return freed;
7411d3d4437SGlauber Costa }
7421d3d4437SGlauber Costa 
7430a432dcbSYang Shi #ifdef CONFIG_MEMCG
744b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
745b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
746b0dedc49SKirill Tkhai {
747e4262c4fSYang Shi 	struct shrinker_info *info;
748b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
749b8e57efaSKirill Tkhai 	int i;
750b0dedc49SKirill Tkhai 
7510a432dcbSYang Shi 	if (!mem_cgroup_online(memcg))
752b0dedc49SKirill Tkhai 		return 0;
753b0dedc49SKirill Tkhai 
754b0dedc49SKirill Tkhai 	if (!down_read_trylock(&shrinker_rwsem))
755b0dedc49SKirill Tkhai 		return 0;
756b0dedc49SKirill Tkhai 
757468ab843SYang Shi 	info = shrinker_info_protected(memcg, nid);
758e4262c4fSYang Shi 	if (unlikely(!info))
759b0dedc49SKirill Tkhai 		goto unlock;
760b0dedc49SKirill Tkhai 
761e4262c4fSYang Shi 	for_each_set_bit(i, info->map, shrinker_nr_max) {
762b0dedc49SKirill Tkhai 		struct shrink_control sc = {
763b0dedc49SKirill Tkhai 			.gfp_mask = gfp_mask,
764b0dedc49SKirill Tkhai 			.nid = nid,
765b0dedc49SKirill Tkhai 			.memcg = memcg,
766b0dedc49SKirill Tkhai 		};
767b0dedc49SKirill Tkhai 		struct shrinker *shrinker;
768b0dedc49SKirill Tkhai 
769b0dedc49SKirill Tkhai 		shrinker = idr_find(&shrinker_idr, i);
77041ca668aSYang Shi 		if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
7717e010df5SKirill Tkhai 			if (!shrinker)
772e4262c4fSYang Shi 				clear_bit(i, info->map);
773b0dedc49SKirill Tkhai 			continue;
774b0dedc49SKirill Tkhai 		}
775b0dedc49SKirill Tkhai 
7760a432dcbSYang Shi 		/* Call non-slab shrinkers even though kmem is disabled */
7770a432dcbSYang Shi 		if (!memcg_kmem_enabled() &&
7780a432dcbSYang Shi 		    !(shrinker->flags & SHRINKER_NONSLAB))
7790a432dcbSYang Shi 			continue;
7800a432dcbSYang Shi 
781b0dedc49SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
782f90280d6SKirill Tkhai 		if (ret == SHRINK_EMPTY) {
783e4262c4fSYang Shi 			clear_bit(i, info->map);
784f90280d6SKirill Tkhai 			/*
785f90280d6SKirill Tkhai 			 * After the shrinker reported that it had no objects to
786f90280d6SKirill Tkhai 			 * free, but before we cleared the corresponding bit in
787f90280d6SKirill Tkhai 			 * the memcg shrinker map, a new object might have been
788f90280d6SKirill Tkhai 			 * added. To make sure, we have the bit set in this
789f90280d6SKirill Tkhai 			 * case, we invoke the shrinker one more time and reset
790f90280d6SKirill Tkhai 			 * the bit if it reports that it is not empty anymore.
791f90280d6SKirill Tkhai 			 * The memory barrier here pairs with the barrier in
7922bfd3637SYang Shi 			 * set_shrinker_bit():
793f90280d6SKirill Tkhai 			 *
794f90280d6SKirill Tkhai 			 * list_lru_add()     shrink_slab_memcg()
795f90280d6SKirill Tkhai 			 *   list_add_tail()    clear_bit()
796f90280d6SKirill Tkhai 			 *   <MB>               <MB>
797f90280d6SKirill Tkhai 			 *   set_bit()          do_shrink_slab()
798f90280d6SKirill Tkhai 			 */
799f90280d6SKirill Tkhai 			smp_mb__after_atomic();
800f90280d6SKirill Tkhai 			ret = do_shrink_slab(&sc, shrinker, priority);
8019b996468SKirill Tkhai 			if (ret == SHRINK_EMPTY)
8029b996468SKirill Tkhai 				ret = 0;
803f90280d6SKirill Tkhai 			else
8042bfd3637SYang Shi 				set_shrinker_bit(memcg, nid, i);
805f90280d6SKirill Tkhai 		}
806b0dedc49SKirill Tkhai 		freed += ret;
807b0dedc49SKirill Tkhai 
808b0dedc49SKirill Tkhai 		if (rwsem_is_contended(&shrinker_rwsem)) {
809b0dedc49SKirill Tkhai 			freed = freed ? : 1;
810b0dedc49SKirill Tkhai 			break;
811b0dedc49SKirill Tkhai 		}
812b0dedc49SKirill Tkhai 	}
813b0dedc49SKirill Tkhai unlock:
814b0dedc49SKirill Tkhai 	up_read(&shrinker_rwsem);
815b0dedc49SKirill Tkhai 	return freed;
816b0dedc49SKirill Tkhai }
8170a432dcbSYang Shi #else /* CONFIG_MEMCG */
818b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
819b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
820b0dedc49SKirill Tkhai {
821b0dedc49SKirill Tkhai 	return 0;
822b0dedc49SKirill Tkhai }
8230a432dcbSYang Shi #endif /* CONFIG_MEMCG */
824b0dedc49SKirill Tkhai 
8256b4f7799SJohannes Weiner /**
826cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
8276b4f7799SJohannes Weiner  * @gfp_mask: allocation context
8286b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
829cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
8309092c71bSJosef Bacik  * @priority: the reclaim priority
8311d3d4437SGlauber Costa  *
8326b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
8331d3d4437SGlauber Costa  *
8346b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
8356b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
8361d3d4437SGlauber Costa  *
837aeed1d32SVladimir Davydov  * @memcg specifies the memory cgroup to target. Unaware shrinkers
838aeed1d32SVladimir Davydov  * are called only if it is the root cgroup.
839cb731d6cSVladimir Davydov  *
8409092c71bSJosef Bacik  * @priority is sc->priority, we take the number of objects and >> by priority
8419092c71bSJosef Bacik  * in order to get the scan target.
8421d3d4437SGlauber Costa  *
8436b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
8441d3d4437SGlauber Costa  */
845cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
846cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
8479092c71bSJosef Bacik 				 int priority)
8481d3d4437SGlauber Costa {
849b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
8501d3d4437SGlauber Costa 	struct shrinker *shrinker;
8511d3d4437SGlauber Costa 
852fa1e512fSYang Shi 	/*
853fa1e512fSYang Shi 	 * The root memcg might be allocated even though memcg is disabled
854fa1e512fSYang Shi 	 * via "cgroup_disable=memory" boot parameter.  This could make
855fa1e512fSYang Shi 	 * mem_cgroup_is_root() return false, then just run memcg slab
856fa1e512fSYang Shi 	 * shrink, but skip global shrink.  This may result in premature
857fa1e512fSYang Shi 	 * oom.
858fa1e512fSYang Shi 	 */
859fa1e512fSYang Shi 	if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
860b0dedc49SKirill Tkhai 		return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
861cb731d6cSVladimir Davydov 
862e830c63aSTetsuo Handa 	if (!down_read_trylock(&shrinker_rwsem))
8631d3d4437SGlauber Costa 		goto out;
8641d3d4437SGlauber Costa 
8651d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
8666b4f7799SJohannes Weiner 		struct shrink_control sc = {
8676b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
8686b4f7799SJohannes Weiner 			.nid = nid,
869cb731d6cSVladimir Davydov 			.memcg = memcg,
8706b4f7799SJohannes Weiner 		};
8716b4f7799SJohannes Weiner 
8729b996468SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
8739b996468SKirill Tkhai 		if (ret == SHRINK_EMPTY)
8749b996468SKirill Tkhai 			ret = 0;
8759b996468SKirill Tkhai 		freed += ret;
876e496612cSMinchan Kim 		/*
877e496612cSMinchan Kim 		 * Bail out if someone want to register a new shrinker to
87855b65a57SEthon Paul 		 * prevent the registration from being stalled for long periods
879e496612cSMinchan Kim 		 * by parallel ongoing shrinking.
880e496612cSMinchan Kim 		 */
881e496612cSMinchan Kim 		if (rwsem_is_contended(&shrinker_rwsem)) {
882e496612cSMinchan Kim 			freed = freed ? : 1;
883e496612cSMinchan Kim 			break;
884e496612cSMinchan Kim 		}
885ec97097bSVladimir Davydov 	}
8861d3d4437SGlauber Costa 
8871da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
888f06590bdSMinchan Kim out:
889f06590bdSMinchan Kim 	cond_resched();
89024f7c6b9SDave Chinner 	return freed;
8911da177e4SLinus Torvalds }
8921da177e4SLinus Torvalds 
893cb731d6cSVladimir Davydov void drop_slab_node(int nid)
894cb731d6cSVladimir Davydov {
895cb731d6cSVladimir Davydov 	unsigned long freed;
896cb731d6cSVladimir Davydov 
897cb731d6cSVladimir Davydov 	do {
898cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
899cb731d6cSVladimir Davydov 
900069c411dSChunxin Zang 		if (fatal_signal_pending(current))
901069c411dSChunxin Zang 			return;
902069c411dSChunxin Zang 
903cb731d6cSVladimir Davydov 		freed = 0;
904aeed1d32SVladimir Davydov 		memcg = mem_cgroup_iter(NULL, NULL, NULL);
905cb731d6cSVladimir Davydov 		do {
9069092c71bSJosef Bacik 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
907cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
908cb731d6cSVladimir Davydov 	} while (freed > 10);
909cb731d6cSVladimir Davydov }
910cb731d6cSVladimir Davydov 
911cb731d6cSVladimir Davydov void drop_slab(void)
912cb731d6cSVladimir Davydov {
913cb731d6cSVladimir Davydov 	int nid;
914cb731d6cSVladimir Davydov 
915cb731d6cSVladimir Davydov 	for_each_online_node(nid)
916cb731d6cSVladimir Davydov 		drop_slab_node(nid);
917cb731d6cSVladimir Davydov }
918cb731d6cSVladimir Davydov 
9191da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
9201da177e4SLinus Torvalds {
921ceddc3a5SJohannes Weiner 	/*
922ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
92367891fffSMatthew Wilcox 	 * that isolated the page, the page cache and optional buffer
92467891fffSMatthew Wilcox 	 * heads at page->private.
925ceddc3a5SJohannes Weiner 	 */
9263efe62e4SMatthew Wilcox (Oracle) 	int page_cache_pins = thp_nr_pages(page);
92767891fffSMatthew Wilcox 	return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
9281da177e4SLinus Torvalds }
9291da177e4SLinus Torvalds 
930cb16556dSYang Shi static int may_write_to_inode(struct inode *inode)
9311da177e4SLinus Torvalds {
932930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
9331da177e4SLinus Torvalds 		return 1;
934703c2708STejun Heo 	if (!inode_write_congested(inode))
9351da177e4SLinus Torvalds 		return 1;
936703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
9371da177e4SLinus Torvalds 		return 1;
9381da177e4SLinus Torvalds 	return 0;
9391da177e4SLinus Torvalds }
9401da177e4SLinus Torvalds 
9411da177e4SLinus Torvalds /*
9421da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
9431da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
9441da177e4SLinus Torvalds  * fsync(), msync() or close().
9451da177e4SLinus Torvalds  *
9461da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
9471da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
9481da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
9491da177e4SLinus Torvalds  *
9501da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
9511da177e4SLinus Torvalds  * __GFP_FS.
9521da177e4SLinus Torvalds  */
9531da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
9541da177e4SLinus Torvalds 				struct page *page, int error)
9551da177e4SLinus Torvalds {
9567eaceaccSJens Axboe 	lock_page(page);
9573e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
9583e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
9591da177e4SLinus Torvalds 	unlock_page(page);
9601da177e4SLinus Torvalds }
9611da177e4SLinus Torvalds 
96204e62a29SChristoph Lameter /* possible outcome of pageout() */
96304e62a29SChristoph Lameter typedef enum {
96404e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
96504e62a29SChristoph Lameter 	PAGE_KEEP,
96604e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
96704e62a29SChristoph Lameter 	PAGE_ACTIVATE,
96804e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
96904e62a29SChristoph Lameter 	PAGE_SUCCESS,
97004e62a29SChristoph Lameter 	/* page is clean and locked */
97104e62a29SChristoph Lameter 	PAGE_CLEAN,
97204e62a29SChristoph Lameter } pageout_t;
97304e62a29SChristoph Lameter 
9741da177e4SLinus Torvalds /*
9751742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
9761742f19fSAndrew Morton  * Calls ->writepage().
9771da177e4SLinus Torvalds  */
978cb16556dSYang Shi static pageout_t pageout(struct page *page, struct address_space *mapping)
9791da177e4SLinus Torvalds {
9801da177e4SLinus Torvalds 	/*
9811da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
9821da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
9831da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
9841da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
9851da177e4SLinus Torvalds 	 * PagePrivate for that.
9861da177e4SLinus Torvalds 	 *
9878174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
9881da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
9891da177e4SLinus Torvalds 	 * will block.
9901da177e4SLinus Torvalds 	 *
9911da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
9921da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
9931da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
9941da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
9951da177e4SLinus Torvalds 	 */
9961da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
9971da177e4SLinus Torvalds 		return PAGE_KEEP;
9981da177e4SLinus Torvalds 	if (!mapping) {
9991da177e4SLinus Torvalds 		/*
10001da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
10011da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
10021da177e4SLinus Torvalds 		 */
1003266cf658SDavid Howells 		if (page_has_private(page)) {
10041da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
10051da177e4SLinus Torvalds 				ClearPageDirty(page);
1006b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
10071da177e4SLinus Torvalds 				return PAGE_CLEAN;
10081da177e4SLinus Torvalds 			}
10091da177e4SLinus Torvalds 		}
10101da177e4SLinus Torvalds 		return PAGE_KEEP;
10111da177e4SLinus Torvalds 	}
10121da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
10131da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
1014cb16556dSYang Shi 	if (!may_write_to_inode(mapping->host))
10151da177e4SLinus Torvalds 		return PAGE_KEEP;
10161da177e4SLinus Torvalds 
10171da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
10181da177e4SLinus Torvalds 		int res;
10191da177e4SLinus Torvalds 		struct writeback_control wbc = {
10201da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
10211da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
1022111ebb6eSOGAWA Hirofumi 			.range_start = 0,
1023111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
10241da177e4SLinus Torvalds 			.for_reclaim = 1,
10251da177e4SLinus Torvalds 		};
10261da177e4SLinus Torvalds 
10271da177e4SLinus Torvalds 		SetPageReclaim(page);
10281da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
10291da177e4SLinus Torvalds 		if (res < 0)
10301da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
1031994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
10321da177e4SLinus Torvalds 			ClearPageReclaim(page);
10331da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
10341da177e4SLinus Torvalds 		}
1035c661b078SAndy Whitcroft 
10361da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
10371da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
10381da177e4SLinus Torvalds 			ClearPageReclaim(page);
10391da177e4SLinus Torvalds 		}
10403aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
1041c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
10421da177e4SLinus Torvalds 		return PAGE_SUCCESS;
10431da177e4SLinus Torvalds 	}
10441da177e4SLinus Torvalds 
10451da177e4SLinus Torvalds 	return PAGE_CLEAN;
10461da177e4SLinus Torvalds }
10471da177e4SLinus Torvalds 
1048a649fd92SAndrew Morton /*
1049e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
1050e286781dSNick Piggin  * gets returned with a refcount of 0.
1051a649fd92SAndrew Morton  */
1052a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
1053b910718aSJohannes Weiner 			    bool reclaimed, struct mem_cgroup *target_memcg)
105449d2e9ccSChristoph Lameter {
1055bd4c82c2SHuang Ying 	int refcount;
1056aae466b0SJoonsoo Kim 	void *shadow = NULL;
1057c4843a75SGreg Thelen 
105828e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
105928e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
106049d2e9ccSChristoph Lameter 
106130472509SJohannes Weiner 	xa_lock_irq(&mapping->i_pages);
106249d2e9ccSChristoph Lameter 	/*
10630fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
10640fd0e6b0SNick Piggin 	 *
10650fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
10660fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
10670fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
10680fd0e6b0SNick Piggin 	 * here, then the following race may occur:
10690fd0e6b0SNick Piggin 	 *
10700fd0e6b0SNick Piggin 	 * get_user_pages(&page);
10710fd0e6b0SNick Piggin 	 * [user mapping goes away]
10720fd0e6b0SNick Piggin 	 * write_to(page);
10730fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
10740fd0e6b0SNick Piggin 	 * SetPageDirty(page);
10750fd0e6b0SNick Piggin 	 * put_page(page);
10760fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
10770fd0e6b0SNick Piggin 	 *
10780fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
10790fd0e6b0SNick Piggin 	 *
10800fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
10810fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
10820139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
10830fd0e6b0SNick Piggin 	 *
10840fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
1085b93b0163SMatthew Wilcox 	 * and thus under the i_pages lock, then this ordering is not required.
108649d2e9ccSChristoph Lameter 	 */
1087906d278dSWilliam Kucharski 	refcount = 1 + compound_nr(page);
1088bd4c82c2SHuang Ying 	if (!page_ref_freeze(page, refcount))
108949d2e9ccSChristoph Lameter 		goto cannot_free;
10901c4c3b99SJiang Biao 	/* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
1091e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
1092bd4c82c2SHuang Ying 		page_ref_unfreeze(page, refcount);
109349d2e9ccSChristoph Lameter 		goto cannot_free;
1094e286781dSNick Piggin 	}
109549d2e9ccSChristoph Lameter 
109649d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
109749d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
10980a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
1099aae466b0SJoonsoo Kim 		if (reclaimed && !mapping_exiting(mapping))
1100aae466b0SJoonsoo Kim 			shadow = workingset_eviction(page, target_memcg);
1101aae466b0SJoonsoo Kim 		__delete_from_swap_cache(page, swap, shadow);
110230472509SJohannes Weiner 		xa_unlock_irq(&mapping->i_pages);
110375f6d6d2SMinchan Kim 		put_swap_page(page, swap);
1104e286781dSNick Piggin 	} else {
11056072d13cSLinus Torvalds 		void (*freepage)(struct page *);
11066072d13cSLinus Torvalds 
11076072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
1108a528910eSJohannes Weiner 		/*
1109a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
1110a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
1111a528910eSJohannes Weiner 		 *
1112a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
1113238c3046Sdylan-meiners 		 * already exiting.  This is not just an optimization,
1114a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
1115a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
1116a528910eSJohannes Weiner 		 * back.
1117f9fe48beSRoss Zwisler 		 *
1118f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
1119f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
1120f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
1121f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
1122b93b0163SMatthew Wilcox 		 * same address_space.
1123a528910eSJohannes Weiner 		 */
11249de4f22aSHuang Ying 		if (reclaimed && page_is_file_lru(page) &&
1125f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
1126b910718aSJohannes Weiner 			shadow = workingset_eviction(page, target_memcg);
112762cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
112830472509SJohannes Weiner 		xa_unlock_irq(&mapping->i_pages);
11296072d13cSLinus Torvalds 
11306072d13cSLinus Torvalds 		if (freepage != NULL)
11316072d13cSLinus Torvalds 			freepage(page);
1132e286781dSNick Piggin 	}
1133e286781dSNick Piggin 
113449d2e9ccSChristoph Lameter 	return 1;
113549d2e9ccSChristoph Lameter 
113649d2e9ccSChristoph Lameter cannot_free:
113730472509SJohannes Weiner 	xa_unlock_irq(&mapping->i_pages);
113849d2e9ccSChristoph Lameter 	return 0;
113949d2e9ccSChristoph Lameter }
114049d2e9ccSChristoph Lameter 
11411da177e4SLinus Torvalds /*
1142e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
1143e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
1144e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
1145e286781dSNick Piggin  * this page.
1146e286781dSNick Piggin  */
1147e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
1148e286781dSNick Piggin {
1149b910718aSJohannes Weiner 	if (__remove_mapping(mapping, page, false, NULL)) {
1150e286781dSNick Piggin 		/*
1151e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
1152e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
1153e286781dSNick Piggin 		 * atomic operation.
1154e286781dSNick Piggin 		 */
1155fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
1156e286781dSNick Piggin 		return 1;
1157e286781dSNick Piggin 	}
1158e286781dSNick Piggin 	return 0;
1159e286781dSNick Piggin }
1160e286781dSNick Piggin 
1161894bc310SLee Schermerhorn /**
1162894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
1163894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
1164894bc310SLee Schermerhorn  *
1165894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
1166894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
1167894bc310SLee Schermerhorn  *
1168894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
1169894bc310SLee Schermerhorn  */
1170894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
1171894bc310SLee Schermerhorn {
1172c53954a0SMel Gorman 	lru_cache_add(page);
1173894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
1174894bc310SLee Schermerhorn }
1175894bc310SLee Schermerhorn 
1176dfc8d636SJohannes Weiner enum page_references {
1177dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
1178dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
117964574746SJohannes Weiner 	PAGEREF_KEEP,
1180dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
1181dfc8d636SJohannes Weiner };
1182dfc8d636SJohannes Weiner 
1183dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
1184dfc8d636SJohannes Weiner 						  struct scan_control *sc)
1185dfc8d636SJohannes Weiner {
118664574746SJohannes Weiner 	int referenced_ptes, referenced_page;
1187dfc8d636SJohannes Weiner 	unsigned long vm_flags;
1188dfc8d636SJohannes Weiner 
1189c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1190c3ac9a8aSJohannes Weiner 					  &vm_flags);
119164574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
1192dfc8d636SJohannes Weiner 
1193dfc8d636SJohannes Weiner 	/*
1194dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
1195dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
1196dfc8d636SJohannes Weiner 	 */
1197dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
1198dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
1199dfc8d636SJohannes Weiner 
120064574746SJohannes Weiner 	if (referenced_ptes) {
120164574746SJohannes Weiner 		/*
120264574746SJohannes Weiner 		 * All mapped pages start out with page table
120364574746SJohannes Weiner 		 * references from the instantiating fault, so we need
120464574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
120564574746SJohannes Weiner 		 * than once.
120664574746SJohannes Weiner 		 *
120764574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
120864574746SJohannes Weiner 		 * inactive list.  Another page table reference will
120964574746SJohannes Weiner 		 * lead to its activation.
121064574746SJohannes Weiner 		 *
121164574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
121264574746SJohannes Weiner 		 * so that recently deactivated but used pages are
121364574746SJohannes Weiner 		 * quickly recovered.
121464574746SJohannes Weiner 		 */
121564574746SJohannes Weiner 		SetPageReferenced(page);
121664574746SJohannes Weiner 
121734dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
1218dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
1219dfc8d636SJohannes Weiner 
1220c909e993SKonstantin Khlebnikov 		/*
1221c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
1222c909e993SKonstantin Khlebnikov 		 */
1223b518154eSJoonsoo Kim 		if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
1224c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
1225c909e993SKonstantin Khlebnikov 
122664574746SJohannes Weiner 		return PAGEREF_KEEP;
122764574746SJohannes Weiner 	}
122864574746SJohannes Weiner 
1229dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
12302e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
1231dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
123264574746SJohannes Weiner 
123364574746SJohannes Weiner 	return PAGEREF_RECLAIM;
1234dfc8d636SJohannes Weiner }
1235dfc8d636SJohannes Weiner 
1236e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
1237e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
1238e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
1239e2be15f6SMel Gorman {
1240b4597226SMel Gorman 	struct address_space *mapping;
1241b4597226SMel Gorman 
1242e2be15f6SMel Gorman 	/*
1243e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
1244e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
1245e2be15f6SMel Gorman 	 */
12469de4f22aSHuang Ying 	if (!page_is_file_lru(page) ||
1247802a3a92SShaohua Li 	    (PageAnon(page) && !PageSwapBacked(page))) {
1248e2be15f6SMel Gorman 		*dirty = false;
1249e2be15f6SMel Gorman 		*writeback = false;
1250e2be15f6SMel Gorman 		return;
1251e2be15f6SMel Gorman 	}
1252e2be15f6SMel Gorman 
1253e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
1254e2be15f6SMel Gorman 	*dirty = PageDirty(page);
1255e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
1256b4597226SMel Gorman 
1257b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
1258b4597226SMel Gorman 	if (!page_has_private(page))
1259b4597226SMel Gorman 		return;
1260b4597226SMel Gorman 
1261b4597226SMel Gorman 	mapping = page_mapping(page);
1262b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
1263b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1264e2be15f6SMel Gorman }
1265e2be15f6SMel Gorman 
1266e286781dSNick Piggin /*
12671742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
12681da177e4SLinus Torvalds  */
1269730ec8c0SManinder Singh static unsigned int shrink_page_list(struct list_head *page_list,
1270599d0c95SMel Gorman 				     struct pglist_data *pgdat,
1271f84f6e2bSMel Gorman 				     struct scan_control *sc,
12723c710c1aSMichal Hocko 				     struct reclaim_stat *stat,
12738940b34aSMinchan Kim 				     bool ignore_references)
12741da177e4SLinus Torvalds {
12751da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
1276abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
1277730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
1278730ec8c0SManinder Singh 	unsigned int pgactivate = 0;
12791da177e4SLinus Torvalds 
1280060f005fSKirill Tkhai 	memset(stat, 0, sizeof(*stat));
12811da177e4SLinus Torvalds 	cond_resched();
12821da177e4SLinus Torvalds 
12831da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
12841da177e4SLinus Torvalds 		struct address_space *mapping;
12851da177e4SLinus Torvalds 		struct page *page;
12868940b34aSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM;
12874b793062SKirill Tkhai 		bool dirty, writeback, may_enter_fs;
128898879b3bSYang Shi 		unsigned int nr_pages;
12891da177e4SLinus Torvalds 
12901da177e4SLinus Torvalds 		cond_resched();
12911da177e4SLinus Torvalds 
12921da177e4SLinus Torvalds 		page = lru_to_page(page_list);
12931da177e4SLinus Torvalds 		list_del(&page->lru);
12941da177e4SLinus Torvalds 
1295529ae9aaSNick Piggin 		if (!trylock_page(page))
12961da177e4SLinus Torvalds 			goto keep;
12971da177e4SLinus Torvalds 
1298309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
12991da177e4SLinus Torvalds 
1300d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
130198879b3bSYang Shi 
130298879b3bSYang Shi 		/* Account the number of base pages even though THP */
130398879b3bSYang Shi 		sc->nr_scanned += nr_pages;
130480e43426SChristoph Lameter 
130539b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
1306ad6b6704SMinchan Kim 			goto activate_locked;
1307894bc310SLee Schermerhorn 
1308a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
130980e43426SChristoph Lameter 			goto keep_locked;
131080e43426SChristoph Lameter 
1311c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1312c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1313c661b078SAndy Whitcroft 
1314e62e384eSMichal Hocko 		/*
1315894befecSAndrey Ryabinin 		 * The number of dirty pages determines if a node is marked
1316e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
1317e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
1318e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
1319e2be15f6SMel Gorman 		 */
1320e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
1321e2be15f6SMel Gorman 		if (dirty || writeback)
1322060f005fSKirill Tkhai 			stat->nr_dirty++;
1323e2be15f6SMel Gorman 
1324e2be15f6SMel Gorman 		if (dirty && !writeback)
1325060f005fSKirill Tkhai 			stat->nr_unqueued_dirty++;
1326e2be15f6SMel Gorman 
1327d04e8acdSMel Gorman 		/*
1328d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
1329d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
1330d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
1331d04e8acdSMel Gorman 		 * end of the LRU a second time.
1332d04e8acdSMel Gorman 		 */
1333e2be15f6SMel Gorman 		mapping = page_mapping(page);
13341da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
1335703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
1336d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
1337060f005fSKirill Tkhai 			stat->nr_congested++;
1338e2be15f6SMel Gorman 
1339e2be15f6SMel Gorman 		/*
1340283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
1341283aba9fSMel Gorman 		 * are three cases to consider.
1342e62e384eSMichal Hocko 		 *
1343283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
1344283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
1345283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
1346283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
1347283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
1348283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
1349283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
1350b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
1351b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
1352c3b94f44SHugh Dickins 		 *
135397c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
1354ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1355ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1356ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
135797c9341fSTejun Heo 		 *    reclaim and continue scanning.
1358283aba9fSMel Gorman 		 *
1359ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1360ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1361283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1362283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1363283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1364283aba9fSMel Gorman 		 *    would probably show more reasons.
1365283aba9fSMel Gorman 		 *
13667fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1367283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1368283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1369283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1370283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1371c55e8d03SJohannes Weiner 		 *
1372c55e8d03SJohannes Weiner 		 * In cases 1) and 2) we activate the pages to get them out of
1373c55e8d03SJohannes Weiner 		 * the way while we continue scanning for clean pages on the
1374c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1375c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1376c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1377c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1378c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1379c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1380e62e384eSMichal Hocko 		 */
1381283aba9fSMel Gorman 		if (PageWriteback(page)) {
1382283aba9fSMel Gorman 			/* Case 1 above */
1383283aba9fSMel Gorman 			if (current_is_kswapd() &&
1384283aba9fSMel Gorman 			    PageReclaim(page) &&
1385599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1386060f005fSKirill Tkhai 				stat->nr_immediate++;
1387c55e8d03SJohannes Weiner 				goto activate_locked;
1388283aba9fSMel Gorman 
1389283aba9fSMel Gorman 			/* Case 2 above */
1390b5ead35eSJohannes Weiner 			} else if (writeback_throttling_sane(sc) ||
1391ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1392c3b94f44SHugh Dickins 				/*
1393c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1394c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1395c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1396c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1397c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1398c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1399c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1400c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1401c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1402c3b94f44SHugh Dickins 				 */
1403c3b94f44SHugh Dickins 				SetPageReclaim(page);
1404060f005fSKirill Tkhai 				stat->nr_writeback++;
1405c55e8d03SJohannes Weiner 				goto activate_locked;
1406283aba9fSMel Gorman 
1407283aba9fSMel Gorman 			/* Case 3 above */
1408283aba9fSMel Gorman 			} else {
14097fadc820SHugh Dickins 				unlock_page(page);
1410c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
14117fadc820SHugh Dickins 				/* then go back and try same page again */
14127fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
14137fadc820SHugh Dickins 				continue;
1414e62e384eSMichal Hocko 			}
1415283aba9fSMel Gorman 		}
14161da177e4SLinus Torvalds 
14178940b34aSMinchan Kim 		if (!ignore_references)
14186a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
141902c6de8dSMinchan Kim 
1420dfc8d636SJohannes Weiner 		switch (references) {
1421dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
14221da177e4SLinus Torvalds 			goto activate_locked;
142364574746SJohannes Weiner 		case PAGEREF_KEEP:
142498879b3bSYang Shi 			stat->nr_ref_keep += nr_pages;
142564574746SJohannes Weiner 			goto keep_locked;
1426dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1427dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1428dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1429dfc8d636SJohannes Weiner 		}
14301da177e4SLinus Torvalds 
14311da177e4SLinus Torvalds 		/*
14321da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
14331da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1434802a3a92SShaohua Li 		 * Lazyfree page could be freed directly
14351da177e4SLinus Torvalds 		 */
1436bd4c82c2SHuang Ying 		if (PageAnon(page) && PageSwapBacked(page)) {
1437bd4c82c2SHuang Ying 			if (!PageSwapCache(page)) {
143863eb6b93SHugh Dickins 				if (!(sc->gfp_mask & __GFP_IO))
143963eb6b93SHugh Dickins 					goto keep_locked;
1440feb889fbSLinus Torvalds 				if (page_maybe_dma_pinned(page))
1441feb889fbSLinus Torvalds 					goto keep_locked;
1442747552b1SHuang Ying 				if (PageTransHuge(page)) {
1443b8f593cdSHuang Ying 					/* cannot split THP, skip it */
1444747552b1SHuang Ying 					if (!can_split_huge_page(page, NULL))
1445b8f593cdSHuang Ying 						goto activate_locked;
1446747552b1SHuang Ying 					/*
1447747552b1SHuang Ying 					 * Split pages without a PMD map right
1448747552b1SHuang Ying 					 * away. Chances are some or all of the
1449747552b1SHuang Ying 					 * tail pages can be freed without IO.
1450747552b1SHuang Ying 					 */
1451747552b1SHuang Ying 					if (!compound_mapcount(page) &&
1452bd4c82c2SHuang Ying 					    split_huge_page_to_list(page,
1453bd4c82c2SHuang Ying 								    page_list))
1454747552b1SHuang Ying 						goto activate_locked;
1455747552b1SHuang Ying 				}
14560f074658SMinchan Kim 				if (!add_to_swap(page)) {
14570f074658SMinchan Kim 					if (!PageTransHuge(page))
145898879b3bSYang Shi 						goto activate_locked_split;
1459bd4c82c2SHuang Ying 					/* Fallback to swap normal pages */
1460bd4c82c2SHuang Ying 					if (split_huge_page_to_list(page,
1461bd4c82c2SHuang Ying 								    page_list))
14620f074658SMinchan Kim 						goto activate_locked;
1463fe490cc0SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1464fe490cc0SHuang Ying 					count_vm_event(THP_SWPOUT_FALLBACK);
1465fe490cc0SHuang Ying #endif
14660f074658SMinchan Kim 					if (!add_to_swap(page))
146798879b3bSYang Shi 						goto activate_locked_split;
14680f074658SMinchan Kim 				}
14690f074658SMinchan Kim 
14704b793062SKirill Tkhai 				may_enter_fs = true;
14711da177e4SLinus Torvalds 
1472e2be15f6SMel Gorman 				/* Adding to swap updated mapping */
14731da177e4SLinus Torvalds 				mapping = page_mapping(page);
1474bd4c82c2SHuang Ying 			}
14757751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
14767751b2daSKirill A. Shutemov 			/* Split file THP */
14777751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
14787751b2daSKirill A. Shutemov 				goto keep_locked;
1479e2be15f6SMel Gorman 		}
14801da177e4SLinus Torvalds 
14811da177e4SLinus Torvalds 		/*
148298879b3bSYang Shi 		 * THP may get split above, need minus tail pages and update
148398879b3bSYang Shi 		 * nr_pages to avoid accounting tail pages twice.
148498879b3bSYang Shi 		 *
148598879b3bSYang Shi 		 * The tail pages that are added into swap cache successfully
148698879b3bSYang Shi 		 * reach here.
148798879b3bSYang Shi 		 */
148898879b3bSYang Shi 		if ((nr_pages > 1) && !PageTransHuge(page)) {
148998879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
149098879b3bSYang Shi 			nr_pages = 1;
149198879b3bSYang Shi 		}
149298879b3bSYang Shi 
149398879b3bSYang Shi 		/*
14941da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
14951da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
14961da177e4SLinus Torvalds 		 */
1497802a3a92SShaohua Li 		if (page_mapped(page)) {
1498013339dfSShakeel Butt 			enum ttu_flags flags = TTU_BATCH_FLUSH;
14991f318a9bSJaewon Kim 			bool was_swapbacked = PageSwapBacked(page);
1500bd4c82c2SHuang Ying 
1501bd4c82c2SHuang Ying 			if (unlikely(PageTransHuge(page)))
1502bd4c82c2SHuang Ying 				flags |= TTU_SPLIT_HUGE_PMD;
15031f318a9bSJaewon Kim 
15041fb08ac6SYang Shi 			try_to_unmap(page, flags);
15051fb08ac6SYang Shi 			if (page_mapped(page)) {
150698879b3bSYang Shi 				stat->nr_unmap_fail += nr_pages;
15071f318a9bSJaewon Kim 				if (!was_swapbacked && PageSwapBacked(page))
15081f318a9bSJaewon Kim 					stat->nr_lazyfree_fail += nr_pages;
15091da177e4SLinus Torvalds 				goto activate_locked;
15101da177e4SLinus Torvalds 			}
15111da177e4SLinus Torvalds 		}
15121da177e4SLinus Torvalds 
15131da177e4SLinus Torvalds 		if (PageDirty(page)) {
1514ee72886dSMel Gorman 			/*
15154eda4823SJohannes Weiner 			 * Only kswapd can writeback filesystem pages
15164eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
15174eda4823SJohannes Weiner 			 * injecting inefficient single-page IO into
15184eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
15194eda4823SJohannes Weiner 			 * write pages when we've encountered many
15204eda4823SJohannes Weiner 			 * dirty pages, and when we've already scanned
15214eda4823SJohannes Weiner 			 * the rest of the LRU for clean pages and see
15224eda4823SJohannes Weiner 			 * the same dirty pages again (PageReclaim).
1523ee72886dSMel Gorman 			 */
15249de4f22aSHuang Ying 			if (page_is_file_lru(page) &&
15254eda4823SJohannes Weiner 			    (!current_is_kswapd() || !PageReclaim(page) ||
1526599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
152749ea7eb6SMel Gorman 				/*
152849ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
152949ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
153049ea7eb6SMel Gorman 				 * except we already have the page isolated
153149ea7eb6SMel Gorman 				 * and know it's dirty
153249ea7eb6SMel Gorman 				 */
1533c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
153449ea7eb6SMel Gorman 				SetPageReclaim(page);
153549ea7eb6SMel Gorman 
1536c55e8d03SJohannes Weiner 				goto activate_locked;
1537ee72886dSMel Gorman 			}
1538ee72886dSMel Gorman 
1539dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
15401da177e4SLinus Torvalds 				goto keep_locked;
15414dd4b920SAndrew Morton 			if (!may_enter_fs)
15421da177e4SLinus Torvalds 				goto keep_locked;
154352a8363eSChristoph Lameter 			if (!sc->may_writepage)
15441da177e4SLinus Torvalds 				goto keep_locked;
15451da177e4SLinus Torvalds 
1546d950c947SMel Gorman 			/*
1547d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1548d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1549d950c947SMel Gorman 			 * starts and then write it out here.
1550d950c947SMel Gorman 			 */
1551d950c947SMel Gorman 			try_to_unmap_flush_dirty();
1552cb16556dSYang Shi 			switch (pageout(page, mapping)) {
15531da177e4SLinus Torvalds 			case PAGE_KEEP:
15541da177e4SLinus Torvalds 				goto keep_locked;
15551da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
15561da177e4SLinus Torvalds 				goto activate_locked;
15571da177e4SLinus Torvalds 			case PAGE_SUCCESS:
15586c357848SMatthew Wilcox (Oracle) 				stat->nr_pageout += thp_nr_pages(page);
155996f8bf4fSJohannes Weiner 
15607d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
156141ac1999SMel Gorman 					goto keep;
15627d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
15631da177e4SLinus Torvalds 					goto keep;
15647d3579e8SKOSAKI Motohiro 
15651da177e4SLinus Torvalds 				/*
15661da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
15671da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
15681da177e4SLinus Torvalds 				 */
1569529ae9aaSNick Piggin 				if (!trylock_page(page))
15701da177e4SLinus Torvalds 					goto keep;
15711da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
15721da177e4SLinus Torvalds 					goto keep_locked;
15731da177e4SLinus Torvalds 				mapping = page_mapping(page);
157401359eb2SGustavo A. R. Silva 				fallthrough;
15751da177e4SLinus Torvalds 			case PAGE_CLEAN:
15761da177e4SLinus Torvalds 				; /* try to free the page below */
15771da177e4SLinus Torvalds 			}
15781da177e4SLinus Torvalds 		}
15791da177e4SLinus Torvalds 
15801da177e4SLinus Torvalds 		/*
15811da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
15821da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
15831da177e4SLinus Torvalds 		 * the page as well.
15841da177e4SLinus Torvalds 		 *
15851da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
15861da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
15871da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
15881da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
15891da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
15901da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
15911da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
15921da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
15931da177e4SLinus Torvalds 		 *
15941da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
15951da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
1596d12b8951SYang Shi 		 * truncate_cleanup_page().  We try to drop those buffers here
15971da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
15981da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
15991da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
16001da177e4SLinus Torvalds 		 */
1601266cf658SDavid Howells 		if (page_has_private(page)) {
16021da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
16031da177e4SLinus Torvalds 				goto activate_locked;
1604e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1605e286781dSNick Piggin 				unlock_page(page);
1606e286781dSNick Piggin 				if (put_page_testzero(page))
16071da177e4SLinus Torvalds 					goto free_it;
1608e286781dSNick Piggin 				else {
1609e286781dSNick Piggin 					/*
1610e286781dSNick Piggin 					 * rare race with speculative reference.
1611e286781dSNick Piggin 					 * the speculative reference will free
1612e286781dSNick Piggin 					 * this page shortly, so we may
1613e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1614e286781dSNick Piggin 					 * leave it off the LRU).
1615e286781dSNick Piggin 					 */
1616e286781dSNick Piggin 					nr_reclaimed++;
1617e286781dSNick Piggin 					continue;
1618e286781dSNick Piggin 				}
1619e286781dSNick Piggin 			}
16201da177e4SLinus Torvalds 		}
16211da177e4SLinus Torvalds 
1622802a3a92SShaohua Li 		if (PageAnon(page) && !PageSwapBacked(page)) {
1623802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
1624802a3a92SShaohua Li 			if (!page_ref_freeze(page, 1))
162549d2e9ccSChristoph Lameter 				goto keep_locked;
1626802a3a92SShaohua Li 			if (PageDirty(page)) {
1627802a3a92SShaohua Li 				page_ref_unfreeze(page, 1);
1628802a3a92SShaohua Li 				goto keep_locked;
1629802a3a92SShaohua Li 			}
16301da177e4SLinus Torvalds 
1631802a3a92SShaohua Li 			count_vm_event(PGLAZYFREED);
16322262185cSRoman Gushchin 			count_memcg_page_event(page, PGLAZYFREED);
1633b910718aSJohannes Weiner 		} else if (!mapping || !__remove_mapping(mapping, page, true,
1634b910718aSJohannes Weiner 							 sc->target_mem_cgroup))
1635802a3a92SShaohua Li 			goto keep_locked;
16369a1ea439SHugh Dickins 
16379a1ea439SHugh Dickins 		unlock_page(page);
1638e286781dSNick Piggin free_it:
163998879b3bSYang Shi 		/*
164098879b3bSYang Shi 		 * THP may get swapped out in a whole, need account
164198879b3bSYang Shi 		 * all base pages.
164298879b3bSYang Shi 		 */
164398879b3bSYang Shi 		nr_reclaimed += nr_pages;
1644abe4c3b5SMel Gorman 
1645abe4c3b5SMel Gorman 		/*
1646abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1647abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1648abe4c3b5SMel Gorman 		 */
16497ae88534SYang Shi 		if (unlikely(PageTransHuge(page)))
1650ff45fc3cSMatthew Wilcox (Oracle) 			destroy_compound_page(page);
16517ae88534SYang Shi 		else
1652abe4c3b5SMel Gorman 			list_add(&page->lru, &free_pages);
16531da177e4SLinus Torvalds 		continue;
16541da177e4SLinus Torvalds 
165598879b3bSYang Shi activate_locked_split:
165698879b3bSYang Shi 		/*
165798879b3bSYang Shi 		 * The tail pages that are failed to add into swap cache
165898879b3bSYang Shi 		 * reach here.  Fixup nr_scanned and nr_pages.
165998879b3bSYang Shi 		 */
166098879b3bSYang Shi 		if (nr_pages > 1) {
166198879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
166298879b3bSYang Shi 			nr_pages = 1;
166398879b3bSYang Shi 		}
16641da177e4SLinus Torvalds activate_locked:
166568a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
1666ad6b6704SMinchan Kim 		if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1667ad6b6704SMinchan Kim 						PageMlocked(page)))
1668a2c43eedSHugh Dickins 			try_to_free_swap(page);
1669309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
1670ad6b6704SMinchan Kim 		if (!PageMlocked(page)) {
16719de4f22aSHuang Ying 			int type = page_is_file_lru(page);
16721da177e4SLinus Torvalds 			SetPageActive(page);
167398879b3bSYang Shi 			stat->nr_activate[type] += nr_pages;
16742262185cSRoman Gushchin 			count_memcg_page_event(page, PGACTIVATE);
1675ad6b6704SMinchan Kim 		}
16761da177e4SLinus Torvalds keep_locked:
16771da177e4SLinus Torvalds 		unlock_page(page);
16781da177e4SLinus Torvalds keep:
16791da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1680309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
16811da177e4SLinus Torvalds 	}
1682abe4c3b5SMel Gorman 
168398879b3bSYang Shi 	pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
168498879b3bSYang Shi 
1685747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
168672b252aeSMel Gorman 	try_to_unmap_flush();
16872d4894b5SMel Gorman 	free_unref_page_list(&free_pages);
1688abe4c3b5SMel Gorman 
16891da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1690886cf190SKirill Tkhai 	count_vm_events(PGACTIVATE, pgactivate);
16910a31bc97SJohannes Weiner 
169205ff5137SAndrew Morton 	return nr_reclaimed;
16931da177e4SLinus Torvalds }
16941da177e4SLinus Torvalds 
1695730ec8c0SManinder Singh unsigned int reclaim_clean_pages_from_list(struct zone *zone,
169602c6de8dSMinchan Kim 					    struct list_head *page_list)
169702c6de8dSMinchan Kim {
169802c6de8dSMinchan Kim 	struct scan_control sc = {
169902c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
170002c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
170102c6de8dSMinchan Kim 		.may_unmap = 1,
170202c6de8dSMinchan Kim 	};
17031f318a9bSJaewon Kim 	struct reclaim_stat stat;
1704730ec8c0SManinder Singh 	unsigned int nr_reclaimed;
170502c6de8dSMinchan Kim 	struct page *page, *next;
170602c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
17072d2b8d2bSYu Zhao 	unsigned int noreclaim_flag;
170802c6de8dSMinchan Kim 
170902c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1710ae37c7ffSOscar Salvador 		if (!PageHuge(page) && page_is_file_lru(page) &&
1711ae37c7ffSOscar Salvador 		    !PageDirty(page) && !__PageMovable(page) &&
1712ae37c7ffSOscar Salvador 		    !PageUnevictable(page)) {
171302c6de8dSMinchan Kim 			ClearPageActive(page);
171402c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
171502c6de8dSMinchan Kim 		}
171602c6de8dSMinchan Kim 	}
171702c6de8dSMinchan Kim 
17182d2b8d2bSYu Zhao 	/*
17192d2b8d2bSYu Zhao 	 * We should be safe here since we are only dealing with file pages and
17202d2b8d2bSYu Zhao 	 * we are not kswapd and therefore cannot write dirty file pages. But
17212d2b8d2bSYu Zhao 	 * call memalloc_noreclaim_save() anyway, just in case these conditions
17222d2b8d2bSYu Zhao 	 * change in the future.
17232d2b8d2bSYu Zhao 	 */
17242d2b8d2bSYu Zhao 	noreclaim_flag = memalloc_noreclaim_save();
17251f318a9bSJaewon Kim 	nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1726013339dfSShakeel Butt 					&stat, true);
17272d2b8d2bSYu Zhao 	memalloc_noreclaim_restore(noreclaim_flag);
17282d2b8d2bSYu Zhao 
172902c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
17302da9f630SNicholas Piggin 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
17312da9f630SNicholas Piggin 			    -(long)nr_reclaimed);
17321f318a9bSJaewon Kim 	/*
17331f318a9bSJaewon Kim 	 * Since lazyfree pages are isolated from file LRU from the beginning,
17341f318a9bSJaewon Kim 	 * they will rotate back to anonymous LRU in the end if it failed to
17351f318a9bSJaewon Kim 	 * discard so isolated count will be mismatched.
17361f318a9bSJaewon Kim 	 * Compensate the isolated count for both LRU lists.
17371f318a9bSJaewon Kim 	 */
17381f318a9bSJaewon Kim 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
17391f318a9bSJaewon Kim 			    stat.nr_lazyfree_fail);
17401f318a9bSJaewon Kim 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
17412da9f630SNicholas Piggin 			    -(long)stat.nr_lazyfree_fail);
17421f318a9bSJaewon Kim 	return nr_reclaimed;
174302c6de8dSMinchan Kim }
174402c6de8dSMinchan Kim 
17455ad333ebSAndy Whitcroft /*
17465ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
17475ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
17485ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
17495ad333ebSAndy Whitcroft  *
17505ad333ebSAndy Whitcroft  * page:	page to consider
17515ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
17525ad333ebSAndy Whitcroft  *
1753c2135f7cSAlex Shi  * returns true on success, false on failure.
17545ad333ebSAndy Whitcroft  */
1755c2135f7cSAlex Shi bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
17565ad333ebSAndy Whitcroft {
17575ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
17585ad333ebSAndy Whitcroft 	if (!PageLRU(page))
1759c2135f7cSAlex Shi 		return false;
17605ad333ebSAndy Whitcroft 
1761e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1762e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1763c2135f7cSAlex Shi 		return false;
1764894bc310SLee Schermerhorn 
1765c8244935SMel Gorman 	/*
1766c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1767c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1768c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1769c8244935SMel Gorman 	 *
1770c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1771c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1772c8244935SMel Gorman 	 */
17731276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1774c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1775c8244935SMel Gorman 		if (PageWriteback(page))
1776c2135f7cSAlex Shi 			return false;
177739deaf85SMinchan Kim 
1778c8244935SMel Gorman 		if (PageDirty(page)) {
1779c8244935SMel Gorman 			struct address_space *mapping;
178069d763fcSMel Gorman 			bool migrate_dirty;
1781c8244935SMel Gorman 
1782c8244935SMel Gorman 			/*
1783c8244935SMel Gorman 			 * Only pages without mappings or that have a
1784c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
178569d763fcSMel Gorman 			 * without blocking. However, we can be racing with
178669d763fcSMel Gorman 			 * truncation so it's necessary to lock the page
178769d763fcSMel Gorman 			 * to stabilise the mapping as truncation holds
178869d763fcSMel Gorman 			 * the page lock until after the page is removed
178969d763fcSMel Gorman 			 * from the page cache.
1790c8244935SMel Gorman 			 */
179169d763fcSMel Gorman 			if (!trylock_page(page))
1792c2135f7cSAlex Shi 				return false;
179369d763fcSMel Gorman 
1794c8244935SMel Gorman 			mapping = page_mapping(page);
1795145e1a71SHugh Dickins 			migrate_dirty = !mapping || mapping->a_ops->migratepage;
179669d763fcSMel Gorman 			unlock_page(page);
179769d763fcSMel Gorman 			if (!migrate_dirty)
1798c2135f7cSAlex Shi 				return false;
1799c8244935SMel Gorman 		}
1800c8244935SMel Gorman 	}
1801c8244935SMel Gorman 
1802f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1803c2135f7cSAlex Shi 		return false;
1804f80c0673SMinchan Kim 
1805c2135f7cSAlex Shi 	return true;
18065ad333ebSAndy Whitcroft }
18075ad333ebSAndy Whitcroft 
18087ee36a14SMel Gorman /*
18097ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
181055b65a57SEthon Paul  * be complete before mem_cgroup_update_lru_size due to a sanity check.
18117ee36a14SMel Gorman  */
18127ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1813b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
18147ee36a14SMel Gorman {
18157ee36a14SMel Gorman 	int zid;
18167ee36a14SMel Gorman 
18177ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
18187ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
18197ee36a14SMel Gorman 			continue;
18207ee36a14SMel Gorman 
1821a892cb6bSWei Yang 		update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
18227ee36a14SMel Gorman 	}
18237ee36a14SMel Gorman 
18247ee36a14SMel Gorman }
18257ee36a14SMel Gorman 
1826f611fab7SMel Gorman /*
182715b44736SHugh Dickins  * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
182815b44736SHugh Dickins  *
182915b44736SHugh Dickins  * lruvec->lru_lock is heavily contended.  Some of the functions that
18301da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
18311da177e4SLinus Torvalds  * and working on them outside the LRU lock.
18321da177e4SLinus Torvalds  *
18331da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
18341da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
18351da177e4SLinus Torvalds  *
183615b44736SHugh Dickins  * Lru_lock must be held before calling this function.
18371da177e4SLinus Torvalds  *
1838791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
18395dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
18401da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1841f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1842fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
18433cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
18441da177e4SLinus Torvalds  *
18451da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
18461da177e4SLinus Torvalds  */
184769e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
18485dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1849fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
1850a9e7c39fSKirill Tkhai 		enum lru_list lru)
18511da177e4SLinus Torvalds {
185275b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
185369e05944SAndrew Morton 	unsigned long nr_taken = 0;
1854599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
18557cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
18563db65812SJohannes Weiner 	unsigned long skipped = 0;
1857791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
1858b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
1859a9e7c39fSKirill Tkhai 	isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
18601da177e4SLinus Torvalds 
186198879b3bSYang Shi 	total_scan = 0;
1862791b48b6SMinchan Kim 	scan = 0;
186398879b3bSYang Shi 	while (scan < nr_to_scan && !list_empty(src)) {
18645ad333ebSAndy Whitcroft 		struct page *page;
18655ad333ebSAndy Whitcroft 
18661da177e4SLinus Torvalds 		page = lru_to_page(src);
18671da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
18681da177e4SLinus Torvalds 
1869d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
187098879b3bSYang Shi 		total_scan += nr_pages;
187198879b3bSYang Shi 
1872b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1873b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
187498879b3bSYang Shi 			nr_skipped[page_zonenum(page)] += nr_pages;
1875b2e18757SMel Gorman 			continue;
1876b2e18757SMel Gorman 		}
1877b2e18757SMel Gorman 
1878791b48b6SMinchan Kim 		/*
1879791b48b6SMinchan Kim 		 * Do not count skipped pages because that makes the function
1880791b48b6SMinchan Kim 		 * return with no isolated pages if the LRU mostly contains
1881791b48b6SMinchan Kim 		 * ineligible pages.  This causes the VM to not reclaim any
1882791b48b6SMinchan Kim 		 * pages, triggering a premature OOM.
188398879b3bSYang Shi 		 *
188498879b3bSYang Shi 		 * Account all tail pages of THP.  This would not cause
188598879b3bSYang Shi 		 * premature OOM since __isolate_lru_page() returns -EBUSY
188698879b3bSYang Shi 		 * only when the page is being freed somewhere else.
1887791b48b6SMinchan Kim 		 */
188898879b3bSYang Shi 		scan += nr_pages;
1889c2135f7cSAlex Shi 		if (!__isolate_lru_page_prepare(page, mode)) {
1890c2135f7cSAlex Shi 			/* It is being freed elsewhere */
1891c2135f7cSAlex Shi 			list_move(&page->lru, src);
1892c2135f7cSAlex Shi 			continue;
1893c2135f7cSAlex Shi 		}
18949df41314SAlex Shi 		/*
18959df41314SAlex Shi 		 * Be careful not to clear PageLRU until after we're
18969df41314SAlex Shi 		 * sure the page is not being freed elsewhere -- the
18979df41314SAlex Shi 		 * page release code relies on it.
18989df41314SAlex Shi 		 */
1899c2135f7cSAlex Shi 		if (unlikely(!get_page_unless_zero(page))) {
1900c2135f7cSAlex Shi 			list_move(&page->lru, src);
1901c2135f7cSAlex Shi 			continue;
1902c2135f7cSAlex Shi 		}
19039df41314SAlex Shi 
19049df41314SAlex Shi 		if (!TestClearPageLRU(page)) {
1905c2135f7cSAlex Shi 			/* Another thread is already isolating this page */
19069df41314SAlex Shi 			put_page(page);
1907c2135f7cSAlex Shi 			list_move(&page->lru, src);
1908c2135f7cSAlex Shi 			continue;
19099df41314SAlex Shi 		}
19109df41314SAlex Shi 
1911599d0c95SMel Gorman 		nr_taken += nr_pages;
1912599d0c95SMel Gorman 		nr_zone_taken[page_zonenum(page)] += nr_pages;
19135ad333ebSAndy Whitcroft 		list_move(&page->lru, dst);
19145ad333ebSAndy Whitcroft 	}
19151da177e4SLinus Torvalds 
1916b2e18757SMel Gorman 	/*
1917b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1918b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1919b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1920b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1921b2e18757SMel Gorman 	 * system at risk of premature OOM.
1922b2e18757SMel Gorman 	 */
19237cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
19247cc30fcfSMel Gorman 		int zid;
19257cc30fcfSMel Gorman 
19263db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
19277cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
19287cc30fcfSMel Gorman 			if (!nr_skipped[zid])
19297cc30fcfSMel Gorman 				continue;
19307cc30fcfSMel Gorman 
19317cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
19321265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
19337cc30fcfSMel Gorman 		}
19347cc30fcfSMel Gorman 	}
1935791b48b6SMinchan Kim 	*nr_scanned = total_scan;
19361265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1937791b48b6SMinchan Kim 				    total_scan, skipped, nr_taken, mode, lru);
1938b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
19391da177e4SLinus Torvalds 	return nr_taken;
19401da177e4SLinus Torvalds }
19411da177e4SLinus Torvalds 
194262695a84SNick Piggin /**
194362695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
194462695a84SNick Piggin  * @page: page to isolate from its LRU list
194562695a84SNick Piggin  *
194662695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
194762695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
194862695a84SNick Piggin  *
194962695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
195062695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
195162695a84SNick Piggin  *
195262695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1953894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1954894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1955894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
195662695a84SNick Piggin  *
195762695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
195862695a84SNick Piggin  * found will be decremented.
195962695a84SNick Piggin  *
196062695a84SNick Piggin  * Restrictions:
1961a5d09bedSMike Rapoport  *
196262695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
196301c4776bSHui Su  *     fundamental difference from isolate_lru_pages (which is called
196462695a84SNick Piggin  *     without a stable reference).
196562695a84SNick Piggin  * (2) the lru_lock must not be held.
196662695a84SNick Piggin  * (3) interrupts must be enabled.
196762695a84SNick Piggin  */
196862695a84SNick Piggin int isolate_lru_page(struct page *page)
196962695a84SNick Piggin {
197062695a84SNick Piggin 	int ret = -EBUSY;
197162695a84SNick Piggin 
1972309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1973cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
19740c917313SKonstantin Khlebnikov 
1975d25b5bd8SAlex Shi 	if (TestClearPageLRU(page)) {
1976fa9add64SHugh Dickins 		struct lruvec *lruvec;
197762695a84SNick Piggin 
19780c917313SKonstantin Khlebnikov 		get_page(page);
19796168d0daSAlex Shi 		lruvec = lock_page_lruvec_irq(page);
198046ae6b2cSYu Zhao 		del_page_from_lru_list(page, lruvec);
19816168d0daSAlex Shi 		unlock_page_lruvec_irq(lruvec);
1982fa9add64SHugh Dickins 		ret = 0;
198362695a84SNick Piggin 	}
1984d25b5bd8SAlex Shi 
198562695a84SNick Piggin 	return ret;
198662695a84SNick Piggin }
198762695a84SNick Piggin 
19885ad333ebSAndy Whitcroft /*
1989d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1990178821b8SXianting Tian  * then get rescheduled. When there are massive number of tasks doing page
1991d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1992d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1993d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
199435cd7815SRik van Riel  */
1995599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
199635cd7815SRik van Riel 		struct scan_control *sc)
199735cd7815SRik van Riel {
199835cd7815SRik van Riel 	unsigned long inactive, isolated;
199935cd7815SRik van Riel 
200035cd7815SRik van Riel 	if (current_is_kswapd())
200135cd7815SRik van Riel 		return 0;
200235cd7815SRik van Riel 
2003b5ead35eSJohannes Weiner 	if (!writeback_throttling_sane(sc))
200435cd7815SRik van Riel 		return 0;
200535cd7815SRik van Riel 
200635cd7815SRik van Riel 	if (file) {
2007599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2008599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
200935cd7815SRik van Riel 	} else {
2010599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2011599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
201235cd7815SRik van Riel 	}
201335cd7815SRik van Riel 
20143cf23841SFengguang Wu 	/*
20153cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
20163cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
20173cf23841SFengguang Wu 	 * deadlock.
20183cf23841SFengguang Wu 	 */
2019d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
20203cf23841SFengguang Wu 		inactive >>= 3;
20213cf23841SFengguang Wu 
202235cd7815SRik van Riel 	return isolated > inactive;
202335cd7815SRik van Riel }
202435cd7815SRik van Riel 
2025a222f341SKirill Tkhai /*
202615b44736SHugh Dickins  * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
202715b44736SHugh Dickins  * On return, @list is reused as a list of pages to be freed by the caller.
2028a222f341SKirill Tkhai  *
2029a222f341SKirill Tkhai  * Returns the number of pages moved to the given lruvec.
2030a222f341SKirill Tkhai  */
20319ef56b78SMuchun Song static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2032a222f341SKirill Tkhai 				      struct list_head *list)
203366635629SMel Gorman {
2034a222f341SKirill Tkhai 	int nr_pages, nr_moved = 0;
20353f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
2036a222f341SKirill Tkhai 	struct page *page;
203766635629SMel Gorman 
2038a222f341SKirill Tkhai 	while (!list_empty(list)) {
2039a222f341SKirill Tkhai 		page = lru_to_page(list);
2040309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
2041a222f341SKirill Tkhai 		list_del(&page->lru);
20423d06afabSAlex Shi 		if (unlikely(!page_evictable(page))) {
20436168d0daSAlex Shi 			spin_unlock_irq(&lruvec->lru_lock);
204466635629SMel Gorman 			putback_lru_page(page);
20456168d0daSAlex Shi 			spin_lock_irq(&lruvec->lru_lock);
204666635629SMel Gorman 			continue;
204766635629SMel Gorman 		}
2048fa9add64SHugh Dickins 
20493d06afabSAlex Shi 		/*
20503d06afabSAlex Shi 		 * The SetPageLRU needs to be kept here for list integrity.
20513d06afabSAlex Shi 		 * Otherwise:
20523d06afabSAlex Shi 		 *   #0 move_pages_to_lru             #1 release_pages
20533d06afabSAlex Shi 		 *   if !put_page_testzero
20543d06afabSAlex Shi 		 *				      if (put_page_testzero())
20553d06afabSAlex Shi 		 *				        !PageLRU //skip lru_lock
20563d06afabSAlex Shi 		 *     SetPageLRU()
20573d06afabSAlex Shi 		 *     list_add(&page->lru,)
20583d06afabSAlex Shi 		 *                                        list_add(&page->lru,)
20593d06afabSAlex Shi 		 */
20607a608572SLinus Torvalds 		SetPageLRU(page);
2061a222f341SKirill Tkhai 
20623d06afabSAlex Shi 		if (unlikely(put_page_testzero(page))) {
206387560179SYu Zhao 			__clear_page_lru_flags(page);
20642bcf8879SHugh Dickins 
20652bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
20666168d0daSAlex Shi 				spin_unlock_irq(&lruvec->lru_lock);
2067ff45fc3cSMatthew Wilcox (Oracle) 				destroy_compound_page(page);
20686168d0daSAlex Shi 				spin_lock_irq(&lruvec->lru_lock);
20692bcf8879SHugh Dickins 			} else
20702bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
20713d06afabSAlex Shi 
20723d06afabSAlex Shi 			continue;
20733d06afabSAlex Shi 		}
20743d06afabSAlex Shi 
2075afca9157SAlex Shi 		/*
2076afca9157SAlex Shi 		 * All pages were isolated from the same lruvec (and isolation
2077afca9157SAlex Shi 		 * inhibits memcg migration).
2078afca9157SAlex Shi 		 */
20797467c391SMuchun Song 		VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
20803a9c9788SYu Zhao 		add_page_to_lru_list(page, lruvec);
20813d06afabSAlex Shi 		nr_pages = thp_nr_pages(page);
2082a222f341SKirill Tkhai 		nr_moved += nr_pages;
208331d8fcacSJohannes Weiner 		if (PageActive(page))
208431d8fcacSJohannes Weiner 			workingset_age_nonresident(lruvec, nr_pages);
208566635629SMel Gorman 	}
208666635629SMel Gorman 
20873f79768fSHugh Dickins 	/*
20883f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
20893f79768fSHugh Dickins 	 */
2090a222f341SKirill Tkhai 	list_splice(&pages_to_free, list);
2091a222f341SKirill Tkhai 
2092a222f341SKirill Tkhai 	return nr_moved;
209366635629SMel Gorman }
209466635629SMel Gorman 
209566635629SMel Gorman /*
2096399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
2097a37b0715SNeilBrown  * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
2098399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
2099399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
2100399ba0b9SNeilBrown  */
2101399ba0b9SNeilBrown static int current_may_throttle(void)
2102399ba0b9SNeilBrown {
2103a37b0715SNeilBrown 	return !(current->flags & PF_LOCAL_THROTTLE) ||
2104399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
2105399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
2106399ba0b9SNeilBrown }
2107399ba0b9SNeilBrown 
2108399ba0b9SNeilBrown /*
2109b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
21101742f19fSAndrew Morton  * of reclaimed pages
21111da177e4SLinus Torvalds  */
21129ef56b78SMuchun Song static unsigned long
21131a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
21149e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
21151da177e4SLinus Torvalds {
21161da177e4SLinus Torvalds 	LIST_HEAD(page_list);
2117e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
2118730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
2119e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
2120060f005fSKirill Tkhai 	struct reclaim_stat stat;
2121497a6c1bSJohannes Weiner 	bool file = is_file_lru(lru);
2122f46b7912SKirill Tkhai 	enum vm_event_item item;
2123599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2124db73ee0dSMichal Hocko 	bool stalled = false;
212578dc583dSKOSAKI Motohiro 
2126599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
2127db73ee0dSMichal Hocko 		if (stalled)
2128db73ee0dSMichal Hocko 			return 0;
2129db73ee0dSMichal Hocko 
2130db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
2131db73ee0dSMichal Hocko 		msleep(100);
2132db73ee0dSMichal Hocko 		stalled = true;
213335cd7815SRik van Riel 
213435cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
213535cd7815SRik van Riel 		if (fatal_signal_pending(current))
213635cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
213735cd7815SRik van Riel 	}
213835cd7815SRik van Riel 
21391da177e4SLinus Torvalds 	lru_add_drain();
2140f80c0673SMinchan Kim 
21416168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
21421da177e4SLinus Torvalds 
21435dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
2144a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
214595d918fcSKonstantin Khlebnikov 
2146599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2147f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
2148b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
2149f46b7912SKirill Tkhai 		__count_vm_events(item, nr_scanned);
2150f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
2151497a6c1bSJohannes Weiner 	__count_vm_events(PGSCAN_ANON + file, nr_scanned);
2152497a6c1bSJohannes Weiner 
21536168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
2154d563c050SHillf Danton 
2155d563c050SHillf Danton 	if (nr_taken == 0)
215666635629SMel Gorman 		return 0;
2157b35ea17bSKOSAKI Motohiro 
2158013339dfSShakeel Butt 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
2159c661b078SAndy Whitcroft 
21606168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2161497a6c1bSJohannes Weiner 	move_pages_to_lru(lruvec, &page_list);
2162497a6c1bSJohannes Weiner 
2163497a6c1bSJohannes Weiner 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2164f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
2165b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
2166f46b7912SKirill Tkhai 		__count_vm_events(item, nr_reclaimed);
2167f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
2168497a6c1bSJohannes Weiner 	__count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
21696168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
21703f79768fSHugh Dickins 
217175cc3c91SAlex Shi 	lru_note_cost(lruvec, file, stat.nr_pageout);
2172747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
21732d4894b5SMel Gorman 	free_unref_page_list(&page_list);
2174e11da5b4SMel Gorman 
217592df3a72SMel Gorman 	/*
21761c610d5fSAndrey Ryabinin 	 * If dirty pages are scanned that are not queued for IO, it
21771c610d5fSAndrey Ryabinin 	 * implies that flushers are not doing their job. This can
21781c610d5fSAndrey Ryabinin 	 * happen when memory pressure pushes dirty pages to the end of
21791c610d5fSAndrey Ryabinin 	 * the LRU before the dirty limits are breached and the dirty
21801c610d5fSAndrey Ryabinin 	 * data has expired. It can also happen when the proportion of
21811c610d5fSAndrey Ryabinin 	 * dirty pages grows not through writes but through memory
21821c610d5fSAndrey Ryabinin 	 * pressure reclaiming all the clean cache. And in some cases,
21831c610d5fSAndrey Ryabinin 	 * the flushers simply cannot keep up with the allocation
21841c610d5fSAndrey Ryabinin 	 * rate. Nudge the flusher threads in case they are asleep.
21851c610d5fSAndrey Ryabinin 	 */
21861c610d5fSAndrey Ryabinin 	if (stat.nr_unqueued_dirty == nr_taken)
21871c610d5fSAndrey Ryabinin 		wakeup_flusher_threads(WB_REASON_VMSCAN);
21881c610d5fSAndrey Ryabinin 
2189d108c772SAndrey Ryabinin 	sc->nr.dirty += stat.nr_dirty;
2190d108c772SAndrey Ryabinin 	sc->nr.congested += stat.nr_congested;
2191d108c772SAndrey Ryabinin 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2192d108c772SAndrey Ryabinin 	sc->nr.writeback += stat.nr_writeback;
2193d108c772SAndrey Ryabinin 	sc->nr.immediate += stat.nr_immediate;
2194d108c772SAndrey Ryabinin 	sc->nr.taken += nr_taken;
2195d108c772SAndrey Ryabinin 	if (file)
2196d108c772SAndrey Ryabinin 		sc->nr.file_taken += nr_taken;
21978e950282SMel Gorman 
2198599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2199d51d1e64SSteven Rostedt 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
220005ff5137SAndrew Morton 	return nr_reclaimed;
22011da177e4SLinus Torvalds }
22021da177e4SLinus Torvalds 
220315b44736SHugh Dickins /*
220415b44736SHugh Dickins  * shrink_active_list() moves pages from the active LRU to the inactive LRU.
220515b44736SHugh Dickins  *
220615b44736SHugh Dickins  * We move them the other way if the page is referenced by one or more
220715b44736SHugh Dickins  * processes.
220815b44736SHugh Dickins  *
220915b44736SHugh Dickins  * If the pages are mostly unmapped, the processing is fast and it is
221015b44736SHugh Dickins  * appropriate to hold lru_lock across the whole operation.  But if
221115b44736SHugh Dickins  * the pages are mapped, the processing is slow (page_referenced()), so
221215b44736SHugh Dickins  * we should drop lru_lock around each page.  It's impossible to balance
221315b44736SHugh Dickins  * this, so instead we remove the pages from the LRU while processing them.
221415b44736SHugh Dickins  * It is safe to rely on PG_active against the non-LRU pages in here because
221515b44736SHugh Dickins  * nobody will play with that bit on a non-LRU page.
221615b44736SHugh Dickins  *
221715b44736SHugh Dickins  * The downside is that we have to touch page->_refcount against each page.
221815b44736SHugh Dickins  * But we had to alter page->flags anyway.
221915b44736SHugh Dickins  */
2220f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
22211a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
2222f16015fbSJohannes Weiner 			       struct scan_control *sc,
22239e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
22241cfb419bSKAMEZAWA Hiroyuki {
222544c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
2226f626012dSHugh Dickins 	unsigned long nr_scanned;
22276fe6b7e3SWu Fengguang 	unsigned long vm_flags;
22281cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
22298cab4754SWu Fengguang 	LIST_HEAD(l_active);
2230b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
22311cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
22329d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
22339d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
22343cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
2235599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
22361cfb419bSKAMEZAWA Hiroyuki 
22371da177e4SLinus Torvalds 	lru_add_drain();
2238f80c0673SMinchan Kim 
22396168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2240925b7673SJohannes Weiner 
22415dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2242a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
224389b5fae5SJohannes Weiner 
2244599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
22451cfb419bSKAMEZAWA Hiroyuki 
2246912c0572SShakeel Butt 	if (!cgroup_reclaim(sc))
2247599d0c95SMel Gorman 		__count_vm_events(PGREFILL, nr_scanned);
22482fa2690cSYafang Shao 	__count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
22499d5e6a9fSHugh Dickins 
22506168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
22511da177e4SLinus Torvalds 
22521da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
22531da177e4SLinus Torvalds 		cond_resched();
22541da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
22551da177e4SLinus Torvalds 		list_del(&page->lru);
22567e9cd484SRik van Riel 
225739b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
2258894bc310SLee Schermerhorn 			putback_lru_page(page);
2259894bc310SLee Schermerhorn 			continue;
2260894bc310SLee Schermerhorn 		}
2261894bc310SLee Schermerhorn 
2262cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
2263cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
2264cc715d99SMel Gorman 				if (page_has_private(page))
2265cc715d99SMel Gorman 					try_to_release_page(page, 0);
2266cc715d99SMel Gorman 				unlock_page(page);
2267cc715d99SMel Gorman 			}
2268cc715d99SMel Gorman 		}
2269cc715d99SMel Gorman 
2270c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
2271c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
22728cab4754SWu Fengguang 			/*
22738cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
22748cab4754SWu Fengguang 			 * give them one more trip around the active list. So
22758cab4754SWu Fengguang 			 * that executable code get better chances to stay in
22768cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
22778cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
22788cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
22798cab4754SWu Fengguang 			 * so we ignore them here.
22808cab4754SWu Fengguang 			 */
22819de4f22aSHuang Ying 			if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
22826c357848SMatthew Wilcox (Oracle) 				nr_rotated += thp_nr_pages(page);
22838cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
22848cab4754SWu Fengguang 				continue;
22858cab4754SWu Fengguang 			}
22868cab4754SWu Fengguang 		}
22877e9cd484SRik van Riel 
22885205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
22891899ad18SJohannes Weiner 		SetPageWorkingset(page);
22901da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
22911da177e4SLinus Torvalds 	}
22921da177e4SLinus Torvalds 
2293b555749aSAndrew Morton 	/*
22948cab4754SWu Fengguang 	 * Move pages back to the lru list.
2295b555749aSAndrew Morton 	 */
22966168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2297556adecbSRik van Riel 
2298a222f341SKirill Tkhai 	nr_activate = move_pages_to_lru(lruvec, &l_active);
2299a222f341SKirill Tkhai 	nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2300f372d89eSKirill Tkhai 	/* Keep all free pages in l_active list */
2301f372d89eSKirill Tkhai 	list_splice(&l_inactive, &l_active);
23029851ac13SKirill Tkhai 
23039851ac13SKirill Tkhai 	__count_vm_events(PGDEACTIVATE, nr_deactivate);
23049851ac13SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
23059851ac13SKirill Tkhai 
2306599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
23076168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
23082bcf8879SHugh Dickins 
2309f372d89eSKirill Tkhai 	mem_cgroup_uncharge_list(&l_active);
2310f372d89eSKirill Tkhai 	free_unref_page_list(&l_active);
23119d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
23129d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
23131da177e4SLinus Torvalds }
23141da177e4SLinus Torvalds 
23151a4e58ccSMinchan Kim unsigned long reclaim_pages(struct list_head *page_list)
23161a4e58ccSMinchan Kim {
2317f661d007SYang Shi 	int nid = NUMA_NO_NODE;
2318730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
23191a4e58ccSMinchan Kim 	LIST_HEAD(node_page_list);
23201a4e58ccSMinchan Kim 	struct reclaim_stat dummy_stat;
23211a4e58ccSMinchan Kim 	struct page *page;
23222d2b8d2bSYu Zhao 	unsigned int noreclaim_flag;
23231a4e58ccSMinchan Kim 	struct scan_control sc = {
23241a4e58ccSMinchan Kim 		.gfp_mask = GFP_KERNEL,
23251a4e58ccSMinchan Kim 		.priority = DEF_PRIORITY,
23261a4e58ccSMinchan Kim 		.may_writepage = 1,
23271a4e58ccSMinchan Kim 		.may_unmap = 1,
23281a4e58ccSMinchan Kim 		.may_swap = 1,
23291a4e58ccSMinchan Kim 	};
23301a4e58ccSMinchan Kim 
23312d2b8d2bSYu Zhao 	noreclaim_flag = memalloc_noreclaim_save();
23322d2b8d2bSYu Zhao 
23331a4e58ccSMinchan Kim 	while (!list_empty(page_list)) {
23341a4e58ccSMinchan Kim 		page = lru_to_page(page_list);
2335f661d007SYang Shi 		if (nid == NUMA_NO_NODE) {
23361a4e58ccSMinchan Kim 			nid = page_to_nid(page);
23371a4e58ccSMinchan Kim 			INIT_LIST_HEAD(&node_page_list);
23381a4e58ccSMinchan Kim 		}
23391a4e58ccSMinchan Kim 
23401a4e58ccSMinchan Kim 		if (nid == page_to_nid(page)) {
23411a4e58ccSMinchan Kim 			ClearPageActive(page);
23421a4e58ccSMinchan Kim 			list_move(&page->lru, &node_page_list);
23431a4e58ccSMinchan Kim 			continue;
23441a4e58ccSMinchan Kim 		}
23451a4e58ccSMinchan Kim 
23461a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
23471a4e58ccSMinchan Kim 						NODE_DATA(nid),
2348013339dfSShakeel Butt 						&sc, &dummy_stat, false);
23491a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
23501a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
23511a4e58ccSMinchan Kim 			list_del(&page->lru);
23521a4e58ccSMinchan Kim 			putback_lru_page(page);
23531a4e58ccSMinchan Kim 		}
23541a4e58ccSMinchan Kim 
2355f661d007SYang Shi 		nid = NUMA_NO_NODE;
23561a4e58ccSMinchan Kim 	}
23571a4e58ccSMinchan Kim 
23581a4e58ccSMinchan Kim 	if (!list_empty(&node_page_list)) {
23591a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
23601a4e58ccSMinchan Kim 						NODE_DATA(nid),
2361013339dfSShakeel Butt 						&sc, &dummy_stat, false);
23621a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
23631a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
23641a4e58ccSMinchan Kim 			list_del(&page->lru);
23651a4e58ccSMinchan Kim 			putback_lru_page(page);
23661a4e58ccSMinchan Kim 		}
23671a4e58ccSMinchan Kim 	}
23681a4e58ccSMinchan Kim 
23692d2b8d2bSYu Zhao 	memalloc_noreclaim_restore(noreclaim_flag);
23702d2b8d2bSYu Zhao 
23711a4e58ccSMinchan Kim 	return nr_reclaimed;
23721a4e58ccSMinchan Kim }
23731a4e58ccSMinchan Kim 
2374b91ac374SJohannes Weiner static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2375b91ac374SJohannes Weiner 				 struct lruvec *lruvec, struct scan_control *sc)
2376b91ac374SJohannes Weiner {
2377b91ac374SJohannes Weiner 	if (is_active_lru(lru)) {
2378b91ac374SJohannes Weiner 		if (sc->may_deactivate & (1 << is_file_lru(lru)))
2379b91ac374SJohannes Weiner 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2380b91ac374SJohannes Weiner 		else
2381b91ac374SJohannes Weiner 			sc->skipped_deactivate = 1;
2382b91ac374SJohannes Weiner 		return 0;
2383b91ac374SJohannes Weiner 	}
2384b91ac374SJohannes Weiner 
2385b91ac374SJohannes Weiner 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2386b91ac374SJohannes Weiner }
2387b91ac374SJohannes Weiner 
238859dc76b0SRik van Riel /*
238959dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
239059dc76b0SRik van Riel  * to do too much work.
239114797e23SKOSAKI Motohiro  *
239259dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
239359dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
239459dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
239559dc76b0SRik van Riel  *
239659dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
239759dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
239859dc76b0SRik van Riel  *
23992a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
24002a2e4885SJohannes Weiner  *
240159dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
24023a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
240359dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
240459dc76b0SRik van Riel  *
240559dc76b0SRik van Riel  * total     target    max
240659dc76b0SRik van Riel  * memory    ratio     inactive
240759dc76b0SRik van Riel  * -------------------------------------
240859dc76b0SRik van Riel  *   10MB       1         5MB
240959dc76b0SRik van Riel  *  100MB       1        50MB
241059dc76b0SRik van Riel  *    1GB       3       250MB
241159dc76b0SRik van Riel  *   10GB      10       0.9GB
241259dc76b0SRik van Riel  *  100GB      31         3GB
241359dc76b0SRik van Riel  *    1TB     101        10GB
241459dc76b0SRik van Riel  *   10TB     320        32GB
241514797e23SKOSAKI Motohiro  */
2416b91ac374SJohannes Weiner static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
241714797e23SKOSAKI Motohiro {
2418b91ac374SJohannes Weiner 	enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
24192a2e4885SJohannes Weiner 	unsigned long inactive, active;
24202a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
242159dc76b0SRik van Riel 	unsigned long gb;
242259dc76b0SRik van Riel 
2423b91ac374SJohannes Weiner 	inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2424b91ac374SJohannes Weiner 	active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2425f8d1a311SMel Gorman 
242659dc76b0SRik van Riel 	gb = (inactive + active) >> (30 - PAGE_SHIFT);
24274002570cSJoonsoo Kim 	if (gb)
242859dc76b0SRik van Riel 		inactive_ratio = int_sqrt(10 * gb);
2429b39415b2SRik van Riel 	else
243059dc76b0SRik van Riel 		inactive_ratio = 1;
2431fd538803SMichal Hocko 
243259dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2433b39415b2SRik van Riel }
2434b39415b2SRik van Riel 
24359a265114SJohannes Weiner enum scan_balance {
24369a265114SJohannes Weiner 	SCAN_EQUAL,
24379a265114SJohannes Weiner 	SCAN_FRACT,
24389a265114SJohannes Weiner 	SCAN_ANON,
24399a265114SJohannes Weiner 	SCAN_FILE,
24409a265114SJohannes Weiner };
24419a265114SJohannes Weiner 
24421da177e4SLinus Torvalds /*
24434f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
24444f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
24454f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
24464f98a2feSRik van Riel  * onto the active list instead of evict.
24474f98a2feSRik van Riel  *
2448be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2449be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
24504f98a2feSRik van Riel  */
2451afaf07a6SJohannes Weiner static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2452afaf07a6SJohannes Weiner 			   unsigned long *nr)
24534f98a2feSRik van Riel {
2454afaf07a6SJohannes Weiner 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2455d483a5ddSJohannes Weiner 	unsigned long anon_cost, file_cost, total_cost;
245633377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
2457ed017373SYu Zhao 	u64 fraction[ANON_AND_FILE];
24589a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
24599a265114SJohannes Weiner 	enum scan_balance scan_balance;
24609a265114SJohannes Weiner 	unsigned long ap, fp;
24619a265114SJohannes Weiner 	enum lru_list lru;
246276a33fc3SShaohua Li 
246376a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2464d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
24659a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
246676a33fc3SShaohua Li 		goto out;
246776a33fc3SShaohua Li 	}
24684f98a2feSRik van Riel 
246910316b31SJohannes Weiner 	/*
247010316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
247110316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
247210316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
247310316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
247410316b31SJohannes Weiner 	 * too expensive.
247510316b31SJohannes Weiner 	 */
2476b5ead35eSJohannes Weiner 	if (cgroup_reclaim(sc) && !swappiness) {
24779a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
247810316b31SJohannes Weiner 		goto out;
247910316b31SJohannes Weiner 	}
248010316b31SJohannes Weiner 
248110316b31SJohannes Weiner 	/*
248210316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
248310316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
248410316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
248510316b31SJohannes Weiner 	 */
248602695175SJohannes Weiner 	if (!sc->priority && swappiness) {
24879a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
248810316b31SJohannes Weiner 		goto out;
248910316b31SJohannes Weiner 	}
249010316b31SJohannes Weiner 
249111d16c25SJohannes Weiner 	/*
249253138ceaSJohannes Weiner 	 * If the system is almost out of file pages, force-scan anon.
249362376251SJohannes Weiner 	 */
2494b91ac374SJohannes Weiner 	if (sc->file_is_tiny) {
249562376251SJohannes Weiner 		scan_balance = SCAN_ANON;
249662376251SJohannes Weiner 		goto out;
249762376251SJohannes Weiner 	}
249862376251SJohannes Weiner 
249962376251SJohannes Weiner 	/*
2500b91ac374SJohannes Weiner 	 * If there is enough inactive page cache, we do not reclaim
2501b91ac374SJohannes Weiner 	 * anything from the anonymous working right now.
2502e9868505SRik van Riel 	 */
2503b91ac374SJohannes Weiner 	if (sc->cache_trim_mode) {
25049a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2505e9868505SRik van Riel 		goto out;
25064f98a2feSRik van Riel 	}
25074f98a2feSRik van Riel 
25089a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
25094f98a2feSRik van Riel 	/*
2510314b57fbSJohannes Weiner 	 * Calculate the pressure balance between anon and file pages.
2511314b57fbSJohannes Weiner 	 *
2512314b57fbSJohannes Weiner 	 * The amount of pressure we put on each LRU is inversely
2513314b57fbSJohannes Weiner 	 * proportional to the cost of reclaiming each list, as
2514314b57fbSJohannes Weiner 	 * determined by the share of pages that are refaulting, times
2515314b57fbSJohannes Weiner 	 * the relative IO cost of bringing back a swapped out
2516314b57fbSJohannes Weiner 	 * anonymous page vs reloading a filesystem page (swappiness).
2517314b57fbSJohannes Weiner 	 *
2518d483a5ddSJohannes Weiner 	 * Although we limit that influence to ensure no list gets
2519d483a5ddSJohannes Weiner 	 * left behind completely: at least a third of the pressure is
2520d483a5ddSJohannes Weiner 	 * applied, before swappiness.
2521d483a5ddSJohannes Weiner 	 *
2522314b57fbSJohannes Weiner 	 * With swappiness at 100, anon and file have equal IO cost.
252358c37f6eSKOSAKI Motohiro 	 */
2524d483a5ddSJohannes Weiner 	total_cost = sc->anon_cost + sc->file_cost;
2525d483a5ddSJohannes Weiner 	anon_cost = total_cost + sc->anon_cost;
2526d483a5ddSJohannes Weiner 	file_cost = total_cost + sc->file_cost;
2527d483a5ddSJohannes Weiner 	total_cost = anon_cost + file_cost;
252858c37f6eSKOSAKI Motohiro 
2529d483a5ddSJohannes Weiner 	ap = swappiness * (total_cost + 1);
2530d483a5ddSJohannes Weiner 	ap /= anon_cost + 1;
25314f98a2feSRik van Riel 
2532d483a5ddSJohannes Weiner 	fp = (200 - swappiness) * (total_cost + 1);
2533d483a5ddSJohannes Weiner 	fp /= file_cost + 1;
25344f98a2feSRik van Riel 
253576a33fc3SShaohua Li 	fraction[0] = ap;
253676a33fc3SShaohua Li 	fraction[1] = fp;
2537a4fe1631SJohannes Weiner 	denominator = ap + fp;
253876a33fc3SShaohua Li out:
25394111304dSHugh Dickins 	for_each_evictable_lru(lru) {
25404111304dSHugh Dickins 		int file = is_file_lru(lru);
25419783aa99SChris Down 		unsigned long lruvec_size;
2542f56ce412SJohannes Weiner 		unsigned long low, min;
254376a33fc3SShaohua Li 		unsigned long scan;
254476a33fc3SShaohua Li 
25459783aa99SChris Down 		lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2546f56ce412SJohannes Weiner 		mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2547f56ce412SJohannes Weiner 				      &min, &low);
25489783aa99SChris Down 
2549f56ce412SJohannes Weiner 		if (min || low) {
25509783aa99SChris Down 			/*
25519783aa99SChris Down 			 * Scale a cgroup's reclaim pressure by proportioning
25529783aa99SChris Down 			 * its current usage to its memory.low or memory.min
25539783aa99SChris Down 			 * setting.
25549783aa99SChris Down 			 *
25559783aa99SChris Down 			 * This is important, as otherwise scanning aggression
25569783aa99SChris Down 			 * becomes extremely binary -- from nothing as we
25579783aa99SChris Down 			 * approach the memory protection threshold, to totally
25589783aa99SChris Down 			 * nominal as we exceed it.  This results in requiring
25599783aa99SChris Down 			 * setting extremely liberal protection thresholds. It
25609783aa99SChris Down 			 * also means we simply get no protection at all if we
25619783aa99SChris Down 			 * set it too low, which is not ideal.
25621bc63fb1SChris Down 			 *
25631bc63fb1SChris Down 			 * If there is any protection in place, we reduce scan
25641bc63fb1SChris Down 			 * pressure by how much of the total memory used is
25651bc63fb1SChris Down 			 * within protection thresholds.
25669783aa99SChris Down 			 *
25679de7ca46SChris Down 			 * There is one special case: in the first reclaim pass,
25689de7ca46SChris Down 			 * we skip over all groups that are within their low
25699de7ca46SChris Down 			 * protection. If that fails to reclaim enough pages to
25709de7ca46SChris Down 			 * satisfy the reclaim goal, we come back and override
25719de7ca46SChris Down 			 * the best-effort low protection. However, we still
25729de7ca46SChris Down 			 * ideally want to honor how well-behaved groups are in
25739de7ca46SChris Down 			 * that case instead of simply punishing them all
25749de7ca46SChris Down 			 * equally. As such, we reclaim them based on how much
25751bc63fb1SChris Down 			 * memory they are using, reducing the scan pressure
25761bc63fb1SChris Down 			 * again by how much of the total memory used is under
25771bc63fb1SChris Down 			 * hard protection.
25789783aa99SChris Down 			 */
25791bc63fb1SChris Down 			unsigned long cgroup_size = mem_cgroup_size(memcg);
2580f56ce412SJohannes Weiner 			unsigned long protection;
2581f56ce412SJohannes Weiner 
2582f56ce412SJohannes Weiner 			/* memory.low scaling, make sure we retry before OOM */
2583f56ce412SJohannes Weiner 			if (!sc->memcg_low_reclaim && low > min) {
2584f56ce412SJohannes Weiner 				protection = low;
2585f56ce412SJohannes Weiner 				sc->memcg_low_skipped = 1;
2586f56ce412SJohannes Weiner 			} else {
2587f56ce412SJohannes Weiner 				protection = min;
2588f56ce412SJohannes Weiner 			}
25891bc63fb1SChris Down 
25901bc63fb1SChris Down 			/* Avoid TOCTOU with earlier protection check */
25911bc63fb1SChris Down 			cgroup_size = max(cgroup_size, protection);
25921bc63fb1SChris Down 
25931bc63fb1SChris Down 			scan = lruvec_size - lruvec_size * protection /
25941bc63fb1SChris Down 				cgroup_size;
25959783aa99SChris Down 
25969783aa99SChris Down 			/*
25971bc63fb1SChris Down 			 * Minimally target SWAP_CLUSTER_MAX pages to keep
259855b65a57SEthon Paul 			 * reclaim moving forwards, avoiding decrementing
25999de7ca46SChris Down 			 * sc->priority further than desirable.
26009783aa99SChris Down 			 */
26011bc63fb1SChris Down 			scan = max(scan, SWAP_CLUSTER_MAX);
26029783aa99SChris Down 		} else {
26039783aa99SChris Down 			scan = lruvec_size;
26049783aa99SChris Down 		}
26059783aa99SChris Down 
26069783aa99SChris Down 		scan >>= sc->priority;
26079783aa99SChris Down 
2608688035f7SJohannes Weiner 		/*
2609688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2610688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2611688035f7SJohannes Weiner 		 */
2612688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
26139783aa99SChris Down 			scan = min(lruvec_size, SWAP_CLUSTER_MAX);
26149a265114SJohannes Weiner 
26159a265114SJohannes Weiner 		switch (scan_balance) {
26169a265114SJohannes Weiner 		case SCAN_EQUAL:
26179a265114SJohannes Weiner 			/* Scan lists relative to size */
26189a265114SJohannes Weiner 			break;
26199a265114SJohannes Weiner 		case SCAN_FRACT:
26209a265114SJohannes Weiner 			/*
26219a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
26229a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
262376073c64SGavin Shan 			 * Make sure we don't miss the last page on
262476073c64SGavin Shan 			 * the offlined memory cgroups because of a
262576073c64SGavin Shan 			 * round-off error.
26269a265114SJohannes Weiner 			 */
262776073c64SGavin Shan 			scan = mem_cgroup_online(memcg) ?
262876073c64SGavin Shan 			       div64_u64(scan * fraction[file], denominator) :
262976073c64SGavin Shan 			       DIV64_U64_ROUND_UP(scan * fraction[file],
26306f04f48dSSuleiman Souhlal 						  denominator);
26319a265114SJohannes Weiner 			break;
26329a265114SJohannes Weiner 		case SCAN_FILE:
26339a265114SJohannes Weiner 		case SCAN_ANON:
26349a265114SJohannes Weiner 			/* Scan one type exclusively */
2635e072bff6SMateusz Nosek 			if ((scan_balance == SCAN_FILE) != file)
26369a265114SJohannes Weiner 				scan = 0;
26379a265114SJohannes Weiner 			break;
26389a265114SJohannes Weiner 		default:
26399a265114SJohannes Weiner 			/* Look ma, no brain */
26409a265114SJohannes Weiner 			BUG();
26419a265114SJohannes Weiner 		}
26426b4f7799SJohannes Weiner 
26434111304dSHugh Dickins 		nr[lru] = scan;
264476a33fc3SShaohua Li 	}
26456e08a369SWu Fengguang }
26464f98a2feSRik van Riel 
2647afaf07a6SJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
26489b4f98cdSJohannes Weiner {
26499b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2650e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
26519b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
26529b4f98cdSJohannes Weiner 	enum lru_list lru;
26539b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
26549b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
26559b4f98cdSJohannes Weiner 	struct blk_plug plug;
26561a501907SMel Gorman 	bool scan_adjusted;
26579b4f98cdSJohannes Weiner 
2658afaf07a6SJohannes Weiner 	get_scan_count(lruvec, sc, nr);
26599b4f98cdSJohannes Weiner 
2660e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2661e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2662e82e0561SMel Gorman 
26631a501907SMel Gorman 	/*
26641a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
26651a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
26661a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
26671a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
26681a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
26691a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
26701a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
26711a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
26721a501907SMel Gorman 	 * dropped to zero at the first pass.
26731a501907SMel Gorman 	 */
2674b5ead35eSJohannes Weiner 	scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
26751a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
26761a501907SMel Gorman 
26779b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
26789b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
26799b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2680e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2681e82e0561SMel Gorman 		unsigned long nr_scanned;
2682e82e0561SMel Gorman 
26839b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
26849b4f98cdSJohannes Weiner 			if (nr[lru]) {
26859b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
26869b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
26879b4f98cdSJohannes Weiner 
26889b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
26893b991208SJohannes Weiner 							    lruvec, sc);
26909b4f98cdSJohannes Weiner 			}
26919b4f98cdSJohannes Weiner 		}
2692e82e0561SMel Gorman 
2693bd041733SMichal Hocko 		cond_resched();
2694bd041733SMichal Hocko 
2695e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2696e82e0561SMel Gorman 			continue;
2697e82e0561SMel Gorman 
26989b4f98cdSJohannes Weiner 		/*
2699e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
27001a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2701e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2702e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2703e82e0561SMel Gorman 		 * proportional to the original scan target.
2704e82e0561SMel Gorman 		 */
2705e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2706e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2707e82e0561SMel Gorman 
27081a501907SMel Gorman 		/*
27091a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
27101a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
27111a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
27121a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
27131a501907SMel Gorman 		 */
27141a501907SMel Gorman 		if (!nr_file || !nr_anon)
27151a501907SMel Gorman 			break;
27161a501907SMel Gorman 
2717e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2718e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2719e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2720e82e0561SMel Gorman 			lru = LRU_BASE;
2721e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2722e82e0561SMel Gorman 		} else {
2723e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2724e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2725e82e0561SMel Gorman 			lru = LRU_FILE;
2726e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2727e82e0561SMel Gorman 		}
2728e82e0561SMel Gorman 
2729e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2730e82e0561SMel Gorman 		nr[lru] = 0;
2731e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2732e82e0561SMel Gorman 
2733e82e0561SMel Gorman 		/*
2734e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2735e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2736e82e0561SMel Gorman 		 */
2737e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2738e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2739e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2740e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2741e82e0561SMel Gorman 
2742e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2743e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2744e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2745e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2746e82e0561SMel Gorman 
2747e82e0561SMel Gorman 		scan_adjusted = true;
27489b4f98cdSJohannes Weiner 	}
27499b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
27509b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
27519b4f98cdSJohannes Weiner 
27529b4f98cdSJohannes Weiner 	/*
27539b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
27549b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
27559b4f98cdSJohannes Weiner 	 */
2756b91ac374SJohannes Weiner 	if (total_swap_pages && inactive_is_low(lruvec, LRU_INACTIVE_ANON))
27579b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
27589b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
27599b4f98cdSJohannes Weiner }
27609b4f98cdSJohannes Weiner 
276123b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
27629e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
276323b9da55SMel Gorman {
2764d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
276523b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
27669e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
276723b9da55SMel Gorman 		return true;
276823b9da55SMel Gorman 
276923b9da55SMel Gorman 	return false;
277023b9da55SMel Gorman }
277123b9da55SMel Gorman 
27724f98a2feSRik van Riel /*
277323b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
277423b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
277523b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
2776df3a45f9SQiwu Chen  * calls try_to_compact_pages() that it will have enough free pages to succeed.
277723b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
27783e7d3449SMel Gorman  */
2779a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
27803e7d3449SMel Gorman 					unsigned long nr_reclaimed,
27813e7d3449SMel Gorman 					struct scan_control *sc)
27823e7d3449SMel Gorman {
27833e7d3449SMel Gorman 	unsigned long pages_for_compaction;
27843e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2785a9dd0a83SMel Gorman 	int z;
27863e7d3449SMel Gorman 
27873e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
27889e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
27893e7d3449SMel Gorman 		return false;
27903e7d3449SMel Gorman 
27913e7d3449SMel Gorman 	/*
27925ee04716SVlastimil Babka 	 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
27935ee04716SVlastimil Babka 	 * number of pages that were scanned. This will return to the caller
27945ee04716SVlastimil Babka 	 * with the risk reclaim/compaction and the resulting allocation attempt
27955ee04716SVlastimil Babka 	 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
27965ee04716SVlastimil Babka 	 * allocations through requiring that the full LRU list has been scanned
27975ee04716SVlastimil Babka 	 * first, by assuming that zero delta of sc->nr_scanned means full LRU
27985ee04716SVlastimil Babka 	 * scan, but that approximation was wrong, and there were corner cases
27995ee04716SVlastimil Babka 	 * where always a non-zero amount of pages were scanned.
28002876592fSMel Gorman 	 */
28012876592fSMel Gorman 	if (!nr_reclaimed)
28022876592fSMel Gorman 		return false;
28033e7d3449SMel Gorman 
28043e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2805a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2806a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
28076aa303deSMel Gorman 		if (!managed_zone(zone))
2808a9dd0a83SMel Gorman 			continue;
2809a9dd0a83SMel Gorman 
2810a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2811cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
28123e7d3449SMel Gorman 		case COMPACT_CONTINUE:
28133e7d3449SMel Gorman 			return false;
28143e7d3449SMel Gorman 		default:
2815a9dd0a83SMel Gorman 			/* check next zone */
2816a9dd0a83SMel Gorman 			;
28173e7d3449SMel Gorman 		}
28183e7d3449SMel Gorman 	}
28191c6c1597SHillf Danton 
28201c6c1597SHillf Danton 	/*
28211c6c1597SHillf Danton 	 * If we have not reclaimed enough pages for compaction and the
28221c6c1597SHillf Danton 	 * inactive lists are large enough, continue reclaiming
28231c6c1597SHillf Danton 	 */
28241c6c1597SHillf Danton 	pages_for_compaction = compact_gap(sc->order);
28251c6c1597SHillf Danton 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
28261c6c1597SHillf Danton 	if (get_nr_swap_pages() > 0)
28271c6c1597SHillf Danton 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
28281c6c1597SHillf Danton 
28295ee04716SVlastimil Babka 	return inactive_lru_pages > pages_for_compaction;
2830a9dd0a83SMel Gorman }
28313e7d3449SMel Gorman 
28320f6a5cffSJohannes Weiner static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
2833f16015fbSJohannes Weiner {
28340f6a5cffSJohannes Weiner 	struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
2835694fbc0fSAndrew Morton 	struct mem_cgroup *memcg;
2836d108c772SAndrey Ryabinin 
28370f6a5cffSJohannes Weiner 	memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
2838694fbc0fSAndrew Morton 	do {
2839afaf07a6SJohannes Weiner 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
28408e8ae645SJohannes Weiner 		unsigned long reclaimed;
2841cb731d6cSVladimir Davydov 		unsigned long scanned;
28429b4f98cdSJohannes Weiner 
2843e3336cabSXunlei Pang 		/*
2844e3336cabSXunlei Pang 		 * This loop can become CPU-bound when target memcgs
2845e3336cabSXunlei Pang 		 * aren't eligible for reclaim - either because they
2846e3336cabSXunlei Pang 		 * don't have any reclaimable pages, or because their
2847e3336cabSXunlei Pang 		 * memory is explicitly protected. Avoid soft lockups.
2848e3336cabSXunlei Pang 		 */
2849e3336cabSXunlei Pang 		cond_resched();
2850e3336cabSXunlei Pang 
285145c7f7e1SChris Down 		mem_cgroup_calculate_protection(target_memcg, memcg);
285245c7f7e1SChris Down 
285345c7f7e1SChris Down 		if (mem_cgroup_below_min(memcg)) {
2854bf8d5d52SRoman Gushchin 			/*
2855bf8d5d52SRoman Gushchin 			 * Hard protection.
2856bf8d5d52SRoman Gushchin 			 * If there is no reclaimable memory, OOM.
2857bf8d5d52SRoman Gushchin 			 */
2858bf8d5d52SRoman Gushchin 			continue;
285945c7f7e1SChris Down 		} else if (mem_cgroup_below_low(memcg)) {
2860bf8d5d52SRoman Gushchin 			/*
2861bf8d5d52SRoman Gushchin 			 * Soft protection.
2862bf8d5d52SRoman Gushchin 			 * Respect the protection only as long as
2863bf8d5d52SRoman Gushchin 			 * there is an unprotected supply
2864bf8d5d52SRoman Gushchin 			 * of reclaimable memory from other cgroups.
2865bf8d5d52SRoman Gushchin 			 */
2866d6622f63SYisheng Xie 			if (!sc->memcg_low_reclaim) {
2867d6622f63SYisheng Xie 				sc->memcg_low_skipped = 1;
2868241994edSJohannes Weiner 				continue;
2869d6622f63SYisheng Xie 			}
2870e27be240SJohannes Weiner 			memcg_memory_event(memcg, MEMCG_LOW);
2871241994edSJohannes Weiner 		}
2872241994edSJohannes Weiner 
28738e8ae645SJohannes Weiner 		reclaimed = sc->nr_reclaimed;
2874cb731d6cSVladimir Davydov 		scanned = sc->nr_scanned;
2875afaf07a6SJohannes Weiner 
2876afaf07a6SJohannes Weiner 		shrink_lruvec(lruvec, sc);
2877f9be23d6SKonstantin Khlebnikov 
287828360f39SMel Gorman 		shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
287928360f39SMel Gorman 			    sc->priority);
2880cb731d6cSVladimir Davydov 
28818e8ae645SJohannes Weiner 		/* Record the group's reclaim efficiency */
28828e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, memcg, false,
28838e8ae645SJohannes Weiner 			   sc->nr_scanned - scanned,
28848e8ae645SJohannes Weiner 			   sc->nr_reclaimed - reclaimed);
28858e8ae645SJohannes Weiner 
28860f6a5cffSJohannes Weiner 	} while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
28870f6a5cffSJohannes Weiner }
28880f6a5cffSJohannes Weiner 
28896c9e0907SLiu Song static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
28900f6a5cffSJohannes Weiner {
28910f6a5cffSJohannes Weiner 	struct reclaim_state *reclaim_state = current->reclaim_state;
28920f6a5cffSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
28931b05117dSJohannes Weiner 	struct lruvec *target_lruvec;
28940f6a5cffSJohannes Weiner 	bool reclaimable = false;
2895b91ac374SJohannes Weiner 	unsigned long file;
28960f6a5cffSJohannes Weiner 
28971b05117dSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
28981b05117dSJohannes Weiner 
28990f6a5cffSJohannes Weiner again:
2900*aa48e47eSShakeel Butt 	/*
2901*aa48e47eSShakeel Butt 	 * Flush the memory cgroup stats, so that we read accurate per-memcg
2902*aa48e47eSShakeel Butt 	 * lruvec stats for heuristics.
2903*aa48e47eSShakeel Butt 	 */
2904*aa48e47eSShakeel Butt 	mem_cgroup_flush_stats();
2905*aa48e47eSShakeel Butt 
29060f6a5cffSJohannes Weiner 	memset(&sc->nr, 0, sizeof(sc->nr));
29070f6a5cffSJohannes Weiner 
29080f6a5cffSJohannes Weiner 	nr_reclaimed = sc->nr_reclaimed;
29090f6a5cffSJohannes Weiner 	nr_scanned = sc->nr_scanned;
29100f6a5cffSJohannes Weiner 
291153138ceaSJohannes Weiner 	/*
29127cf111bcSJohannes Weiner 	 * Determine the scan balance between anon and file LRUs.
29137cf111bcSJohannes Weiner 	 */
29146168d0daSAlex Shi 	spin_lock_irq(&target_lruvec->lru_lock);
29157cf111bcSJohannes Weiner 	sc->anon_cost = target_lruvec->anon_cost;
29167cf111bcSJohannes Weiner 	sc->file_cost = target_lruvec->file_cost;
29176168d0daSAlex Shi 	spin_unlock_irq(&target_lruvec->lru_lock);
29187cf111bcSJohannes Weiner 
29197cf111bcSJohannes Weiner 	/*
2920b91ac374SJohannes Weiner 	 * Target desirable inactive:active list ratios for the anon
2921b91ac374SJohannes Weiner 	 * and file LRU lists.
2922b91ac374SJohannes Weiner 	 */
2923b91ac374SJohannes Weiner 	if (!sc->force_deactivate) {
2924b91ac374SJohannes Weiner 		unsigned long refaults;
2925b91ac374SJohannes Weiner 
2926170b04b7SJoonsoo Kim 		refaults = lruvec_page_state(target_lruvec,
2927170b04b7SJoonsoo Kim 				WORKINGSET_ACTIVATE_ANON);
2928170b04b7SJoonsoo Kim 		if (refaults != target_lruvec->refaults[0] ||
2929170b04b7SJoonsoo Kim 			inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2930b91ac374SJohannes Weiner 			sc->may_deactivate |= DEACTIVATE_ANON;
2931b91ac374SJohannes Weiner 		else
2932b91ac374SJohannes Weiner 			sc->may_deactivate &= ~DEACTIVATE_ANON;
2933b91ac374SJohannes Weiner 
2934b91ac374SJohannes Weiner 		/*
2935b91ac374SJohannes Weiner 		 * When refaults are being observed, it means a new
2936b91ac374SJohannes Weiner 		 * workingset is being established. Deactivate to get
2937b91ac374SJohannes Weiner 		 * rid of any stale active pages quickly.
2938b91ac374SJohannes Weiner 		 */
2939b91ac374SJohannes Weiner 		refaults = lruvec_page_state(target_lruvec,
2940170b04b7SJoonsoo Kim 				WORKINGSET_ACTIVATE_FILE);
2941170b04b7SJoonsoo Kim 		if (refaults != target_lruvec->refaults[1] ||
2942b91ac374SJohannes Weiner 		    inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2943b91ac374SJohannes Weiner 			sc->may_deactivate |= DEACTIVATE_FILE;
2944b91ac374SJohannes Weiner 		else
2945b91ac374SJohannes Weiner 			sc->may_deactivate &= ~DEACTIVATE_FILE;
2946b91ac374SJohannes Weiner 	} else
2947b91ac374SJohannes Weiner 		sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2948b91ac374SJohannes Weiner 
2949b91ac374SJohannes Weiner 	/*
2950b91ac374SJohannes Weiner 	 * If we have plenty of inactive file pages that aren't
2951b91ac374SJohannes Weiner 	 * thrashing, try to reclaim those first before touching
2952b91ac374SJohannes Weiner 	 * anonymous pages.
2953b91ac374SJohannes Weiner 	 */
2954b91ac374SJohannes Weiner 	file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2955b91ac374SJohannes Weiner 	if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2956b91ac374SJohannes Weiner 		sc->cache_trim_mode = 1;
2957b91ac374SJohannes Weiner 	else
2958b91ac374SJohannes Weiner 		sc->cache_trim_mode = 0;
2959b91ac374SJohannes Weiner 
2960b91ac374SJohannes Weiner 	/*
296153138ceaSJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
296253138ceaSJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
296353138ceaSJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
296453138ceaSJohannes Weiner 	 * shrinks, so does the window for rotation from references.
296553138ceaSJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
296653138ceaSJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
296753138ceaSJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
296853138ceaSJohannes Weiner 	 */
296953138ceaSJohannes Weiner 	if (!cgroup_reclaim(sc)) {
297053138ceaSJohannes Weiner 		unsigned long total_high_wmark = 0;
2971b91ac374SJohannes Weiner 		unsigned long free, anon;
2972b91ac374SJohannes Weiner 		int z;
297353138ceaSJohannes Weiner 
297453138ceaSJohannes Weiner 		free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
297553138ceaSJohannes Weiner 		file = node_page_state(pgdat, NR_ACTIVE_FILE) +
297653138ceaSJohannes Weiner 			   node_page_state(pgdat, NR_INACTIVE_FILE);
297753138ceaSJohannes Weiner 
297853138ceaSJohannes Weiner 		for (z = 0; z < MAX_NR_ZONES; z++) {
297953138ceaSJohannes Weiner 			struct zone *zone = &pgdat->node_zones[z];
298053138ceaSJohannes Weiner 			if (!managed_zone(zone))
298153138ceaSJohannes Weiner 				continue;
298253138ceaSJohannes Weiner 
298353138ceaSJohannes Weiner 			total_high_wmark += high_wmark_pages(zone);
298453138ceaSJohannes Weiner 		}
298553138ceaSJohannes Weiner 
2986b91ac374SJohannes Weiner 		/*
2987b91ac374SJohannes Weiner 		 * Consider anon: if that's low too, this isn't a
2988b91ac374SJohannes Weiner 		 * runaway file reclaim problem, but rather just
2989b91ac374SJohannes Weiner 		 * extreme pressure. Reclaim as per usual then.
2990b91ac374SJohannes Weiner 		 */
2991b91ac374SJohannes Weiner 		anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2992b91ac374SJohannes Weiner 
2993b91ac374SJohannes Weiner 		sc->file_is_tiny =
2994b91ac374SJohannes Weiner 			file + free <= total_high_wmark &&
2995b91ac374SJohannes Weiner 			!(sc->may_deactivate & DEACTIVATE_ANON) &&
2996b91ac374SJohannes Weiner 			anon >> sc->priority;
299753138ceaSJohannes Weiner 	}
299853138ceaSJohannes Weiner 
29990f6a5cffSJohannes Weiner 	shrink_node_memcgs(pgdat, sc);
300070ddf637SAnton Vorontsov 
30016b4f7799SJohannes Weiner 	if (reclaim_state) {
3002cb731d6cSVladimir Davydov 		sc->nr_reclaimed += reclaim_state->reclaimed_slab;
30036b4f7799SJohannes Weiner 		reclaim_state->reclaimed_slab = 0;
30046b4f7799SJohannes Weiner 	}
30056b4f7799SJohannes Weiner 
30068e8ae645SJohannes Weiner 	/* Record the subtree's reclaim efficiency */
30071b05117dSJohannes Weiner 	vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
300870ddf637SAnton Vorontsov 		   sc->nr_scanned - nr_scanned,
300970ddf637SAnton Vorontsov 		   sc->nr_reclaimed - nr_reclaimed);
301070ddf637SAnton Vorontsov 
30112344d7e4SJohannes Weiner 	if (sc->nr_reclaimed - nr_reclaimed)
30122344d7e4SJohannes Weiner 		reclaimable = true;
30132344d7e4SJohannes Weiner 
3014e3c1ac58SAndrey Ryabinin 	if (current_is_kswapd()) {
3015d108c772SAndrey Ryabinin 		/*
3016e3c1ac58SAndrey Ryabinin 		 * If reclaim is isolating dirty pages under writeback,
3017e3c1ac58SAndrey Ryabinin 		 * it implies that the long-lived page allocation rate
3018e3c1ac58SAndrey Ryabinin 		 * is exceeding the page laundering rate. Either the
3019e3c1ac58SAndrey Ryabinin 		 * global limits are not being effective at throttling
3020e3c1ac58SAndrey Ryabinin 		 * processes due to the page distribution throughout
3021e3c1ac58SAndrey Ryabinin 		 * zones or there is heavy usage of a slow backing
3022e3c1ac58SAndrey Ryabinin 		 * device. The only option is to throttle from reclaim
3023e3c1ac58SAndrey Ryabinin 		 * context which is not ideal as there is no guarantee
3024d108c772SAndrey Ryabinin 		 * the dirtying process is throttled in the same way
3025d108c772SAndrey Ryabinin 		 * balance_dirty_pages() manages.
3026d108c772SAndrey Ryabinin 		 *
3027e3c1ac58SAndrey Ryabinin 		 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
3028e3c1ac58SAndrey Ryabinin 		 * count the number of pages under pages flagged for
3029e3c1ac58SAndrey Ryabinin 		 * immediate reclaim and stall if any are encountered
3030e3c1ac58SAndrey Ryabinin 		 * in the nr_immediate check below.
3031d108c772SAndrey Ryabinin 		 */
3032d108c772SAndrey Ryabinin 		if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
3033d108c772SAndrey Ryabinin 			set_bit(PGDAT_WRITEBACK, &pgdat->flags);
3034d108c772SAndrey Ryabinin 
3035d108c772SAndrey Ryabinin 		/* Allow kswapd to start writing pages during reclaim.*/
3036d108c772SAndrey Ryabinin 		if (sc->nr.unqueued_dirty == sc->nr.file_taken)
3037d108c772SAndrey Ryabinin 			set_bit(PGDAT_DIRTY, &pgdat->flags);
3038d108c772SAndrey Ryabinin 
3039d108c772SAndrey Ryabinin 		/*
30401eba09c1SRandy Dunlap 		 * If kswapd scans pages marked for immediate
3041d108c772SAndrey Ryabinin 		 * reclaim and under writeback (nr_immediate), it
3042d108c772SAndrey Ryabinin 		 * implies that pages are cycling through the LRU
3043d108c772SAndrey Ryabinin 		 * faster than they are written so also forcibly stall.
3044d108c772SAndrey Ryabinin 		 */
3045d108c772SAndrey Ryabinin 		if (sc->nr.immediate)
3046d108c772SAndrey Ryabinin 			congestion_wait(BLK_RW_ASYNC, HZ/10);
3047d108c772SAndrey Ryabinin 	}
3048d108c772SAndrey Ryabinin 
3049d108c772SAndrey Ryabinin 	/*
30501b05117dSJohannes Weiner 	 * Tag a node/memcg as congested if all the dirty pages
30511b05117dSJohannes Weiner 	 * scanned were backed by a congested BDI and
30521b05117dSJohannes Weiner 	 * wait_iff_congested will stall.
30531b05117dSJohannes Weiner 	 *
3054e3c1ac58SAndrey Ryabinin 	 * Legacy memcg will stall in page writeback so avoid forcibly
3055e3c1ac58SAndrey Ryabinin 	 * stalling in wait_iff_congested().
3056e3c1ac58SAndrey Ryabinin 	 */
30571b05117dSJohannes Weiner 	if ((current_is_kswapd() ||
30581b05117dSJohannes Weiner 	     (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
3059e3c1ac58SAndrey Ryabinin 	    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
30601b05117dSJohannes Weiner 		set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
3061e3c1ac58SAndrey Ryabinin 
3062e3c1ac58SAndrey Ryabinin 	/*
3063d108c772SAndrey Ryabinin 	 * Stall direct reclaim for IO completions if underlying BDIs
3064d108c772SAndrey Ryabinin 	 * and node is congested. Allow kswapd to continue until it
3065d108c772SAndrey Ryabinin 	 * starts encountering unqueued dirty pages or cycling through
3066d108c772SAndrey Ryabinin 	 * the LRU too quickly.
3067d108c772SAndrey Ryabinin 	 */
30681b05117dSJohannes Weiner 	if (!current_is_kswapd() && current_may_throttle() &&
30691b05117dSJohannes Weiner 	    !sc->hibernation_mode &&
30701b05117dSJohannes Weiner 	    test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
3071e3c1ac58SAndrey Ryabinin 		wait_iff_congested(BLK_RW_ASYNC, HZ/10);
3072d108c772SAndrey Ryabinin 
3073d2af3397SJohannes Weiner 	if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
3074d2af3397SJohannes Weiner 				    sc))
3075d2af3397SJohannes Weiner 		goto again;
30762344d7e4SJohannes Weiner 
3077c73322d0SJohannes Weiner 	/*
3078c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
3079c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
3080c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
3081c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
3082c73322d0SJohannes Weiner 	 */
3083c73322d0SJohannes Weiner 	if (reclaimable)
3084c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
3085f16015fbSJohannes Weiner }
3086f16015fbSJohannes Weiner 
308753853e2dSVlastimil Babka /*
3088fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
3089fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
3090fdd4c614SVlastimil Babka  * should reclaim first.
309153853e2dSVlastimil Babka  */
30924f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
3093fe4b1b24SMel Gorman {
309431483b6aSMel Gorman 	unsigned long watermark;
3095fdd4c614SVlastimil Babka 	enum compact_result suitable;
3096fe4b1b24SMel Gorman 
3097fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
3098fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
3099fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
3100fdd4c614SVlastimil Babka 		return true;
3101fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
3102fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
3103fe4b1b24SMel Gorman 		return false;
3104fe4b1b24SMel Gorman 
3105fdd4c614SVlastimil Babka 	/*
3106fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
3107fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
3108fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
3109fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
3110fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
3111fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
3112fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
3113fdd4c614SVlastimil Babka 	 */
3114fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
3115fdd4c614SVlastimil Babka 
3116fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
3117fe4b1b24SMel Gorman }
3118fe4b1b24SMel Gorman 
31191da177e4SLinus Torvalds /*
31201da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
31211da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
31221da177e4SLinus Torvalds  * request.
31231da177e4SLinus Torvalds  *
31241da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
31251da177e4SLinus Torvalds  * scan then give up on it.
31261da177e4SLinus Torvalds  */
31270a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
31281da177e4SLinus Torvalds {
3129dd1a239fSMel Gorman 	struct zoneref *z;
313054a6eb5cSMel Gorman 	struct zone *zone;
31310608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
31320608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3133619d0d76SWeijie Yang 	gfp_t orig_mask;
313479dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
31351cfb419bSKAMEZAWA Hiroyuki 
3136cc715d99SMel Gorman 	/*
3137cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
3138cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
3139cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
3140cc715d99SMel Gorman 	 */
3141619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
3142b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
3143cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
31444f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
3145b2e18757SMel Gorman 	}
3146cc715d99SMel Gorman 
3147d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
3148b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
3149b2e18757SMel Gorman 		/*
31501cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
31511cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
31521cfb419bSKAMEZAWA Hiroyuki 		 */
3153b5ead35eSJohannes Weiner 		if (!cgroup_reclaim(sc)) {
3154344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
3155344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
31561da177e4SLinus Torvalds 				continue;
315765ec02cbSVladimir Davydov 
3158e0887c19SRik van Riel 			/*
3159e0c23279SMel Gorman 			 * If we already have plenty of memory free for
3160e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
3161e0c23279SMel Gorman 			 * Even though compaction is invoked for any
3162e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
3163e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
3164c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
3165c7cfa37bSCopot Alexandru 			 * page allocations.
3166e0887c19SRik van Riel 			 */
31670b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
31680b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
31694f588331SMel Gorman 			    compaction_ready(zone, sc)) {
31700b06496aSJohannes Weiner 				sc->compaction_ready = true;
3171e0887c19SRik van Riel 				continue;
3172e0887c19SRik van Riel 			}
31730b06496aSJohannes Weiner 
31740608f43dSAndrew Morton 			/*
317579dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
317679dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
317779dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
317879dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
317979dafcdcSMel Gorman 			 */
318079dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
318179dafcdcSMel Gorman 				continue;
318279dafcdcSMel Gorman 
318379dafcdcSMel Gorman 			/*
31840608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
31850608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
31860608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
31870608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
31880608f43dSAndrew Morton 			 */
31890608f43dSAndrew Morton 			nr_soft_scanned = 0;
3190ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
31910608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
31920608f43dSAndrew Morton 						&nr_soft_scanned);
31930608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
31940608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
3195ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
3196ac34a1a3SKAMEZAWA Hiroyuki 		}
3197d149e3b2SYing Han 
319879dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
319979dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
320079dafcdcSMel Gorman 			continue;
320179dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
3202970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
32031da177e4SLinus Torvalds 	}
3204e0c23279SMel Gorman 
320565ec02cbSVladimir Davydov 	/*
3206619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
3207619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
3208619d0d76SWeijie Yang 	 */
3209619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
32101da177e4SLinus Torvalds }
32111da177e4SLinus Torvalds 
3212b910718aSJohannes Weiner static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
32132a2e4885SJohannes Weiner {
3214b910718aSJohannes Weiner 	struct lruvec *target_lruvec;
32152a2e4885SJohannes Weiner 	unsigned long refaults;
32162a2e4885SJohannes Weiner 
3217b910718aSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
3218170b04b7SJoonsoo Kim 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
3219170b04b7SJoonsoo Kim 	target_lruvec->refaults[0] = refaults;
3220170b04b7SJoonsoo Kim 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
3221170b04b7SJoonsoo Kim 	target_lruvec->refaults[1] = refaults;
32222a2e4885SJohannes Weiner }
32232a2e4885SJohannes Weiner 
32241da177e4SLinus Torvalds /*
32251da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
32261da177e4SLinus Torvalds  *
32271da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
32281da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
32291da177e4SLinus Torvalds  *
32301da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
32311da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
32325b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
32335b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
32345b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
32355b0830cbSJens Axboe  * work, and the allocation attempt will fail.
3236a41f24eaSNishanth Aravamudan  *
3237a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
3238a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
32391da177e4SLinus Torvalds  */
3240dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
32413115cd91SVladimir Davydov 					  struct scan_control *sc)
32421da177e4SLinus Torvalds {
3243241994edSJohannes Weiner 	int initial_priority = sc->priority;
32442a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
32452a2e4885SJohannes Weiner 	struct zoneref *z;
32462a2e4885SJohannes Weiner 	struct zone *zone;
3247241994edSJohannes Weiner retry:
3248873b4771SKeika Kobayashi 	delayacct_freepages_start();
3249873b4771SKeika Kobayashi 
3250b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
32517cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
32521da177e4SLinus Torvalds 
32539e3b2f8cSKonstantin Khlebnikov 	do {
325470ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
325570ddf637SAnton Vorontsov 				sc->priority);
325666e1707bSBalbir Singh 		sc->nr_scanned = 0;
32570a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
3258e0c23279SMel Gorman 
3259bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
32600b06496aSJohannes Weiner 			break;
32610b06496aSJohannes Weiner 
32620b06496aSJohannes Weiner 		if (sc->compaction_ready)
32630b06496aSJohannes Weiner 			break;
32641da177e4SLinus Torvalds 
32651da177e4SLinus Torvalds 		/*
32660e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
32670e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
32680e50ce3bSMinchan Kim 		 */
32690e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
32700e50ce3bSMinchan Kim 			sc->may_writepage = 1;
32710b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
3272bb21c7ceSKOSAKI Motohiro 
32732a2e4885SJohannes Weiner 	last_pgdat = NULL;
32742a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
32752a2e4885SJohannes Weiner 					sc->nodemask) {
32762a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
32772a2e4885SJohannes Weiner 			continue;
32782a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
32791b05117dSJohannes Weiner 
32802a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
32811b05117dSJohannes Weiner 
32821b05117dSJohannes Weiner 		if (cgroup_reclaim(sc)) {
32831b05117dSJohannes Weiner 			struct lruvec *lruvec;
32841b05117dSJohannes Weiner 
32851b05117dSJohannes Weiner 			lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
32861b05117dSJohannes Weiner 						   zone->zone_pgdat);
32871b05117dSJohannes Weiner 			clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
32881b05117dSJohannes Weiner 		}
32892a2e4885SJohannes Weiner 	}
32902a2e4885SJohannes Weiner 
3291873b4771SKeika Kobayashi 	delayacct_freepages_end();
3292873b4771SKeika Kobayashi 
3293bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
3294bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
3295bb21c7ceSKOSAKI Motohiro 
32960cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
32970b06496aSJohannes Weiner 	if (sc->compaction_ready)
32987335084dSMel Gorman 		return 1;
32997335084dSMel Gorman 
3300b91ac374SJohannes Weiner 	/*
3301b91ac374SJohannes Weiner 	 * We make inactive:active ratio decisions based on the node's
3302b91ac374SJohannes Weiner 	 * composition of memory, but a restrictive reclaim_idx or a
3303b91ac374SJohannes Weiner 	 * memory.low cgroup setting can exempt large amounts of
3304b91ac374SJohannes Weiner 	 * memory from reclaim. Neither of which are very common, so
3305b91ac374SJohannes Weiner 	 * instead of doing costly eligibility calculations of the
3306b91ac374SJohannes Weiner 	 * entire cgroup subtree up front, we assume the estimates are
3307b91ac374SJohannes Weiner 	 * good, and retry with forcible deactivation if that fails.
3308b91ac374SJohannes Weiner 	 */
3309b91ac374SJohannes Weiner 	if (sc->skipped_deactivate) {
3310b91ac374SJohannes Weiner 		sc->priority = initial_priority;
3311b91ac374SJohannes Weiner 		sc->force_deactivate = 1;
3312b91ac374SJohannes Weiner 		sc->skipped_deactivate = 0;
3313b91ac374SJohannes Weiner 		goto retry;
3314b91ac374SJohannes Weiner 	}
3315b91ac374SJohannes Weiner 
3316241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
3317d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
3318241994edSJohannes Weiner 		sc->priority = initial_priority;
3319b91ac374SJohannes Weiner 		sc->force_deactivate = 0;
3320d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
3321d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
3322241994edSJohannes Weiner 		goto retry;
3323241994edSJohannes Weiner 	}
3324241994edSJohannes Weiner 
3325bb21c7ceSKOSAKI Motohiro 	return 0;
33261da177e4SLinus Torvalds }
33271da177e4SLinus Torvalds 
3328c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
33295515061dSMel Gorman {
33305515061dSMel Gorman 	struct zone *zone;
33315515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
33325515061dSMel Gorman 	unsigned long free_pages = 0;
33335515061dSMel Gorman 	int i;
33345515061dSMel Gorman 	bool wmark_ok;
33355515061dSMel Gorman 
3336c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3337c73322d0SJohannes Weiner 		return true;
3338c73322d0SJohannes Weiner 
33395515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
33405515061dSMel Gorman 		zone = &pgdat->node_zones[i];
3341d450abd8SJohannes Weiner 		if (!managed_zone(zone))
3342d450abd8SJohannes Weiner 			continue;
3343d450abd8SJohannes Weiner 
3344d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
3345675becceSMel Gorman 			continue;
3346675becceSMel Gorman 
33475515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
33485515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
33495515061dSMel Gorman 	}
33505515061dSMel Gorman 
3351675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
3352675becceSMel Gorman 	if (!pfmemalloc_reserve)
3353675becceSMel Gorman 		return true;
3354675becceSMel Gorman 
33555515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
33565515061dSMel Gorman 
33575515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
33585515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
335997a225e6SJoonsoo Kim 		if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
336097a225e6SJoonsoo Kim 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
33615644e1fbSQian Cai 
33625515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
33635515061dSMel Gorman 	}
33645515061dSMel Gorman 
33655515061dSMel Gorman 	return wmark_ok;
33665515061dSMel Gorman }
33675515061dSMel Gorman 
33685515061dSMel Gorman /*
33695515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
33705515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
33715515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
337250694c28SMel Gorman  * when the low watermark is reached.
337350694c28SMel Gorman  *
337450694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
337550694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
33765515061dSMel Gorman  */
337750694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
33785515061dSMel Gorman 					nodemask_t *nodemask)
33795515061dSMel Gorman {
3380675becceSMel Gorman 	struct zoneref *z;
33815515061dSMel Gorman 	struct zone *zone;
3382675becceSMel Gorman 	pg_data_t *pgdat = NULL;
33835515061dSMel Gorman 
33845515061dSMel Gorman 	/*
33855515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
33865515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
33875515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
33885515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
33895515061dSMel Gorman 	 * processes to block on log_wait_commit().
33905515061dSMel Gorman 	 */
33915515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
339250694c28SMel Gorman 		goto out;
339350694c28SMel Gorman 
339450694c28SMel Gorman 	/*
339550694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
339650694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
339750694c28SMel Gorman 	 */
339850694c28SMel Gorman 	if (fatal_signal_pending(current))
339950694c28SMel Gorman 		goto out;
34005515061dSMel Gorman 
3401675becceSMel Gorman 	/*
3402675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
3403675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3404675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
3405675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
3406675becceSMel Gorman 	 *
3407675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
3408675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
3409675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
3410675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
3411675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
3412675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
3413675becceSMel Gorman 	 * should make reasonable progress.
3414675becceSMel Gorman 	 */
3415675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
341617636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
3417675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
3418675becceSMel Gorman 			continue;
3419675becceSMel Gorman 
3420675becceSMel Gorman 		/* Throttle based on the first usable node */
34215515061dSMel Gorman 		pgdat = zone->zone_pgdat;
3422c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
342350694c28SMel Gorman 			goto out;
3424675becceSMel Gorman 		break;
3425675becceSMel Gorman 	}
3426675becceSMel Gorman 
3427675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
3428675becceSMel Gorman 	if (!pgdat)
3429675becceSMel Gorman 		goto out;
34305515061dSMel Gorman 
343168243e76SMel Gorman 	/* Account for the throttling */
343268243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
343368243e76SMel Gorman 
34345515061dSMel Gorman 	/*
34355515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
34365515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
34375515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
34385515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
34395515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
34405515061dSMel Gorman 	 * second before continuing.
34415515061dSMel Gorman 	 */
34425515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
34435515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3444c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
344550694c28SMel Gorman 
344650694c28SMel Gorman 		goto check_pending;
34475515061dSMel Gorman 	}
34485515061dSMel Gorman 
34495515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
34505515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3451c73322d0SJohannes Weiner 		allow_direct_reclaim(pgdat));
345250694c28SMel Gorman 
345350694c28SMel Gorman check_pending:
345450694c28SMel Gorman 	if (fatal_signal_pending(current))
345550694c28SMel Gorman 		return true;
345650694c28SMel Gorman 
345750694c28SMel Gorman out:
345850694c28SMel Gorman 	return false;
34595515061dSMel Gorman }
34605515061dSMel Gorman 
3461dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3462327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
346366e1707bSBalbir Singh {
346433906bc5SMel Gorman 	unsigned long nr_reclaimed;
346566e1707bSBalbir Singh 	struct scan_control sc = {
346622fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3467f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3468b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
3469ee814fe2SJohannes Weiner 		.order = order,
3470ee814fe2SJohannes Weiner 		.nodemask = nodemask,
3471ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
3472ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3473a6dc60f8SJohannes Weiner 		.may_unmap = 1,
34742e2e4259SKOSAKI Motohiro 		.may_swap = 1,
347566e1707bSBalbir Singh 	};
347666e1707bSBalbir Singh 
34775515061dSMel Gorman 	/*
3478bb451fdfSGreg Thelen 	 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3479bb451fdfSGreg Thelen 	 * Confirm they are large enough for max values.
3480bb451fdfSGreg Thelen 	 */
3481bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3482bb451fdfSGreg Thelen 	BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3483bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3484bb451fdfSGreg Thelen 
3485bb451fdfSGreg Thelen 	/*
348650694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
348750694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
348850694c28SMel Gorman 	 * point.
34895515061dSMel Gorman 	 */
3490f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
34915515061dSMel Gorman 		return 1;
34925515061dSMel Gorman 
34931732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
34943481c37fSYafang Shao 	trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
349533906bc5SMel Gorman 
34963115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
349733906bc5SMel Gorman 
349833906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
34991732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
350033906bc5SMel Gorman 
350133906bc5SMel Gorman 	return nr_reclaimed;
350266e1707bSBalbir Singh }
350366e1707bSBalbir Singh 
3504c255a458SAndrew Morton #ifdef CONFIG_MEMCG
350566e1707bSBalbir Singh 
3506d2e5fb92SMichal Hocko /* Only used by soft limit reclaim. Do not reuse for anything else. */
3507a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
35084e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
3509ef8f2327SMel Gorman 						pg_data_t *pgdat,
35100ae5e89cSYing Han 						unsigned long *nr_scanned)
35114e416953SBalbir Singh {
3512afaf07a6SJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
35134e416953SBalbir Singh 	struct scan_control sc = {
3514b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3515ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
35164e416953SBalbir Singh 		.may_writepage = !laptop_mode,
35174e416953SBalbir Singh 		.may_unmap = 1,
3518b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
35194e416953SBalbir Singh 		.may_swap = !noswap,
35204e416953SBalbir Singh 	};
35210ae5e89cSYing Han 
3522d2e5fb92SMichal Hocko 	WARN_ON_ONCE(!current->reclaim_state);
3523d2e5fb92SMichal Hocko 
35244e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
35254e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3526bdce6d9eSKOSAKI Motohiro 
35279e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
35283481c37fSYafang Shao 						      sc.gfp_mask);
3529bdce6d9eSKOSAKI Motohiro 
35304e416953SBalbir Singh 	/*
35314e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
35324e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3533a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
35344e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
35354e416953SBalbir Singh 	 * the priority and make it zero.
35364e416953SBalbir Singh 	 */
3537afaf07a6SJohannes Weiner 	shrink_lruvec(lruvec, &sc);
3538bdce6d9eSKOSAKI Motohiro 
3539bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3540bdce6d9eSKOSAKI Motohiro 
35410ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
35420308f7cfSYafang Shao 
35434e416953SBalbir Singh 	return sc.nr_reclaimed;
35444e416953SBalbir Singh }
35454e416953SBalbir Singh 
354672835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3547b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
35488c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3549b70a2a21SJohannes Weiner 					   bool may_swap)
355066e1707bSBalbir Singh {
3551bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3552499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
355366e1707bSBalbir Singh 	struct scan_control sc = {
3554b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
35557dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3556ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3557b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3558ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3559ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
356066e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3561a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3562b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3563a09ed5e0SYing Han 	};
3564fa40d1eeSShakeel Butt 	/*
3565fa40d1eeSShakeel Butt 	 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
3566fa40d1eeSShakeel Butt 	 * equal pressure on all the nodes. This is based on the assumption that
3567fa40d1eeSShakeel Butt 	 * the reclaim does not bail out early.
3568fa40d1eeSShakeel Butt 	 */
3569fa40d1eeSShakeel Butt 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
357066e1707bSBalbir Singh 
35711732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
35723481c37fSYafang Shao 	trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
3573499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3574eb414681SJohannes Weiner 
35753115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3576eb414681SJohannes Weiner 
3577499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3578bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
35791732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3580bdce6d9eSKOSAKI Motohiro 
3581bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
358266e1707bSBalbir Singh }
358366e1707bSBalbir Singh #endif
358466e1707bSBalbir Singh 
35851d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3586ef8f2327SMel Gorman 				struct scan_control *sc)
3587f16015fbSJohannes Weiner {
3588b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3589b91ac374SJohannes Weiner 	struct lruvec *lruvec;
3590b95a2f2dSJohannes Weiner 
3591b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3592b95a2f2dSJohannes Weiner 		return;
3593b95a2f2dSJohannes Weiner 
3594b91ac374SJohannes Weiner 	lruvec = mem_cgroup_lruvec(NULL, pgdat);
3595b91ac374SJohannes Weiner 	if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
3596b91ac374SJohannes Weiner 		return;
3597b91ac374SJohannes Weiner 
3598b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3599b95a2f2dSJohannes Weiner 	do {
3600b91ac374SJohannes Weiner 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
36011a93be0eSKonstantin Khlebnikov 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
36029e3b2f8cSKonstantin Khlebnikov 				   sc, LRU_ACTIVE_ANON);
3603b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3604b95a2f2dSJohannes Weiner 	} while (memcg);
3605f16015fbSJohannes Weiner }
3606f16015fbSJohannes Weiner 
360797a225e6SJoonsoo Kim static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
36081c30844dSMel Gorman {
36091c30844dSMel Gorman 	int i;
36101c30844dSMel Gorman 	struct zone *zone;
36111c30844dSMel Gorman 
36121c30844dSMel Gorman 	/*
36131c30844dSMel Gorman 	 * Check for watermark boosts top-down as the higher zones
36141c30844dSMel Gorman 	 * are more likely to be boosted. Both watermarks and boosts
36151eba09c1SRandy Dunlap 	 * should not be checked at the same time as reclaim would
36161c30844dSMel Gorman 	 * start prematurely when there is no boosting and a lower
36171c30844dSMel Gorman 	 * zone is balanced.
36181c30844dSMel Gorman 	 */
361997a225e6SJoonsoo Kim 	for (i = highest_zoneidx; i >= 0; i--) {
36201c30844dSMel Gorman 		zone = pgdat->node_zones + i;
36211c30844dSMel Gorman 		if (!managed_zone(zone))
36221c30844dSMel Gorman 			continue;
36231c30844dSMel Gorman 
36241c30844dSMel Gorman 		if (zone->watermark_boost)
36251c30844dSMel Gorman 			return true;
36261c30844dSMel Gorman 	}
36271c30844dSMel Gorman 
36281c30844dSMel Gorman 	return false;
36291c30844dSMel Gorman }
36301c30844dSMel Gorman 
3631e716f2ebSMel Gorman /*
3632e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
363397a225e6SJoonsoo Kim  * and highest_zoneidx
3634e716f2ebSMel Gorman  */
363597a225e6SJoonsoo Kim static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
363660cefed4SJohannes Weiner {
3637e716f2ebSMel Gorman 	int i;
3638e716f2ebSMel Gorman 	unsigned long mark = -1;
3639e716f2ebSMel Gorman 	struct zone *zone;
364060cefed4SJohannes Weiner 
36411c30844dSMel Gorman 	/*
36421c30844dSMel Gorman 	 * Check watermarks bottom-up as lower zones are more likely to
36431c30844dSMel Gorman 	 * meet watermarks.
36441c30844dSMel Gorman 	 */
364597a225e6SJoonsoo Kim 	for (i = 0; i <= highest_zoneidx; i++) {
3646e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
36476256c6b4SMel Gorman 
3648e716f2ebSMel Gorman 		if (!managed_zone(zone))
3649e716f2ebSMel Gorman 			continue;
3650e716f2ebSMel Gorman 
3651e716f2ebSMel Gorman 		mark = high_wmark_pages(zone);
365297a225e6SJoonsoo Kim 		if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
36536256c6b4SMel Gorman 			return true;
365460cefed4SJohannes Weiner 	}
365560cefed4SJohannes Weiner 
3656e716f2ebSMel Gorman 	/*
365797a225e6SJoonsoo Kim 	 * If a node has no populated zone within highest_zoneidx, it does not
3658e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3659e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3660e716f2ebSMel Gorman 	 */
3661e716f2ebSMel Gorman 	if (mark == -1)
3662e716f2ebSMel Gorman 		return true;
3663e716f2ebSMel Gorman 
3664e716f2ebSMel Gorman 	return false;
3665e716f2ebSMel Gorman }
3666e716f2ebSMel Gorman 
3667631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
3668631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
3669631b6e08SMel Gorman {
36701b05117dSJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
36711b05117dSJohannes Weiner 
36721b05117dSJohannes Weiner 	clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3673631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
3674631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3675631b6e08SMel Gorman }
3676631b6e08SMel Gorman 
36771741c877SMel Gorman /*
36785515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
36795515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
36805515061dSMel Gorman  *
36815515061dSMel Gorman  * Returns true if kswapd is ready to sleep
36825515061dSMel Gorman  */
368397a225e6SJoonsoo Kim static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
368497a225e6SJoonsoo Kim 				int highest_zoneidx)
3685f50de2d3SMel Gorman {
36865515061dSMel Gorman 	/*
36879e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3688c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
36899e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
36909e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
36919e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
36929e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
36939e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
36949e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
36959e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
36969e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
36979e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
36985515061dSMel Gorman 	 */
36999e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
37009e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3701f50de2d3SMel Gorman 
3702c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3703c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3704c73322d0SJohannes Weiner 		return true;
3705c73322d0SJohannes Weiner 
370697a225e6SJoonsoo Kim 	if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
3707631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
3708333b0a45SShantanu Goel 		return true;
37091d82de61SMel Gorman 	}
37101d82de61SMel Gorman 
3711333b0a45SShantanu Goel 	return false;
3712f50de2d3SMel Gorman }
3713f50de2d3SMel Gorman 
37141da177e4SLinus Torvalds /*
37151d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
37161d82de61SMel Gorman  * zone that is currently unbalanced.
3717b8e83b94SMel Gorman  *
3718b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3719283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3720283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
372175485363SMel Gorman  */
37221d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3723accf6242SVlastimil Babka 			       struct scan_control *sc)
372475485363SMel Gorman {
37251d82de61SMel Gorman 	struct zone *zone;
37261d82de61SMel Gorman 	int z;
372775485363SMel Gorman 
37281d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
37291d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3730970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
37311d82de61SMel Gorman 		zone = pgdat->node_zones + z;
37326aa303deSMel Gorman 		if (!managed_zone(zone))
37331d82de61SMel Gorman 			continue;
37347c954f6dSMel Gorman 
37351d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
37367c954f6dSMel Gorman 	}
37377c954f6dSMel Gorman 
37381d82de61SMel Gorman 	/*
37391d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
37401d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
37411d82de61SMel Gorman 	 */
3742970a39a3SMel Gorman 	shrink_node(pgdat, sc);
37431d82de61SMel Gorman 
37441d82de61SMel Gorman 	/*
37451d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
37461d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
37471d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
37481d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
37491d82de61SMel Gorman 	 * can direct reclaim/compact.
37501d82de61SMel Gorman 	 */
37519861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
37521d82de61SMel Gorman 		sc->order = 0;
37531d82de61SMel Gorman 
3754b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
375575485363SMel Gorman }
375675485363SMel Gorman 
3757c49c2c47SMel Gorman /* Page allocator PCP high watermark is lowered if reclaim is active. */
3758c49c2c47SMel Gorman static inline void
3759c49c2c47SMel Gorman update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
3760c49c2c47SMel Gorman {
3761c49c2c47SMel Gorman 	int i;
3762c49c2c47SMel Gorman 	struct zone *zone;
3763c49c2c47SMel Gorman 
3764c49c2c47SMel Gorman 	for (i = 0; i <= highest_zoneidx; i++) {
3765c49c2c47SMel Gorman 		zone = pgdat->node_zones + i;
3766c49c2c47SMel Gorman 
3767c49c2c47SMel Gorman 		if (!managed_zone(zone))
3768c49c2c47SMel Gorman 			continue;
3769c49c2c47SMel Gorman 
3770c49c2c47SMel Gorman 		if (active)
3771c49c2c47SMel Gorman 			set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
3772c49c2c47SMel Gorman 		else
3773c49c2c47SMel Gorman 			clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
3774c49c2c47SMel Gorman 	}
3775c49c2c47SMel Gorman }
3776c49c2c47SMel Gorman 
3777c49c2c47SMel Gorman static inline void
3778c49c2c47SMel Gorman set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
3779c49c2c47SMel Gorman {
3780c49c2c47SMel Gorman 	update_reclaim_active(pgdat, highest_zoneidx, true);
3781c49c2c47SMel Gorman }
3782c49c2c47SMel Gorman 
3783c49c2c47SMel Gorman static inline void
3784c49c2c47SMel Gorman clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
3785c49c2c47SMel Gorman {
3786c49c2c47SMel Gorman 	update_reclaim_active(pgdat, highest_zoneidx, false);
3787c49c2c47SMel Gorman }
3788c49c2c47SMel Gorman 
378975485363SMel Gorman /*
37901d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
37911d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
37921d82de61SMel Gorman  * balanced.
37931da177e4SLinus Torvalds  *
37941d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
37951da177e4SLinus Torvalds  *
37961da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
379741858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
37988bb4e7a2SWei Yang  * found to have free_pages <= high_wmark_pages(zone), any page in that zone
37991d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
38001d82de61SMel Gorman  * balanced.
38011da177e4SLinus Torvalds  */
380297a225e6SJoonsoo Kim static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
38031da177e4SLinus Torvalds {
38041da177e4SLinus Torvalds 	int i;
38050608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
38060608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3807eb414681SJohannes Weiner 	unsigned long pflags;
38081c30844dSMel Gorman 	unsigned long nr_boost_reclaim;
38091c30844dSMel Gorman 	unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
38101c30844dSMel Gorman 	bool boosted;
38111d82de61SMel Gorman 	struct zone *zone;
3812179e9639SAndrew Morton 	struct scan_control sc = {
3813179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3814ee814fe2SJohannes Weiner 		.order = order,
3815a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3816179e9639SAndrew Morton 	};
381793781325SOmar Sandoval 
38181732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
3819eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
38204f3eaf45SMatthew Wilcox (Oracle) 	__fs_reclaim_acquire(_THIS_IP_);
382193781325SOmar Sandoval 
3822f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
38231da177e4SLinus Torvalds 
38241c30844dSMel Gorman 	/*
38251c30844dSMel Gorman 	 * Account for the reclaim boost. Note that the zone boost is left in
38261c30844dSMel Gorman 	 * place so that parallel allocations that are near the watermark will
38271c30844dSMel Gorman 	 * stall or direct reclaim until kswapd is finished.
38281c30844dSMel Gorman 	 */
38291c30844dSMel Gorman 	nr_boost_reclaim = 0;
383097a225e6SJoonsoo Kim 	for (i = 0; i <= highest_zoneidx; i++) {
38311c30844dSMel Gorman 		zone = pgdat->node_zones + i;
38321c30844dSMel Gorman 		if (!managed_zone(zone))
38331c30844dSMel Gorman 			continue;
38341c30844dSMel Gorman 
38351c30844dSMel Gorman 		nr_boost_reclaim += zone->watermark_boost;
38361c30844dSMel Gorman 		zone_boosts[i] = zone->watermark_boost;
38371c30844dSMel Gorman 	}
38381c30844dSMel Gorman 	boosted = nr_boost_reclaim;
38391c30844dSMel Gorman 
38401c30844dSMel Gorman restart:
3841c49c2c47SMel Gorman 	set_reclaim_active(pgdat, highest_zoneidx);
38421c30844dSMel Gorman 	sc.priority = DEF_PRIORITY;
38439e3b2f8cSKonstantin Khlebnikov 	do {
3844c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
3845b8e83b94SMel Gorman 		bool raise_priority = true;
38461c30844dSMel Gorman 		bool balanced;
384793781325SOmar Sandoval 		bool ret;
3848b8e83b94SMel Gorman 
384997a225e6SJoonsoo Kim 		sc.reclaim_idx = highest_zoneidx;
38501da177e4SLinus Torvalds 
385186c79f6bSMel Gorman 		/*
385284c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
385384c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
385484c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
385584c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
385684c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
385784c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
385884c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
385984c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
386086c79f6bSMel Gorman 		 */
386186c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
386286c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
386386c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
38646aa303deSMel Gorman 				if (!managed_zone(zone))
386586c79f6bSMel Gorman 					continue;
386686c79f6bSMel Gorman 
3867970a39a3SMel Gorman 				sc.reclaim_idx = i;
386886c79f6bSMel Gorman 				break;
386986c79f6bSMel Gorman 			}
387086c79f6bSMel Gorman 		}
387186c79f6bSMel Gorman 
387286c79f6bSMel Gorman 		/*
38731c30844dSMel Gorman 		 * If the pgdat is imbalanced then ignore boosting and preserve
38741c30844dSMel Gorman 		 * the watermarks for a later time and restart. Note that the
38751c30844dSMel Gorman 		 * zone watermarks will be still reset at the end of balancing
38761c30844dSMel Gorman 		 * on the grounds that the normal reclaim should be enough to
38771c30844dSMel Gorman 		 * re-evaluate if boosting is required when kswapd next wakes.
387886c79f6bSMel Gorman 		 */
387997a225e6SJoonsoo Kim 		balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
38801c30844dSMel Gorman 		if (!balanced && nr_boost_reclaim) {
38811c30844dSMel Gorman 			nr_boost_reclaim = 0;
38821c30844dSMel Gorman 			goto restart;
38831c30844dSMel Gorman 		}
38841c30844dSMel Gorman 
38851c30844dSMel Gorman 		/*
38861c30844dSMel Gorman 		 * If boosting is not active then only reclaim if there are no
38871c30844dSMel Gorman 		 * eligible zones. Note that sc.reclaim_idx is not used as
38881c30844dSMel Gorman 		 * buffer_heads_over_limit may have adjusted it.
38891c30844dSMel Gorman 		 */
38901c30844dSMel Gorman 		if (!nr_boost_reclaim && balanced)
38911da177e4SLinus Torvalds 			goto out;
3892e1dbeda6SAndrew Morton 
38931c30844dSMel Gorman 		/* Limit the priority of boosting to avoid reclaim writeback */
38941c30844dSMel Gorman 		if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
38951c30844dSMel Gorman 			raise_priority = false;
38961c30844dSMel Gorman 
38971c30844dSMel Gorman 		/*
38981c30844dSMel Gorman 		 * Do not writeback or swap pages for boosted reclaim. The
38991c30844dSMel Gorman 		 * intent is to relieve pressure not issue sub-optimal IO
39001c30844dSMel Gorman 		 * from reclaim context. If no pages are reclaimed, the
39011c30844dSMel Gorman 		 * reclaim will be aborted.
39021c30844dSMel Gorman 		 */
39031c30844dSMel Gorman 		sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
39041c30844dSMel Gorman 		sc.may_swap = !nr_boost_reclaim;
39051c30844dSMel Gorman 
39061da177e4SLinus Torvalds 		/*
39071d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
39081d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
39091d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
39101d82de61SMel Gorman 		 * about consistent aging.
39111d82de61SMel Gorman 		 */
3912ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
39131d82de61SMel Gorman 
39141d82de61SMel Gorman 		/*
3915b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3916b7ea3c41SMel Gorman 		 * even in laptop mode.
3917b7ea3c41SMel Gorman 		 */
3918047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
3919b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3920b7ea3c41SMel Gorman 
39211d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
39221da177e4SLinus Torvalds 		sc.nr_scanned = 0;
39230608f43dSAndrew Morton 		nr_soft_scanned = 0;
3924ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
39251d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
39260608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
39270608f43dSAndrew Morton 
392832a4330dSRik van Riel 		/*
39291d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
39301d82de61SMel Gorman 		 * enough pages are already being scanned that that high
39311d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
393232a4330dSRik van Riel 		 */
3933970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3934b8e83b94SMel Gorman 			raise_priority = false;
3935d7868daeSMel Gorman 
39365515061dSMel Gorman 		/*
39375515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
39385515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
39395515061dSMel Gorman 		 * able to safely make forward progress. Wake them
39405515061dSMel Gorman 		 */
39415515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3942c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
3943cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
39445515061dSMel Gorman 
3945b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
39464f3eaf45SMatthew Wilcox (Oracle) 		__fs_reclaim_release(_THIS_IP_);
394793781325SOmar Sandoval 		ret = try_to_freeze();
39484f3eaf45SMatthew Wilcox (Oracle) 		__fs_reclaim_acquire(_THIS_IP_);
394993781325SOmar Sandoval 		if (ret || kthread_should_stop())
3950b8e83b94SMel Gorman 			break;
3951b8e83b94SMel Gorman 
3952b8e83b94SMel Gorman 		/*
3953b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3954b8e83b94SMel Gorman 		 * progress in reclaiming pages
3955b8e83b94SMel Gorman 		 */
3956c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
39571c30844dSMel Gorman 		nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
39581c30844dSMel Gorman 
39591c30844dSMel Gorman 		/*
39601c30844dSMel Gorman 		 * If reclaim made no progress for a boost, stop reclaim as
39611c30844dSMel Gorman 		 * IO cannot be queued and it could be an infinite loop in
39621c30844dSMel Gorman 		 * extreme circumstances.
39631c30844dSMel Gorman 		 */
39641c30844dSMel Gorman 		if (nr_boost_reclaim && !nr_reclaimed)
39651c30844dSMel Gorman 			break;
39661c30844dSMel Gorman 
3967c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
3968b8e83b94SMel Gorman 			sc.priority--;
39691d82de61SMel Gorman 	} while (sc.priority >= 1);
39701da177e4SLinus Torvalds 
3971c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
3972c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
3973c73322d0SJohannes Weiner 
3974b8e83b94SMel Gorman out:
3975c49c2c47SMel Gorman 	clear_reclaim_active(pgdat, highest_zoneidx);
3976c49c2c47SMel Gorman 
39771c30844dSMel Gorman 	/* If reclaim was boosted, account for the reclaim done in this pass */
39781c30844dSMel Gorman 	if (boosted) {
39791c30844dSMel Gorman 		unsigned long flags;
39801c30844dSMel Gorman 
398197a225e6SJoonsoo Kim 		for (i = 0; i <= highest_zoneidx; i++) {
39821c30844dSMel Gorman 			if (!zone_boosts[i])
39831c30844dSMel Gorman 				continue;
39841c30844dSMel Gorman 
39851c30844dSMel Gorman 			/* Increments are under the zone lock */
39861c30844dSMel Gorman 			zone = pgdat->node_zones + i;
39871c30844dSMel Gorman 			spin_lock_irqsave(&zone->lock, flags);
39881c30844dSMel Gorman 			zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
39891c30844dSMel Gorman 			spin_unlock_irqrestore(&zone->lock, flags);
39901c30844dSMel Gorman 		}
39911c30844dSMel Gorman 
39921c30844dSMel Gorman 		/*
39931c30844dSMel Gorman 		 * As there is now likely space, wakeup kcompact to defragment
39941c30844dSMel Gorman 		 * pageblocks.
39951c30844dSMel Gorman 		 */
399697a225e6SJoonsoo Kim 		wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
39971c30844dSMel Gorman 	}
39981c30844dSMel Gorman 
39992a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
40004f3eaf45SMatthew Wilcox (Oracle) 	__fs_reclaim_release(_THIS_IP_);
4001eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
40021732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
4003e5ca8071SYafang Shao 
40040abdee2bSMel Gorman 	/*
40051d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
40061d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
40071d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
40081d82de61SMel Gorman 	 * remain at the higher level.
40090abdee2bSMel Gorman 	 */
40101d82de61SMel Gorman 	return sc.order;
40111da177e4SLinus Torvalds }
40121da177e4SLinus Torvalds 
4013e716f2ebSMel Gorman /*
401497a225e6SJoonsoo Kim  * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
401597a225e6SJoonsoo Kim  * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
401697a225e6SJoonsoo Kim  * not a valid index then either kswapd runs for first time or kswapd couldn't
401797a225e6SJoonsoo Kim  * sleep after previous reclaim attempt (node is still unbalanced). In that
401897a225e6SJoonsoo Kim  * case return the zone index of the previous kswapd reclaim cycle.
4019e716f2ebSMel Gorman  */
402097a225e6SJoonsoo Kim static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
402197a225e6SJoonsoo Kim 					   enum zone_type prev_highest_zoneidx)
4022e716f2ebSMel Gorman {
402397a225e6SJoonsoo Kim 	enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
40245644e1fbSQian Cai 
402597a225e6SJoonsoo Kim 	return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
4026e716f2ebSMel Gorman }
4027e716f2ebSMel Gorman 
402838087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
402997a225e6SJoonsoo Kim 				unsigned int highest_zoneidx)
4030f0bc0a60SKOSAKI Motohiro {
4031f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
4032f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
4033f0bc0a60SKOSAKI Motohiro 
4034f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
4035f0bc0a60SKOSAKI Motohiro 		return;
4036f0bc0a60SKOSAKI Motohiro 
4037f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
4038f0bc0a60SKOSAKI Motohiro 
4039333b0a45SShantanu Goel 	/*
4040333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
4041333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
4042333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
4043333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
4044333b0a45SShantanu Goel 	 * succeed.
4045333b0a45SShantanu Goel 	 */
404697a225e6SJoonsoo Kim 	if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
4047fd901c95SVlastimil Babka 		/*
4048fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
4049fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
4050fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
4051fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
4052fd901c95SVlastimil Babka 		 */
4053fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
4054fd901c95SVlastimil Babka 
4055fd901c95SVlastimil Babka 		/*
4056fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
4057fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
4058fd901c95SVlastimil Babka 		 */
405997a225e6SJoonsoo Kim 		wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
4060fd901c95SVlastimil Babka 
4061f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
406238087d9bSMel Gorman 
406338087d9bSMel Gorman 		/*
406497a225e6SJoonsoo Kim 		 * If woken prematurely then reset kswapd_highest_zoneidx and
406538087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
406638087d9bSMel Gorman 		 * the previous request that slept prematurely.
406738087d9bSMel Gorman 		 */
406838087d9bSMel Gorman 		if (remaining) {
406997a225e6SJoonsoo Kim 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
407097a225e6SJoonsoo Kim 					kswapd_highest_zoneidx(pgdat,
407197a225e6SJoonsoo Kim 							highest_zoneidx));
40725644e1fbSQian Cai 
40735644e1fbSQian Cai 			if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
40745644e1fbSQian Cai 				WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
407538087d9bSMel Gorman 		}
407638087d9bSMel Gorman 
4077f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
4078f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
4079f0bc0a60SKOSAKI Motohiro 	}
4080f0bc0a60SKOSAKI Motohiro 
4081f0bc0a60SKOSAKI Motohiro 	/*
4082f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
4083f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
4084f0bc0a60SKOSAKI Motohiro 	 */
4085d9f21d42SMel Gorman 	if (!remaining &&
408697a225e6SJoonsoo Kim 	    prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
4087f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
4088f0bc0a60SKOSAKI Motohiro 
4089f0bc0a60SKOSAKI Motohiro 		/*
4090f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
4091f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
4092f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
4093f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
4094f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
4095f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
4096f0bc0a60SKOSAKI Motohiro 		 */
4097f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
40981c7e7f6cSAaditya Kumar 
40991c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
4100f0bc0a60SKOSAKI Motohiro 			schedule();
41011c7e7f6cSAaditya Kumar 
4102f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
4103f0bc0a60SKOSAKI Motohiro 	} else {
4104f0bc0a60SKOSAKI Motohiro 		if (remaining)
4105f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
4106f0bc0a60SKOSAKI Motohiro 		else
4107f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
4108f0bc0a60SKOSAKI Motohiro 	}
4109f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
4110f0bc0a60SKOSAKI Motohiro }
4111f0bc0a60SKOSAKI Motohiro 
41121da177e4SLinus Torvalds /*
41131da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
41141da177e4SLinus Torvalds  * from the init process.
41151da177e4SLinus Torvalds  *
41161da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
41171da177e4SLinus Torvalds  * free memory available even if there is no other activity
41181da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
41191da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
41201da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
41211da177e4SLinus Torvalds  *
41221da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
41231da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
41241da177e4SLinus Torvalds  */
41251da177e4SLinus Torvalds static int kswapd(void *p)
41261da177e4SLinus Torvalds {
4127e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
412897a225e6SJoonsoo Kim 	unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
41291da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t *)p;
41301da177e4SLinus Torvalds 	struct task_struct *tsk = current;
4131a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
41321da177e4SLinus Torvalds 
4133174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
4134c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
41351da177e4SLinus Torvalds 
41361da177e4SLinus Torvalds 	/*
41371da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
41381da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
41391da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
41401da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
41411da177e4SLinus Torvalds 	 *
41421da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
41431da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
41441da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
41451da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
41461da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
41471da177e4SLinus Torvalds 	 */
4148930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
414983144186SRafael J. Wysocki 	set_freezable();
41501da177e4SLinus Torvalds 
41515644e1fbSQian Cai 	WRITE_ONCE(pgdat->kswapd_order, 0);
415297a225e6SJoonsoo Kim 	WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
41531da177e4SLinus Torvalds 	for ( ; ; ) {
41546f6313d4SJeff Liu 		bool ret;
41553e1d1d28SChristoph Lameter 
41565644e1fbSQian Cai 		alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
415797a225e6SJoonsoo Kim 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
415897a225e6SJoonsoo Kim 							highest_zoneidx);
4159e716f2ebSMel Gorman 
416038087d9bSMel Gorman kswapd_try_sleep:
416138087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
416297a225e6SJoonsoo Kim 					highest_zoneidx);
4163215ddd66SMel Gorman 
416497a225e6SJoonsoo Kim 		/* Read the new order and highest_zoneidx */
41652b47a24cSLukas Bulwahn 		alloc_order = READ_ONCE(pgdat->kswapd_order);
416697a225e6SJoonsoo Kim 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
416797a225e6SJoonsoo Kim 							highest_zoneidx);
41685644e1fbSQian Cai 		WRITE_ONCE(pgdat->kswapd_order, 0);
416997a225e6SJoonsoo Kim 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
41701da177e4SLinus Torvalds 
41718fe23e05SDavid Rientjes 		ret = try_to_freeze();
41728fe23e05SDavid Rientjes 		if (kthread_should_stop())
41738fe23e05SDavid Rientjes 			break;
41748fe23e05SDavid Rientjes 
41758fe23e05SDavid Rientjes 		/*
41768fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
41778fe23e05SDavid Rientjes 		 * after returning from the refrigerator
4178b1296cc4SRafael J. Wysocki 		 */
417938087d9bSMel Gorman 		if (ret)
418038087d9bSMel Gorman 			continue;
41811d82de61SMel Gorman 
418238087d9bSMel Gorman 		/*
418338087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
418438087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
418538087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
418638087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
418738087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
418838087d9bSMel Gorman 		 * request (alloc_order).
418938087d9bSMel Gorman 		 */
419097a225e6SJoonsoo Kim 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
4191e5146b12SMel Gorman 						alloc_order);
419297a225e6SJoonsoo Kim 		reclaim_order = balance_pgdat(pgdat, alloc_order,
419397a225e6SJoonsoo Kim 						highest_zoneidx);
419438087d9bSMel Gorman 		if (reclaim_order < alloc_order)
419538087d9bSMel Gorman 			goto kswapd_try_sleep;
419633906bc5SMel Gorman 	}
4197b0a8cc58STakamori Yamaguchi 
419871abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
419971abdc15SJohannes Weiner 
42001da177e4SLinus Torvalds 	return 0;
42011da177e4SLinus Torvalds }
42021da177e4SLinus Torvalds 
42031da177e4SLinus Torvalds /*
42045ecd9d40SDavid Rientjes  * A zone is low on free memory or too fragmented for high-order memory.  If
42055ecd9d40SDavid Rientjes  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
42065ecd9d40SDavid Rientjes  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
42075ecd9d40SDavid Rientjes  * has failed or is not needed, still wake up kcompactd if only compaction is
42085ecd9d40SDavid Rientjes  * needed.
42091da177e4SLinus Torvalds  */
42105ecd9d40SDavid Rientjes void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
421197a225e6SJoonsoo Kim 		   enum zone_type highest_zoneidx)
42121da177e4SLinus Torvalds {
42131da177e4SLinus Torvalds 	pg_data_t *pgdat;
42145644e1fbSQian Cai 	enum zone_type curr_idx;
42151da177e4SLinus Torvalds 
42166aa303deSMel Gorman 	if (!managed_zone(zone))
42171da177e4SLinus Torvalds 		return;
42181da177e4SLinus Torvalds 
42195ecd9d40SDavid Rientjes 	if (!cpuset_zone_allowed(zone, gfp_flags))
42201da177e4SLinus Torvalds 		return;
4221dffcac2cSShakeel Butt 
42225644e1fbSQian Cai 	pgdat = zone->zone_pgdat;
422397a225e6SJoonsoo Kim 	curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
42245644e1fbSQian Cai 
422597a225e6SJoonsoo Kim 	if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
422697a225e6SJoonsoo Kim 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
42275644e1fbSQian Cai 
42285644e1fbSQian Cai 	if (READ_ONCE(pgdat->kswapd_order) < order)
42295644e1fbSQian Cai 		WRITE_ONCE(pgdat->kswapd_order, order);
42305644e1fbSQian Cai 
42318d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
42321da177e4SLinus Torvalds 		return;
4233e1a55637SMel Gorman 
42345ecd9d40SDavid Rientjes 	/* Hopeless node, leave it to direct reclaim if possible */
42355ecd9d40SDavid Rientjes 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
423697a225e6SJoonsoo Kim 	    (pgdat_balanced(pgdat, order, highest_zoneidx) &&
423797a225e6SJoonsoo Kim 	     !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
42385ecd9d40SDavid Rientjes 		/*
42395ecd9d40SDavid Rientjes 		 * There may be plenty of free memory available, but it's too
42405ecd9d40SDavid Rientjes 		 * fragmented for high-order allocations.  Wake up kcompactd
42415ecd9d40SDavid Rientjes 		 * and rely on compaction_suitable() to determine if it's
42425ecd9d40SDavid Rientjes 		 * needed.  If it fails, it will defer subsequent attempts to
42435ecd9d40SDavid Rientjes 		 * ratelimit its work.
42445ecd9d40SDavid Rientjes 		 */
42455ecd9d40SDavid Rientjes 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
424697a225e6SJoonsoo Kim 			wakeup_kcompactd(pgdat, order, highest_zoneidx);
4247c73322d0SJohannes Weiner 		return;
42485ecd9d40SDavid Rientjes 	}
4249c73322d0SJohannes Weiner 
425097a225e6SJoonsoo Kim 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
42515ecd9d40SDavid Rientjes 				      gfp_flags);
42528d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
42531da177e4SLinus Torvalds }
42541da177e4SLinus Torvalds 
4255c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
42561da177e4SLinus Torvalds /*
42577b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
4258d6277db4SRafael J. Wysocki  * freed pages.
4259d6277db4SRafael J. Wysocki  *
4260d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
4261d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
4262d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
42631da177e4SLinus Torvalds  */
42647b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
42651da177e4SLinus Torvalds {
4266d6277db4SRafael J. Wysocki 	struct scan_control sc = {
42677b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
4268ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
4269b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
42709e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
4271ee814fe2SJohannes Weiner 		.may_writepage = 1,
4272ee814fe2SJohannes Weiner 		.may_unmap = 1,
4273ee814fe2SJohannes Weiner 		.may_swap = 1,
4274ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
42751da177e4SLinus Torvalds 	};
42767b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
42777b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
4278499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
42791da177e4SLinus Torvalds 
4280d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
428193781325SOmar Sandoval 	noreclaim_flag = memalloc_noreclaim_save();
42821732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
4283d6277db4SRafael J. Wysocki 
42843115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4285d6277db4SRafael J. Wysocki 
42861732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
4287499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
428893781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4289d6277db4SRafael J. Wysocki 
42907b51755cSKOSAKI Motohiro 	return nr_reclaimed;
42911da177e4SLinus Torvalds }
4292c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
42931da177e4SLinus Torvalds 
42943218ae14SYasunori Goto /*
42953218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
42963218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
42973218ae14SYasunori Goto  */
42983218ae14SYasunori Goto int kswapd_run(int nid)
42993218ae14SYasunori Goto {
43003218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
43013218ae14SYasunori Goto 	int ret = 0;
43023218ae14SYasunori Goto 
43033218ae14SYasunori Goto 	if (pgdat->kswapd)
43043218ae14SYasunori Goto 		return 0;
43053218ae14SYasunori Goto 
43063218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
43073218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
43083218ae14SYasunori Goto 		/* failure at boot is fatal */
4309c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
4310d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
4311d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
4312d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
43133218ae14SYasunori Goto 	}
43143218ae14SYasunori Goto 	return ret;
43153218ae14SYasunori Goto }
43163218ae14SYasunori Goto 
43178fe23e05SDavid Rientjes /*
4318d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
4319bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
43208fe23e05SDavid Rientjes  */
43218fe23e05SDavid Rientjes void kswapd_stop(int nid)
43228fe23e05SDavid Rientjes {
43238fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
43248fe23e05SDavid Rientjes 
4325d8adde17SJiang Liu 	if (kswapd) {
43268fe23e05SDavid Rientjes 		kthread_stop(kswapd);
4327d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
4328d8adde17SJiang Liu 	}
43298fe23e05SDavid Rientjes }
43308fe23e05SDavid Rientjes 
43311da177e4SLinus Torvalds static int __init kswapd_init(void)
43321da177e4SLinus Torvalds {
43336b700b5bSWei Yang 	int nid;
433469e05944SAndrew Morton 
43351da177e4SLinus Torvalds 	swap_setup();
433648fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
43373218ae14SYasunori Goto  		kswapd_run(nid);
43381da177e4SLinus Torvalds 	return 0;
43391da177e4SLinus Torvalds }
43401da177e4SLinus Torvalds 
43411da177e4SLinus Torvalds module_init(kswapd_init)
43429eeff239SChristoph Lameter 
43439eeff239SChristoph Lameter #ifdef CONFIG_NUMA
43449eeff239SChristoph Lameter /*
4345a5f5f91dSMel Gorman  * Node reclaim mode
43469eeff239SChristoph Lameter  *
4347a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
43489eeff239SChristoph Lameter  * the watermarks.
43499eeff239SChristoph Lameter  */
4350a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
43519eeff239SChristoph Lameter 
435251998364SDave Hansen /*
4353a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
4354a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
4355a92f7126SChristoph Lameter  * a zone.
4356a92f7126SChristoph Lameter  */
4357a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
4358a92f7126SChristoph Lameter 
43599eeff239SChristoph Lameter /*
4360a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
43619614634fSChristoph Lameter  * occur.
43629614634fSChristoph Lameter  */
43639614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
43649614634fSChristoph Lameter 
43659614634fSChristoph Lameter /*
43660ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
43670ff38490SChristoph Lameter  * slab reclaim needs to occur.
43680ff38490SChristoph Lameter  */
43690ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
43700ff38490SChristoph Lameter 
437111fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
437290afa5deSMel Gorman {
437311fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
437411fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
437511fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
437690afa5deSMel Gorman 
437790afa5deSMel Gorman 	/*
437890afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
437990afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
438090afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
438190afa5deSMel Gorman 	 */
438290afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
438390afa5deSMel Gorman }
438490afa5deSMel Gorman 
438590afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4386a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
438790afa5deSMel Gorman {
4388d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
4389d031a157SAlexandru Moise 	unsigned long delta = 0;
439090afa5deSMel Gorman 
439190afa5deSMel Gorman 	/*
439295bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
439390afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
439411fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
439590afa5deSMel Gorman 	 * a better estimate
439690afa5deSMel Gorman 	 */
4397a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
4398a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
439990afa5deSMel Gorman 	else
4400a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
440190afa5deSMel Gorman 
440290afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
4403a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
4404a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
440590afa5deSMel Gorman 
440690afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
440790afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
440890afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
440990afa5deSMel Gorman 
441090afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
441190afa5deSMel Gorman }
441290afa5deSMel Gorman 
44130ff38490SChristoph Lameter /*
4414a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
44159eeff239SChristoph Lameter  */
4416a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
44179eeff239SChristoph Lameter {
44187fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
441969e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
44209eeff239SChristoph Lameter 	struct task_struct *p = current;
4421499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
4422179e9639SAndrew Morton 	struct scan_control sc = {
442362b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4424f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
4425bd2f6199SJohannes Weiner 		.order = order,
4426a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
4427a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4428a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4429ee814fe2SJohannes Weiner 		.may_swap = 1,
4430f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
4431179e9639SAndrew Morton 	};
443257f29762SJohannes Weiner 	unsigned long pflags;
44339eeff239SChristoph Lameter 
4434132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4435132bb8cfSYafang Shao 					   sc.gfp_mask);
4436132bb8cfSYafang Shao 
44379eeff239SChristoph Lameter 	cond_resched();
443857f29762SJohannes Weiner 	psi_memstall_enter(&pflags);
443993781325SOmar Sandoval 	fs_reclaim_acquire(sc.gfp_mask);
4440d4f7796eSChristoph Lameter 	/*
444195bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4442d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
444395bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
4444d4f7796eSChristoph Lameter 	 */
4445499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
4446499118e9SVlastimil Babka 	p->flags |= PF_SWAPWRITE;
44471732d2b0SAndrew Morton 	set_task_reclaim_state(p, &sc.reclaim_state);
4448c84db23cSChristoph Lameter 
4449a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
4450a92f7126SChristoph Lameter 		/*
4451894befecSAndrey Ryabinin 		 * Free memory by calling shrink node with increasing
44520ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
4453a92f7126SChristoph Lameter 		 */
4454a92f7126SChristoph Lameter 		do {
4455970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
44569e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
44570ff38490SChristoph Lameter 	}
4458a92f7126SChristoph Lameter 
44591732d2b0SAndrew Morton 	set_task_reclaim_state(p, NULL);
4460499118e9SVlastimil Babka 	current->flags &= ~PF_SWAPWRITE;
4461499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
446293781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
446357f29762SJohannes Weiner 	psi_memstall_leave(&pflags);
4464132bb8cfSYafang Shao 
4465132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4466132bb8cfSYafang Shao 
4467a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
44689eeff239SChristoph Lameter }
4469179e9639SAndrew Morton 
4470a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4471179e9639SAndrew Morton {
4472d773ed6bSDavid Rientjes 	int ret;
4473179e9639SAndrew Morton 
4474179e9639SAndrew Morton 	/*
4475a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
44760ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
447734aa1330SChristoph Lameter 	 *
44789614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
44799614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
4480a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
4481a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
44829614634fSChristoph Lameter 	 * unmapped file backed pages.
4483179e9639SAndrew Morton 	 */
4484a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4485d42f3245SRoman Gushchin 	    node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
4486d42f3245SRoman Gushchin 	    pgdat->min_slab_pages)
4487a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
4488179e9639SAndrew Morton 
4489179e9639SAndrew Morton 	/*
4490d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
4491179e9639SAndrew Morton 	 */
4492d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4493a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4494179e9639SAndrew Morton 
4495179e9639SAndrew Morton 	/*
4496a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
4497179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
4498179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
4499179e9639SAndrew Morton 	 * as wide as possible.
4500179e9639SAndrew Morton 	 */
4501a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4502a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4503d773ed6bSDavid Rientjes 
4504a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4505a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4506fa5e084eSMel Gorman 
4507a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
4508a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4509d773ed6bSDavid Rientjes 
451024cf7251SMel Gorman 	if (!ret)
451124cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
451224cf7251SMel Gorman 
4513d773ed6bSDavid Rientjes 	return ret;
4514179e9639SAndrew Morton }
45159eeff239SChristoph Lameter #endif
4516894bc310SLee Schermerhorn 
451789e004eaSLee Schermerhorn /**
451864e3d12fSKuo-Hsin Yang  * check_move_unevictable_pages - check pages for evictability and move to
451964e3d12fSKuo-Hsin Yang  * appropriate zone lru list
452064e3d12fSKuo-Hsin Yang  * @pvec: pagevec with lru pages to check
452189e004eaSLee Schermerhorn  *
452264e3d12fSKuo-Hsin Yang  * Checks pages for evictability, if an evictable page is in the unevictable
452364e3d12fSKuo-Hsin Yang  * lru list, moves it to the appropriate evictable lru list. This function
452464e3d12fSKuo-Hsin Yang  * should be only used for lru pages.
452589e004eaSLee Schermerhorn  */
452664e3d12fSKuo-Hsin Yang void check_move_unevictable_pages(struct pagevec *pvec)
452789e004eaSLee Schermerhorn {
45286168d0daSAlex Shi 	struct lruvec *lruvec = NULL;
452924513264SHugh Dickins 	int pgscanned = 0;
453024513264SHugh Dickins 	int pgrescued = 0;
453189e004eaSLee Schermerhorn 	int i;
453289e004eaSLee Schermerhorn 
453364e3d12fSKuo-Hsin Yang 	for (i = 0; i < pvec->nr; i++) {
453464e3d12fSKuo-Hsin Yang 		struct page *page = pvec->pages[i];
45358d8869caSHugh Dickins 		int nr_pages;
453689e004eaSLee Schermerhorn 
45378d8869caSHugh Dickins 		if (PageTransTail(page))
45388d8869caSHugh Dickins 			continue;
45398d8869caSHugh Dickins 
45408d8869caSHugh Dickins 		nr_pages = thp_nr_pages(page);
45418d8869caSHugh Dickins 		pgscanned += nr_pages;
45428d8869caSHugh Dickins 
4543d25b5bd8SAlex Shi 		/* block memcg migration during page moving between lru */
4544d25b5bd8SAlex Shi 		if (!TestClearPageLRU(page))
4545d25b5bd8SAlex Shi 			continue;
4546d25b5bd8SAlex Shi 
45472a5e4e34SAlexander Duyck 		lruvec = relock_page_lruvec_irq(page, lruvec);
4548d25b5bd8SAlex Shi 		if (page_evictable(page) && PageUnevictable(page)) {
454946ae6b2cSYu Zhao 			del_page_from_lru_list(page, lruvec);
455024513264SHugh Dickins 			ClearPageUnevictable(page);
45513a9c9788SYu Zhao 			add_page_to_lru_list(page, lruvec);
45528d8869caSHugh Dickins 			pgrescued += nr_pages;
455389e004eaSLee Schermerhorn 		}
4554d25b5bd8SAlex Shi 		SetPageLRU(page);
455589e004eaSLee Schermerhorn 	}
455624513264SHugh Dickins 
45576168d0daSAlex Shi 	if (lruvec) {
455824513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
455924513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
45606168d0daSAlex Shi 		unlock_page_lruvec_irq(lruvec);
4561d25b5bd8SAlex Shi 	} else if (pgscanned) {
4562d25b5bd8SAlex Shi 		count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
456324513264SHugh Dickins 	}
456485046579SHugh Dickins }
456564e3d12fSKuo-Hsin Yang EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
4566