xref: /openbmc/linux/mm/vmscan.c (revision c3f4a9a2b082c5392fbff17c6d8551154add5fdb)
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>
4426aa2d19SDave Hansen #include <linux/migrate.h>
45873b4771SKeika Kobayashi #include <linux/delayacct.h>
46af936a16SLee Schermerhorn #include <linux/sysctl.h>
47929bea7cSKOSAKI Motohiro #include <linux/oom.h>
4864e3d12fSKuo-Hsin Yang #include <linux/pagevec.h>
49268bb0ceSLinus Torvalds #include <linux/prefetch.h>
50b1de0d13SMitchel Humpherys #include <linux/printk.h>
51f9fe48beSRoss Zwisler #include <linux/dax.h>
52eb414681SJohannes Weiner #include <linux/psi.h>
531da177e4SLinus Torvalds 
541da177e4SLinus Torvalds #include <asm/tlbflush.h>
551da177e4SLinus Torvalds #include <asm/div64.h>
561da177e4SLinus Torvalds 
571da177e4SLinus Torvalds #include <linux/swapops.h>
58117aad1eSRafael Aquini #include <linux/balloon_compaction.h>
591da177e4SLinus Torvalds 
600f8053a5SNick Piggin #include "internal.h"
610f8053a5SNick Piggin 
6233906bc5SMel Gorman #define CREATE_TRACE_POINTS
6333906bc5SMel Gorman #include <trace/events/vmscan.h>
6433906bc5SMel Gorman 
651da177e4SLinus Torvalds struct scan_control {
6622fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6722fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
6822fba335SKOSAKI Motohiro 
69ee814fe2SJohannes Weiner 	/*
70ee814fe2SJohannes Weiner 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
71ee814fe2SJohannes Weiner 	 * are scanned.
72ee814fe2SJohannes Weiner 	 */
73ee814fe2SJohannes Weiner 	nodemask_t	*nodemask;
749e3b2f8cSKonstantin Khlebnikov 
755f53e762SKOSAKI Motohiro 	/*
76f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
77f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
78f16015fbSJohannes Weiner 	 */
79f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
8066e1707bSBalbir Singh 
817cf111bcSJohannes Weiner 	/*
827cf111bcSJohannes Weiner 	 * Scan pressure balancing between anon and file LRUs
837cf111bcSJohannes Weiner 	 */
847cf111bcSJohannes Weiner 	unsigned long	anon_cost;
857cf111bcSJohannes Weiner 	unsigned long	file_cost;
867cf111bcSJohannes Weiner 
87b91ac374SJohannes Weiner 	/* Can active pages be deactivated as part of reclaim? */
88b91ac374SJohannes Weiner #define DEACTIVATE_ANON 1
89b91ac374SJohannes Weiner #define DEACTIVATE_FILE 2
90b91ac374SJohannes Weiner 	unsigned int may_deactivate:2;
91b91ac374SJohannes Weiner 	unsigned int force_deactivate:1;
92b91ac374SJohannes Weiner 	unsigned int skipped_deactivate:1;
93b91ac374SJohannes Weiner 
941276ad68SJohannes Weiner 	/* Writepage batching in laptop mode; RECLAIM_WRITE */
95ee814fe2SJohannes Weiner 	unsigned int may_writepage:1;
96ee814fe2SJohannes Weiner 
97ee814fe2SJohannes Weiner 	/* Can mapped pages be reclaimed? */
98ee814fe2SJohannes Weiner 	unsigned int may_unmap:1;
99ee814fe2SJohannes Weiner 
100ee814fe2SJohannes Weiner 	/* Can pages be swapped as part of reclaim? */
101ee814fe2SJohannes Weiner 	unsigned int may_swap:1;
102ee814fe2SJohannes Weiner 
103d6622f63SYisheng Xie 	/*
104f56ce412SJohannes Weiner 	 * Cgroup memory below memory.low is protected as long as we
105f56ce412SJohannes Weiner 	 * don't threaten to OOM. If any cgroup is reclaimed at
106f56ce412SJohannes Weiner 	 * reduced force or passed over entirely due to its memory.low
107f56ce412SJohannes Weiner 	 * setting (memcg_low_skipped), and nothing is reclaimed as a
108f56ce412SJohannes Weiner 	 * result, then go back for one more cycle that reclaims the protected
109f56ce412SJohannes Weiner 	 * memory (memcg_low_reclaim) to avert OOM.
110d6622f63SYisheng Xie 	 */
111d6622f63SYisheng Xie 	unsigned int memcg_low_reclaim:1;
112d6622f63SYisheng Xie 	unsigned int memcg_low_skipped:1;
113241994edSJohannes Weiner 
114ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
115ee814fe2SJohannes Weiner 
116ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
117ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
118ee814fe2SJohannes Weiner 
119b91ac374SJohannes Weiner 	/* There is easily reclaimable cold cache in the current node */
120b91ac374SJohannes Weiner 	unsigned int cache_trim_mode:1;
121b91ac374SJohannes Weiner 
12253138ceaSJohannes Weiner 	/* The file pages on the current node are dangerously low */
12353138ceaSJohannes Weiner 	unsigned int file_is_tiny:1;
12453138ceaSJohannes Weiner 
12526aa2d19SDave Hansen 	/* Always discard instead of demoting to lower tier memory */
12626aa2d19SDave Hansen 	unsigned int no_demotion:1;
12726aa2d19SDave Hansen 
128bb451fdfSGreg Thelen 	/* Allocation order */
129bb451fdfSGreg Thelen 	s8 order;
130bb451fdfSGreg Thelen 
131bb451fdfSGreg Thelen 	/* Scan (total_size >> priority) pages at once */
132bb451fdfSGreg Thelen 	s8 priority;
133bb451fdfSGreg Thelen 
134bb451fdfSGreg Thelen 	/* The highest zone to isolate pages for reclaim from */
135bb451fdfSGreg Thelen 	s8 reclaim_idx;
136bb451fdfSGreg Thelen 
137bb451fdfSGreg Thelen 	/* This context's GFP mask */
138bb451fdfSGreg Thelen 	gfp_t gfp_mask;
139bb451fdfSGreg Thelen 
140ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
141ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
142ee814fe2SJohannes Weiner 
143ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
144ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
145d108c772SAndrey Ryabinin 
146d108c772SAndrey Ryabinin 	struct {
147d108c772SAndrey Ryabinin 		unsigned int dirty;
148d108c772SAndrey Ryabinin 		unsigned int unqueued_dirty;
149d108c772SAndrey Ryabinin 		unsigned int congested;
150d108c772SAndrey Ryabinin 		unsigned int writeback;
151d108c772SAndrey Ryabinin 		unsigned int immediate;
152d108c772SAndrey Ryabinin 		unsigned int file_taken;
153d108c772SAndrey Ryabinin 		unsigned int taken;
154d108c772SAndrey Ryabinin 	} nr;
155e5ca8071SYafang Shao 
156e5ca8071SYafang Shao 	/* for recording the reclaimed slab by now */
157e5ca8071SYafang Shao 	struct reclaim_state reclaim_state;
1581da177e4SLinus Torvalds };
1591da177e4SLinus Torvalds 
1601da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1611da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1621da177e4SLinus Torvalds 	do {								\
1631da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1641da177e4SLinus Torvalds 			struct page *prev;				\
1651da177e4SLinus Torvalds 									\
1661da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1671da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1681da177e4SLinus Torvalds 		}							\
1691da177e4SLinus Torvalds 	} while (0)
1701da177e4SLinus Torvalds #else
1711da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1721da177e4SLinus Torvalds #endif
1731da177e4SLinus Torvalds 
1741da177e4SLinus Torvalds /*
175c843966cSJohannes Weiner  * From 0 .. 200.  Higher means more swappy.
1761da177e4SLinus Torvalds  */
1771da177e4SLinus Torvalds int vm_swappiness = 60;
1781da177e4SLinus Torvalds 
1790a432dcbSYang Shi static void set_task_reclaim_state(struct task_struct *task,
1800a432dcbSYang Shi 				   struct reclaim_state *rs)
1810a432dcbSYang Shi {
1820a432dcbSYang Shi 	/* Check for an overwrite */
1830a432dcbSYang Shi 	WARN_ON_ONCE(rs && task->reclaim_state);
1840a432dcbSYang Shi 
1850a432dcbSYang Shi 	/* Check for the nulling of an already-nulled member */
1860a432dcbSYang Shi 	WARN_ON_ONCE(!rs && !task->reclaim_state);
1870a432dcbSYang Shi 
1880a432dcbSYang Shi 	task->reclaim_state = rs;
1890a432dcbSYang Shi }
1900a432dcbSYang Shi 
1911da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1921da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1931da177e4SLinus Torvalds 
1940a432dcbSYang Shi #ifdef CONFIG_MEMCG
195a2fb1261SYang Shi static int shrinker_nr_max;
1962bfd3637SYang Shi 
1973c6f17e6SYang Shi /* The shrinker_info is expanded in a batch of BITS_PER_LONG */
198a2fb1261SYang Shi static inline int shrinker_map_size(int nr_items)
199a2fb1261SYang Shi {
200a2fb1261SYang Shi 	return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
201a2fb1261SYang Shi }
2022bfd3637SYang Shi 
2033c6f17e6SYang Shi static inline int shrinker_defer_size(int nr_items)
2043c6f17e6SYang Shi {
2053c6f17e6SYang Shi 	return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
2063c6f17e6SYang Shi }
2073c6f17e6SYang Shi 
208468ab843SYang Shi static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
209468ab843SYang Shi 						     int nid)
210468ab843SYang Shi {
211468ab843SYang Shi 	return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
212468ab843SYang Shi 					 lockdep_is_held(&shrinker_rwsem));
213468ab843SYang Shi }
214468ab843SYang Shi 
215e4262c4fSYang Shi static int expand_one_shrinker_info(struct mem_cgroup *memcg,
2163c6f17e6SYang Shi 				    int map_size, int defer_size,
2173c6f17e6SYang Shi 				    int old_map_size, int old_defer_size)
2182bfd3637SYang Shi {
219e4262c4fSYang Shi 	struct shrinker_info *new, *old;
2202bfd3637SYang Shi 	struct mem_cgroup_per_node *pn;
2212bfd3637SYang Shi 	int nid;
2223c6f17e6SYang Shi 	int size = map_size + defer_size;
2232bfd3637SYang Shi 
2242bfd3637SYang Shi 	for_each_node(nid) {
2252bfd3637SYang Shi 		pn = memcg->nodeinfo[nid];
226468ab843SYang Shi 		old = shrinker_info_protected(memcg, nid);
2272bfd3637SYang Shi 		/* Not yet online memcg */
2282bfd3637SYang Shi 		if (!old)
2292bfd3637SYang Shi 			return 0;
2302bfd3637SYang Shi 
2312bfd3637SYang Shi 		new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
2322bfd3637SYang Shi 		if (!new)
2332bfd3637SYang Shi 			return -ENOMEM;
2342bfd3637SYang Shi 
2353c6f17e6SYang Shi 		new->nr_deferred = (atomic_long_t *)(new + 1);
2363c6f17e6SYang Shi 		new->map = (void *)new->nr_deferred + defer_size;
2373c6f17e6SYang Shi 
2383c6f17e6SYang Shi 		/* map: set all old bits, clear all new bits */
2393c6f17e6SYang Shi 		memset(new->map, (int)0xff, old_map_size);
2403c6f17e6SYang Shi 		memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
2413c6f17e6SYang Shi 		/* nr_deferred: copy old values, clear all new values */
2423c6f17e6SYang Shi 		memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
2433c6f17e6SYang Shi 		memset((void *)new->nr_deferred + old_defer_size, 0,
2443c6f17e6SYang Shi 		       defer_size - old_defer_size);
2452bfd3637SYang Shi 
246e4262c4fSYang Shi 		rcu_assign_pointer(pn->shrinker_info, new);
24772673e86SYang Shi 		kvfree_rcu(old, rcu);
2482bfd3637SYang Shi 	}
2492bfd3637SYang Shi 
2502bfd3637SYang Shi 	return 0;
2512bfd3637SYang Shi }
2522bfd3637SYang Shi 
253e4262c4fSYang Shi void free_shrinker_info(struct mem_cgroup *memcg)
2542bfd3637SYang Shi {
2552bfd3637SYang Shi 	struct mem_cgroup_per_node *pn;
256e4262c4fSYang Shi 	struct shrinker_info *info;
2572bfd3637SYang Shi 	int nid;
2582bfd3637SYang Shi 
2592bfd3637SYang Shi 	for_each_node(nid) {
2602bfd3637SYang Shi 		pn = memcg->nodeinfo[nid];
261e4262c4fSYang Shi 		info = rcu_dereference_protected(pn->shrinker_info, true);
262e4262c4fSYang Shi 		kvfree(info);
263e4262c4fSYang Shi 		rcu_assign_pointer(pn->shrinker_info, NULL);
2642bfd3637SYang Shi 	}
2652bfd3637SYang Shi }
2662bfd3637SYang Shi 
267e4262c4fSYang Shi int alloc_shrinker_info(struct mem_cgroup *memcg)
2682bfd3637SYang Shi {
269e4262c4fSYang Shi 	struct shrinker_info *info;
2702bfd3637SYang Shi 	int nid, size, ret = 0;
2713c6f17e6SYang Shi 	int map_size, defer_size = 0;
2722bfd3637SYang Shi 
273d27cf2aaSYang Shi 	down_write(&shrinker_rwsem);
2743c6f17e6SYang Shi 	map_size = shrinker_map_size(shrinker_nr_max);
2753c6f17e6SYang Shi 	defer_size = shrinker_defer_size(shrinker_nr_max);
2763c6f17e6SYang Shi 	size = map_size + defer_size;
2772bfd3637SYang Shi 	for_each_node(nid) {
278e4262c4fSYang Shi 		info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
279e4262c4fSYang Shi 		if (!info) {
280e4262c4fSYang Shi 			free_shrinker_info(memcg);
2812bfd3637SYang Shi 			ret = -ENOMEM;
2822bfd3637SYang Shi 			break;
2832bfd3637SYang Shi 		}
2843c6f17e6SYang Shi 		info->nr_deferred = (atomic_long_t *)(info + 1);
2853c6f17e6SYang Shi 		info->map = (void *)info->nr_deferred + defer_size;
286e4262c4fSYang Shi 		rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
2872bfd3637SYang Shi 	}
288d27cf2aaSYang Shi 	up_write(&shrinker_rwsem);
2892bfd3637SYang Shi 
2902bfd3637SYang Shi 	return ret;
2912bfd3637SYang Shi }
2922bfd3637SYang Shi 
2933c6f17e6SYang Shi static inline bool need_expand(int nr_max)
2943c6f17e6SYang Shi {
2953c6f17e6SYang Shi 	return round_up(nr_max, BITS_PER_LONG) >
2963c6f17e6SYang Shi 	       round_up(shrinker_nr_max, BITS_PER_LONG);
2973c6f17e6SYang Shi }
2983c6f17e6SYang Shi 
299e4262c4fSYang Shi static int expand_shrinker_info(int new_id)
3002bfd3637SYang Shi {
3013c6f17e6SYang Shi 	int ret = 0;
302a2fb1261SYang Shi 	int new_nr_max = new_id + 1;
3033c6f17e6SYang Shi 	int map_size, defer_size = 0;
3043c6f17e6SYang Shi 	int old_map_size, old_defer_size = 0;
3052bfd3637SYang Shi 	struct mem_cgroup *memcg;
3062bfd3637SYang Shi 
3073c6f17e6SYang Shi 	if (!need_expand(new_nr_max))
308a2fb1261SYang Shi 		goto out;
3092bfd3637SYang Shi 
3102bfd3637SYang Shi 	if (!root_mem_cgroup)
311d27cf2aaSYang Shi 		goto out;
312d27cf2aaSYang Shi 
313d27cf2aaSYang Shi 	lockdep_assert_held(&shrinker_rwsem);
3142bfd3637SYang Shi 
3153c6f17e6SYang Shi 	map_size = shrinker_map_size(new_nr_max);
3163c6f17e6SYang Shi 	defer_size = shrinker_defer_size(new_nr_max);
3173c6f17e6SYang Shi 	old_map_size = shrinker_map_size(shrinker_nr_max);
3183c6f17e6SYang Shi 	old_defer_size = shrinker_defer_size(shrinker_nr_max);
3193c6f17e6SYang Shi 
3202bfd3637SYang Shi 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3212bfd3637SYang Shi 	do {
3223c6f17e6SYang Shi 		ret = expand_one_shrinker_info(memcg, map_size, defer_size,
3233c6f17e6SYang Shi 					       old_map_size, old_defer_size);
3242bfd3637SYang Shi 		if (ret) {
3252bfd3637SYang Shi 			mem_cgroup_iter_break(NULL, memcg);
326d27cf2aaSYang Shi 			goto out;
3272bfd3637SYang Shi 		}
3282bfd3637SYang Shi 	} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
329d27cf2aaSYang Shi out:
3302bfd3637SYang Shi 	if (!ret)
331a2fb1261SYang Shi 		shrinker_nr_max = new_nr_max;
332d27cf2aaSYang Shi 
3332bfd3637SYang Shi 	return ret;
3342bfd3637SYang Shi }
3352bfd3637SYang Shi 
3362bfd3637SYang Shi void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
3372bfd3637SYang Shi {
3382bfd3637SYang Shi 	if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
339e4262c4fSYang Shi 		struct shrinker_info *info;
3402bfd3637SYang Shi 
3412bfd3637SYang Shi 		rcu_read_lock();
342e4262c4fSYang Shi 		info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
3432bfd3637SYang Shi 		/* Pairs with smp mb in shrink_slab() */
3442bfd3637SYang Shi 		smp_mb__before_atomic();
345e4262c4fSYang Shi 		set_bit(shrinker_id, info->map);
3462bfd3637SYang Shi 		rcu_read_unlock();
3472bfd3637SYang Shi 	}
3482bfd3637SYang Shi }
3492bfd3637SYang Shi 
350b4c2b231SKirill Tkhai static DEFINE_IDR(shrinker_idr);
351b4c2b231SKirill Tkhai 
352b4c2b231SKirill Tkhai static int prealloc_memcg_shrinker(struct shrinker *shrinker)
353b4c2b231SKirill Tkhai {
354b4c2b231SKirill Tkhai 	int id, ret = -ENOMEM;
355b4c2b231SKirill Tkhai 
356476b30a0SYang Shi 	if (mem_cgroup_disabled())
357476b30a0SYang Shi 		return -ENOSYS;
358476b30a0SYang Shi 
359b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
360b4c2b231SKirill Tkhai 	/* This may call shrinker, so it must use down_read_trylock() */
36141ca668aSYang Shi 	id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
362b4c2b231SKirill Tkhai 	if (id < 0)
363b4c2b231SKirill Tkhai 		goto unlock;
364b4c2b231SKirill Tkhai 
3650a4465d3SKirill Tkhai 	if (id >= shrinker_nr_max) {
366e4262c4fSYang Shi 		if (expand_shrinker_info(id)) {
3670a4465d3SKirill Tkhai 			idr_remove(&shrinker_idr, id);
3680a4465d3SKirill Tkhai 			goto unlock;
3690a4465d3SKirill Tkhai 		}
3700a4465d3SKirill Tkhai 	}
371b4c2b231SKirill Tkhai 	shrinker->id = id;
372b4c2b231SKirill Tkhai 	ret = 0;
373b4c2b231SKirill Tkhai unlock:
374b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
375b4c2b231SKirill Tkhai 	return ret;
376b4c2b231SKirill Tkhai }
377b4c2b231SKirill Tkhai 
378b4c2b231SKirill Tkhai static void unregister_memcg_shrinker(struct shrinker *shrinker)
379b4c2b231SKirill Tkhai {
380b4c2b231SKirill Tkhai 	int id = shrinker->id;
381b4c2b231SKirill Tkhai 
382b4c2b231SKirill Tkhai 	BUG_ON(id < 0);
383b4c2b231SKirill Tkhai 
38441ca668aSYang Shi 	lockdep_assert_held(&shrinker_rwsem);
38541ca668aSYang Shi 
386b4c2b231SKirill Tkhai 	idr_remove(&shrinker_idr, id);
387b4c2b231SKirill Tkhai }
388b4c2b231SKirill Tkhai 
38986750830SYang Shi static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
39086750830SYang Shi 				   struct mem_cgroup *memcg)
39186750830SYang Shi {
39286750830SYang Shi 	struct shrinker_info *info;
39386750830SYang Shi 
39486750830SYang Shi 	info = shrinker_info_protected(memcg, nid);
39586750830SYang Shi 	return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
39686750830SYang Shi }
39786750830SYang Shi 
39886750830SYang Shi static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
39986750830SYang Shi 				  struct mem_cgroup *memcg)
40086750830SYang Shi {
40186750830SYang Shi 	struct shrinker_info *info;
40286750830SYang Shi 
40386750830SYang Shi 	info = shrinker_info_protected(memcg, nid);
40486750830SYang Shi 	return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
40586750830SYang Shi }
40686750830SYang Shi 
407a178015cSYang Shi void reparent_shrinker_deferred(struct mem_cgroup *memcg)
408a178015cSYang Shi {
409a178015cSYang Shi 	int i, nid;
410a178015cSYang Shi 	long nr;
411a178015cSYang Shi 	struct mem_cgroup *parent;
412a178015cSYang Shi 	struct shrinker_info *child_info, *parent_info;
413a178015cSYang Shi 
414a178015cSYang Shi 	parent = parent_mem_cgroup(memcg);
415a178015cSYang Shi 	if (!parent)
416a178015cSYang Shi 		parent = root_mem_cgroup;
417a178015cSYang Shi 
418a178015cSYang Shi 	/* Prevent from concurrent shrinker_info expand */
419a178015cSYang Shi 	down_read(&shrinker_rwsem);
420a178015cSYang Shi 	for_each_node(nid) {
421a178015cSYang Shi 		child_info = shrinker_info_protected(memcg, nid);
422a178015cSYang Shi 		parent_info = shrinker_info_protected(parent, nid);
423a178015cSYang Shi 		for (i = 0; i < shrinker_nr_max; i++) {
424a178015cSYang Shi 			nr = atomic_long_read(&child_info->nr_deferred[i]);
425a178015cSYang Shi 			atomic_long_add(nr, &parent_info->nr_deferred[i]);
426a178015cSYang Shi 		}
427a178015cSYang Shi 	}
428a178015cSYang Shi 	up_read(&shrinker_rwsem);
429a178015cSYang Shi }
430a178015cSYang Shi 
431b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
43289b5fae5SJohannes Weiner {
433b5ead35eSJohannes Weiner 	return sc->target_mem_cgroup;
43489b5fae5SJohannes Weiner }
43597c9341fSTejun Heo 
43697c9341fSTejun Heo /**
437b5ead35eSJohannes Weiner  * writeback_throttling_sane - is the usual dirty throttling mechanism available?
43897c9341fSTejun Heo  * @sc: scan_control in question
43997c9341fSTejun Heo  *
44097c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
44197c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
44297c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
44397c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
44497c9341fSTejun Heo  * allocation and configurability.
44597c9341fSTejun Heo  *
44697c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
44797c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
44897c9341fSTejun Heo  */
449b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
45097c9341fSTejun Heo {
451b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
45297c9341fSTejun Heo 		return true;
45397c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
45469234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
45597c9341fSTejun Heo 		return true;
45697c9341fSTejun Heo #endif
45797c9341fSTejun Heo 	return false;
45897c9341fSTejun Heo }
45991a45470SKAMEZAWA Hiroyuki #else
4600a432dcbSYang Shi static int prealloc_memcg_shrinker(struct shrinker *shrinker)
4610a432dcbSYang Shi {
462476b30a0SYang Shi 	return -ENOSYS;
4630a432dcbSYang Shi }
4640a432dcbSYang Shi 
4650a432dcbSYang Shi static void unregister_memcg_shrinker(struct shrinker *shrinker)
4660a432dcbSYang Shi {
4670a432dcbSYang Shi }
4680a432dcbSYang Shi 
46986750830SYang Shi static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
47086750830SYang Shi 				   struct mem_cgroup *memcg)
47186750830SYang Shi {
47286750830SYang Shi 	return 0;
47386750830SYang Shi }
47486750830SYang Shi 
47586750830SYang Shi static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
47686750830SYang Shi 				  struct mem_cgroup *memcg)
47786750830SYang Shi {
47886750830SYang Shi 	return 0;
47986750830SYang Shi }
48086750830SYang Shi 
481b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
48289b5fae5SJohannes Weiner {
483b5ead35eSJohannes Weiner 	return false;
48489b5fae5SJohannes Weiner }
48597c9341fSTejun Heo 
486b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
48797c9341fSTejun Heo {
48897c9341fSTejun Heo 	return true;
48997c9341fSTejun Heo }
49091a45470SKAMEZAWA Hiroyuki #endif
49191a45470SKAMEZAWA Hiroyuki 
49286750830SYang Shi static long xchg_nr_deferred(struct shrinker *shrinker,
49386750830SYang Shi 			     struct shrink_control *sc)
49486750830SYang Shi {
49586750830SYang Shi 	int nid = sc->nid;
49686750830SYang Shi 
49786750830SYang Shi 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
49886750830SYang Shi 		nid = 0;
49986750830SYang Shi 
50086750830SYang Shi 	if (sc->memcg &&
50186750830SYang Shi 	    (shrinker->flags & SHRINKER_MEMCG_AWARE))
50286750830SYang Shi 		return xchg_nr_deferred_memcg(nid, shrinker,
50386750830SYang Shi 					      sc->memcg);
50486750830SYang Shi 
50586750830SYang Shi 	return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
50686750830SYang Shi }
50786750830SYang Shi 
50886750830SYang Shi 
50986750830SYang Shi static long add_nr_deferred(long nr, struct shrinker *shrinker,
51086750830SYang Shi 			    struct shrink_control *sc)
51186750830SYang Shi {
51286750830SYang Shi 	int nid = sc->nid;
51386750830SYang Shi 
51486750830SYang Shi 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
51586750830SYang Shi 		nid = 0;
51686750830SYang Shi 
51786750830SYang Shi 	if (sc->memcg &&
51886750830SYang Shi 	    (shrinker->flags & SHRINKER_MEMCG_AWARE))
51986750830SYang Shi 		return add_nr_deferred_memcg(nr, nid, shrinker,
52086750830SYang Shi 					     sc->memcg);
52186750830SYang Shi 
52286750830SYang Shi 	return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
52386750830SYang Shi }
52486750830SYang Shi 
52526aa2d19SDave Hansen static bool can_demote(int nid, struct scan_control *sc)
52626aa2d19SDave Hansen {
52720b51af1SHuang Ying 	if (!numa_demotion_enabled)
52820b51af1SHuang Ying 		return false;
5293a235693SDave Hansen 	if (sc) {
5303a235693SDave Hansen 		if (sc->no_demotion)
53126aa2d19SDave Hansen 			return false;
5323a235693SDave Hansen 		/* It is pointless to do demotion in memcg reclaim */
5333a235693SDave Hansen 		if (cgroup_reclaim(sc))
5343a235693SDave Hansen 			return false;
5353a235693SDave Hansen 	}
53626aa2d19SDave Hansen 	if (next_demotion_node(nid) == NUMA_NO_NODE)
53726aa2d19SDave Hansen 		return false;
53826aa2d19SDave Hansen 
53920b51af1SHuang Ying 	return true;
54026aa2d19SDave Hansen }
54126aa2d19SDave Hansen 
542a2a36488SKeith Busch static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
543a2a36488SKeith Busch 					  int nid,
544a2a36488SKeith Busch 					  struct scan_control *sc)
545a2a36488SKeith Busch {
546a2a36488SKeith Busch 	if (memcg == NULL) {
547a2a36488SKeith Busch 		/*
548a2a36488SKeith Busch 		 * For non-memcg reclaim, is there
549a2a36488SKeith Busch 		 * space in any swap device?
550a2a36488SKeith Busch 		 */
551a2a36488SKeith Busch 		if (get_nr_swap_pages() > 0)
552a2a36488SKeith Busch 			return true;
553a2a36488SKeith Busch 	} else {
554a2a36488SKeith Busch 		/* Is the memcg below its swap limit? */
555a2a36488SKeith Busch 		if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
556a2a36488SKeith Busch 			return true;
557a2a36488SKeith Busch 	}
558a2a36488SKeith Busch 
559a2a36488SKeith Busch 	/*
560a2a36488SKeith Busch 	 * The page can not be swapped.
561a2a36488SKeith Busch 	 *
562a2a36488SKeith Busch 	 * Can it be reclaimed from this node via demotion?
563a2a36488SKeith Busch 	 */
564a2a36488SKeith Busch 	return can_demote(nid, sc);
565a2a36488SKeith Busch }
566a2a36488SKeith Busch 
5675a1c84b4SMel Gorman /*
5685a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
5695a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
5705a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
5715a1c84b4SMel Gorman  */
5725a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
5735a1c84b4SMel Gorman {
5745a1c84b4SMel Gorman 	unsigned long nr;
5755a1c84b4SMel Gorman 
5765a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
5775a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
578a2a36488SKeith Busch 	if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
5795a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
5805a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
5815a1c84b4SMel Gorman 
5825a1c84b4SMel Gorman 	return nr;
5835a1c84b4SMel Gorman }
5845a1c84b4SMel Gorman 
585fd538803SMichal Hocko /**
586fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
587fd538803SMichal Hocko  * @lruvec: lru vector
588fd538803SMichal Hocko  * @lru: lru to use
589fd538803SMichal Hocko  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
590fd538803SMichal Hocko  */
5912091339dSYu Zhao static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
5922091339dSYu Zhao 				     int zone_idx)
593c9f299d9SKOSAKI Motohiro {
594de3b0150SJohannes Weiner 	unsigned long size = 0;
595fd538803SMichal Hocko 	int zid;
596a3d8e054SKOSAKI Motohiro 
597de3b0150SJohannes Weiner 	for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
598fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
599fd538803SMichal Hocko 
600fd538803SMichal Hocko 		if (!managed_zone(zone))
601fd538803SMichal Hocko 			continue;
602fd538803SMichal Hocko 
603fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
604de3b0150SJohannes Weiner 			size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
605fd538803SMichal Hocko 		else
606de3b0150SJohannes Weiner 			size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
607c9f299d9SKOSAKI Motohiro 	}
608de3b0150SJohannes Weiner 	return size;
609b4536f0cSMichal Hocko }
610b4536f0cSMichal Hocko 
6111da177e4SLinus Torvalds /*
6121d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
6131da177e4SLinus Torvalds  */
6148e04944fSTetsuo Handa int prealloc_shrinker(struct shrinker *shrinker)
6151da177e4SLinus Torvalds {
616476b30a0SYang Shi 	unsigned int size;
617476b30a0SYang Shi 	int err;
6181d3d4437SGlauber Costa 
619476b30a0SYang Shi 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
620476b30a0SYang Shi 		err = prealloc_memcg_shrinker(shrinker);
621476b30a0SYang Shi 		if (err != -ENOSYS)
622476b30a0SYang Shi 			return err;
623476b30a0SYang Shi 
624476b30a0SYang Shi 		shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
625476b30a0SYang Shi 	}
626476b30a0SYang Shi 
627476b30a0SYang Shi 	size = sizeof(*shrinker->nr_deferred);
6281d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
6291d3d4437SGlauber Costa 		size *= nr_node_ids;
6301d3d4437SGlauber Costa 
6311d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
6321d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
6331d3d4437SGlauber Costa 		return -ENOMEM;
634b4c2b231SKirill Tkhai 
6358e04944fSTetsuo Handa 	return 0;
6368e04944fSTetsuo Handa }
6371d3d4437SGlauber Costa 
6388e04944fSTetsuo Handa void free_prealloced_shrinker(struct shrinker *shrinker)
6398e04944fSTetsuo Handa {
64041ca668aSYang Shi 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
64141ca668aSYang Shi 		down_write(&shrinker_rwsem);
642b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
64341ca668aSYang Shi 		up_write(&shrinker_rwsem);
644476b30a0SYang Shi 		return;
64541ca668aSYang Shi 	}
646b4c2b231SKirill Tkhai 
6478e04944fSTetsuo Handa 	kfree(shrinker->nr_deferred);
6488e04944fSTetsuo Handa 	shrinker->nr_deferred = NULL;
6498e04944fSTetsuo Handa }
6508e04944fSTetsuo Handa 
6518e04944fSTetsuo Handa void register_shrinker_prepared(struct shrinker *shrinker)
6528e04944fSTetsuo Handa {
6531da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
6541da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
65541ca668aSYang Shi 	shrinker->flags |= SHRINKER_REGISTERED;
6561da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
6578e04944fSTetsuo Handa }
6588e04944fSTetsuo Handa 
6598e04944fSTetsuo Handa int register_shrinker(struct shrinker *shrinker)
6608e04944fSTetsuo Handa {
6618e04944fSTetsuo Handa 	int err = prealloc_shrinker(shrinker);
6628e04944fSTetsuo Handa 
6638e04944fSTetsuo Handa 	if (err)
6648e04944fSTetsuo Handa 		return err;
6658e04944fSTetsuo Handa 	register_shrinker_prepared(shrinker);
6661d3d4437SGlauber Costa 	return 0;
6671da177e4SLinus Torvalds }
6688e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
6691da177e4SLinus Torvalds 
6701da177e4SLinus Torvalds /*
6711da177e4SLinus Torvalds  * Remove one
6721da177e4SLinus Torvalds  */
6738e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
6741da177e4SLinus Torvalds {
67541ca668aSYang Shi 	if (!(shrinker->flags & SHRINKER_REGISTERED))
676bb422a73STetsuo Handa 		return;
67741ca668aSYang Shi 
6781da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
6791da177e4SLinus Torvalds 	list_del(&shrinker->list);
68041ca668aSYang Shi 	shrinker->flags &= ~SHRINKER_REGISTERED;
68141ca668aSYang Shi 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
68241ca668aSYang Shi 		unregister_memcg_shrinker(shrinker);
6831da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
68441ca668aSYang Shi 
685ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
686bb422a73STetsuo Handa 	shrinker->nr_deferred = NULL;
6871da177e4SLinus Torvalds }
6888e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
6891da177e4SLinus Torvalds 
6901da177e4SLinus Torvalds #define SHRINK_BATCH 128
6911d3d4437SGlauber Costa 
692cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
6939092c71bSJosef Bacik 				    struct shrinker *shrinker, int priority)
6941da177e4SLinus Torvalds {
69524f7c6b9SDave Chinner 	unsigned long freed = 0;
6961da177e4SLinus Torvalds 	unsigned long long delta;
697635697c6SKonstantin Khlebnikov 	long total_scan;
698d5bc5fd3SVladimir Davydov 	long freeable;
699acf92b48SDave Chinner 	long nr;
700acf92b48SDave Chinner 	long new_nr;
701e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
702e9299f50SDave Chinner 					  : SHRINK_BATCH;
7035f33a080SShaohua Li 	long scanned = 0, next_deferred;
7041da177e4SLinus Torvalds 
705d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
7069b996468SKirill Tkhai 	if (freeable == 0 || freeable == SHRINK_EMPTY)
7079b996468SKirill Tkhai 		return freeable;
708635697c6SKonstantin Khlebnikov 
709acf92b48SDave Chinner 	/*
710acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
711acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
712acf92b48SDave Chinner 	 * don't also do this scanning work.
713acf92b48SDave Chinner 	 */
71486750830SYang Shi 	nr = xchg_nr_deferred(shrinker, shrinkctl);
715acf92b48SDave Chinner 
7164b85afbdSJohannes Weiner 	if (shrinker->seeks) {
7179092c71bSJosef Bacik 		delta = freeable >> priority;
7189092c71bSJosef Bacik 		delta *= 4;
7199092c71bSJosef Bacik 		do_div(delta, shrinker->seeks);
7204b85afbdSJohannes Weiner 	} else {
7214b85afbdSJohannes Weiner 		/*
7224b85afbdSJohannes Weiner 		 * These objects don't require any IO to create. Trim
7234b85afbdSJohannes Weiner 		 * them aggressively under memory pressure to keep
7244b85afbdSJohannes Weiner 		 * them from causing refetches in the IO caches.
7254b85afbdSJohannes Weiner 		 */
7264b85afbdSJohannes Weiner 		delta = freeable / 2;
7274b85afbdSJohannes Weiner 	}
728172b06c3SRoman Gushchin 
72918bb473eSYang Shi 	total_scan = nr >> priority;
730acf92b48SDave Chinner 	total_scan += delta;
73118bb473eSYang Shi 	total_scan = min(total_scan, (2 * freeable));
7321da177e4SLinus Torvalds 
73324f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
7349092c71bSJosef Bacik 				   freeable, delta, total_scan, priority);
73509576073SDave Chinner 
7360b1fb40aSVladimir Davydov 	/*
7370b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
7380b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
7390b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
7400b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
7410b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
7420b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
7430b1fb40aSVladimir Davydov 	 * batch_size.
7440b1fb40aSVladimir Davydov 	 *
7450b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
7460b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
747d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
7480b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
7490b1fb40aSVladimir Davydov 	 * possible.
7500b1fb40aSVladimir Davydov 	 */
7510b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
752d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
75324f7c6b9SDave Chinner 		unsigned long ret;
7540b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
7551da177e4SLinus Torvalds 
7560b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
757d460acb5SChris Wilson 		shrinkctl->nr_scanned = nr_to_scan;
75824f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
75924f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
7601da177e4SLinus Torvalds 			break;
76124f7c6b9SDave Chinner 		freed += ret;
76224f7c6b9SDave Chinner 
763d460acb5SChris Wilson 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
764d460acb5SChris Wilson 		total_scan -= shrinkctl->nr_scanned;
765d460acb5SChris Wilson 		scanned += shrinkctl->nr_scanned;
7661da177e4SLinus Torvalds 
7671da177e4SLinus Torvalds 		cond_resched();
7681da177e4SLinus Torvalds 	}
7691da177e4SLinus Torvalds 
77018bb473eSYang Shi 	/*
77118bb473eSYang Shi 	 * The deferred work is increased by any new work (delta) that wasn't
77218bb473eSYang Shi 	 * done, decreased by old deferred work that was done now.
77318bb473eSYang Shi 	 *
77418bb473eSYang Shi 	 * And it is capped to two times of the freeable items.
77518bb473eSYang Shi 	 */
77618bb473eSYang Shi 	next_deferred = max_t(long, (nr + delta - scanned), 0);
77718bb473eSYang Shi 	next_deferred = min(next_deferred, (2 * freeable));
77818bb473eSYang Shi 
779acf92b48SDave Chinner 	/*
780acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
78186750830SYang Shi 	 * manner that handles concurrent updates.
782acf92b48SDave Chinner 	 */
78386750830SYang Shi 	new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
784acf92b48SDave Chinner 
7858efb4b59SYang Shi 	trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
7861d3d4437SGlauber Costa 	return freed;
7871d3d4437SGlauber Costa }
7881d3d4437SGlauber Costa 
7890a432dcbSYang Shi #ifdef CONFIG_MEMCG
790b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
791b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
792b0dedc49SKirill Tkhai {
793e4262c4fSYang Shi 	struct shrinker_info *info;
794b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
795b8e57efaSKirill Tkhai 	int i;
796b0dedc49SKirill Tkhai 
7970a432dcbSYang Shi 	if (!mem_cgroup_online(memcg))
798b0dedc49SKirill Tkhai 		return 0;
799b0dedc49SKirill Tkhai 
800b0dedc49SKirill Tkhai 	if (!down_read_trylock(&shrinker_rwsem))
801b0dedc49SKirill Tkhai 		return 0;
802b0dedc49SKirill Tkhai 
803468ab843SYang Shi 	info = shrinker_info_protected(memcg, nid);
804e4262c4fSYang Shi 	if (unlikely(!info))
805b0dedc49SKirill Tkhai 		goto unlock;
806b0dedc49SKirill Tkhai 
807e4262c4fSYang Shi 	for_each_set_bit(i, info->map, shrinker_nr_max) {
808b0dedc49SKirill Tkhai 		struct shrink_control sc = {
809b0dedc49SKirill Tkhai 			.gfp_mask = gfp_mask,
810b0dedc49SKirill Tkhai 			.nid = nid,
811b0dedc49SKirill Tkhai 			.memcg = memcg,
812b0dedc49SKirill Tkhai 		};
813b0dedc49SKirill Tkhai 		struct shrinker *shrinker;
814b0dedc49SKirill Tkhai 
815b0dedc49SKirill Tkhai 		shrinker = idr_find(&shrinker_idr, i);
81641ca668aSYang Shi 		if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
8177e010df5SKirill Tkhai 			if (!shrinker)
818e4262c4fSYang Shi 				clear_bit(i, info->map);
819b0dedc49SKirill Tkhai 			continue;
820b0dedc49SKirill Tkhai 		}
821b0dedc49SKirill Tkhai 
8220a432dcbSYang Shi 		/* Call non-slab shrinkers even though kmem is disabled */
8230a432dcbSYang Shi 		if (!memcg_kmem_enabled() &&
8240a432dcbSYang Shi 		    !(shrinker->flags & SHRINKER_NONSLAB))
8250a432dcbSYang Shi 			continue;
8260a432dcbSYang Shi 
827b0dedc49SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
828f90280d6SKirill Tkhai 		if (ret == SHRINK_EMPTY) {
829e4262c4fSYang Shi 			clear_bit(i, info->map);
830f90280d6SKirill Tkhai 			/*
831f90280d6SKirill Tkhai 			 * After the shrinker reported that it had no objects to
832f90280d6SKirill Tkhai 			 * free, but before we cleared the corresponding bit in
833f90280d6SKirill Tkhai 			 * the memcg shrinker map, a new object might have been
834f90280d6SKirill Tkhai 			 * added. To make sure, we have the bit set in this
835f90280d6SKirill Tkhai 			 * case, we invoke the shrinker one more time and reset
836f90280d6SKirill Tkhai 			 * the bit if it reports that it is not empty anymore.
837f90280d6SKirill Tkhai 			 * The memory barrier here pairs with the barrier in
8382bfd3637SYang Shi 			 * set_shrinker_bit():
839f90280d6SKirill Tkhai 			 *
840f90280d6SKirill Tkhai 			 * list_lru_add()     shrink_slab_memcg()
841f90280d6SKirill Tkhai 			 *   list_add_tail()    clear_bit()
842f90280d6SKirill Tkhai 			 *   <MB>               <MB>
843f90280d6SKirill Tkhai 			 *   set_bit()          do_shrink_slab()
844f90280d6SKirill Tkhai 			 */
845f90280d6SKirill Tkhai 			smp_mb__after_atomic();
846f90280d6SKirill Tkhai 			ret = do_shrink_slab(&sc, shrinker, priority);
8479b996468SKirill Tkhai 			if (ret == SHRINK_EMPTY)
8489b996468SKirill Tkhai 				ret = 0;
849f90280d6SKirill Tkhai 			else
8502bfd3637SYang Shi 				set_shrinker_bit(memcg, nid, i);
851f90280d6SKirill Tkhai 		}
852b0dedc49SKirill Tkhai 		freed += ret;
853b0dedc49SKirill Tkhai 
854b0dedc49SKirill Tkhai 		if (rwsem_is_contended(&shrinker_rwsem)) {
855b0dedc49SKirill Tkhai 			freed = freed ? : 1;
856b0dedc49SKirill Tkhai 			break;
857b0dedc49SKirill Tkhai 		}
858b0dedc49SKirill Tkhai 	}
859b0dedc49SKirill Tkhai unlock:
860b0dedc49SKirill Tkhai 	up_read(&shrinker_rwsem);
861b0dedc49SKirill Tkhai 	return freed;
862b0dedc49SKirill Tkhai }
8630a432dcbSYang Shi #else /* CONFIG_MEMCG */
864b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
865b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
866b0dedc49SKirill Tkhai {
867b0dedc49SKirill Tkhai 	return 0;
868b0dedc49SKirill Tkhai }
8690a432dcbSYang Shi #endif /* CONFIG_MEMCG */
870b0dedc49SKirill Tkhai 
8716b4f7799SJohannes Weiner /**
872cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
8736b4f7799SJohannes Weiner  * @gfp_mask: allocation context
8746b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
875cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
8769092c71bSJosef Bacik  * @priority: the reclaim priority
8771d3d4437SGlauber Costa  *
8786b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
8791d3d4437SGlauber Costa  *
8806b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
8816b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
8821d3d4437SGlauber Costa  *
883aeed1d32SVladimir Davydov  * @memcg specifies the memory cgroup to target. Unaware shrinkers
884aeed1d32SVladimir Davydov  * are called only if it is the root cgroup.
885cb731d6cSVladimir Davydov  *
8869092c71bSJosef Bacik  * @priority is sc->priority, we take the number of objects and >> by priority
8879092c71bSJosef Bacik  * in order to get the scan target.
8881d3d4437SGlauber Costa  *
8896b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
8901d3d4437SGlauber Costa  */
891cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
892cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
8939092c71bSJosef Bacik 				 int priority)
8941d3d4437SGlauber Costa {
895b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
8961d3d4437SGlauber Costa 	struct shrinker *shrinker;
8971d3d4437SGlauber Costa 
898fa1e512fSYang Shi 	/*
899fa1e512fSYang Shi 	 * The root memcg might be allocated even though memcg is disabled
900fa1e512fSYang Shi 	 * via "cgroup_disable=memory" boot parameter.  This could make
901fa1e512fSYang Shi 	 * mem_cgroup_is_root() return false, then just run memcg slab
902fa1e512fSYang Shi 	 * shrink, but skip global shrink.  This may result in premature
903fa1e512fSYang Shi 	 * oom.
904fa1e512fSYang Shi 	 */
905fa1e512fSYang Shi 	if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
906b0dedc49SKirill Tkhai 		return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
907cb731d6cSVladimir Davydov 
908e830c63aSTetsuo Handa 	if (!down_read_trylock(&shrinker_rwsem))
9091d3d4437SGlauber Costa 		goto out;
9101d3d4437SGlauber Costa 
9111d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
9126b4f7799SJohannes Weiner 		struct shrink_control sc = {
9136b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
9146b4f7799SJohannes Weiner 			.nid = nid,
915cb731d6cSVladimir Davydov 			.memcg = memcg,
9166b4f7799SJohannes Weiner 		};
9176b4f7799SJohannes Weiner 
9189b996468SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
9199b996468SKirill Tkhai 		if (ret == SHRINK_EMPTY)
9209b996468SKirill Tkhai 			ret = 0;
9219b996468SKirill Tkhai 		freed += ret;
922e496612cSMinchan Kim 		/*
923e496612cSMinchan Kim 		 * Bail out if someone want to register a new shrinker to
92455b65a57SEthon Paul 		 * prevent the registration from being stalled for long periods
925e496612cSMinchan Kim 		 * by parallel ongoing shrinking.
926e496612cSMinchan Kim 		 */
927e496612cSMinchan Kim 		if (rwsem_is_contended(&shrinker_rwsem)) {
928e496612cSMinchan Kim 			freed = freed ? : 1;
929e496612cSMinchan Kim 			break;
930e496612cSMinchan Kim 		}
931ec97097bSVladimir Davydov 	}
9321d3d4437SGlauber Costa 
9331da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
934f06590bdSMinchan Kim out:
935f06590bdSMinchan Kim 	cond_resched();
93624f7c6b9SDave Chinner 	return freed;
9371da177e4SLinus Torvalds }
9381da177e4SLinus Torvalds 
939cb731d6cSVladimir Davydov void drop_slab_node(int nid)
940cb731d6cSVladimir Davydov {
941cb731d6cSVladimir Davydov 	unsigned long freed;
9421399af7eSVlastimil Babka 	int shift = 0;
943cb731d6cSVladimir Davydov 
944cb731d6cSVladimir Davydov 	do {
945cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
946cb731d6cSVladimir Davydov 
947069c411dSChunxin Zang 		if (fatal_signal_pending(current))
948069c411dSChunxin Zang 			return;
949069c411dSChunxin Zang 
950cb731d6cSVladimir Davydov 		freed = 0;
951aeed1d32SVladimir Davydov 		memcg = mem_cgroup_iter(NULL, NULL, NULL);
952cb731d6cSVladimir Davydov 		do {
9539092c71bSJosef Bacik 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
954cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
9551399af7eSVlastimil Babka 	} while ((freed >> shift++) > 1);
956cb731d6cSVladimir Davydov }
957cb731d6cSVladimir Davydov 
958cb731d6cSVladimir Davydov void drop_slab(void)
959cb731d6cSVladimir Davydov {
960cb731d6cSVladimir Davydov 	int nid;
961cb731d6cSVladimir Davydov 
962cb731d6cSVladimir Davydov 	for_each_online_node(nid)
963cb731d6cSVladimir Davydov 		drop_slab_node(nid);
964cb731d6cSVladimir Davydov }
965cb731d6cSVladimir Davydov 
9661da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
9671da177e4SLinus Torvalds {
968ceddc3a5SJohannes Weiner 	/*
969ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
97067891fffSMatthew Wilcox 	 * that isolated the page, the page cache and optional buffer
97167891fffSMatthew Wilcox 	 * heads at page->private.
972ceddc3a5SJohannes Weiner 	 */
9733efe62e4SMatthew Wilcox (Oracle) 	int page_cache_pins = thp_nr_pages(page);
97467891fffSMatthew Wilcox 	return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
9751da177e4SLinus Torvalds }
9761da177e4SLinus Torvalds 
977cb16556dSYang Shi static int may_write_to_inode(struct inode *inode)
9781da177e4SLinus Torvalds {
979930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
9801da177e4SLinus Torvalds 		return 1;
981703c2708STejun Heo 	if (!inode_write_congested(inode))
9821da177e4SLinus Torvalds 		return 1;
983703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
9841da177e4SLinus Torvalds 		return 1;
9851da177e4SLinus Torvalds 	return 0;
9861da177e4SLinus Torvalds }
9871da177e4SLinus Torvalds 
9881da177e4SLinus Torvalds /*
9891da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
9901da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
9911da177e4SLinus Torvalds  * fsync(), msync() or close().
9921da177e4SLinus Torvalds  *
9931da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
9941da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
9951da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
9961da177e4SLinus Torvalds  *
9971da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
9981da177e4SLinus Torvalds  * __GFP_FS.
9991da177e4SLinus Torvalds  */
10001da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
10011da177e4SLinus Torvalds 				struct page *page, int error)
10021da177e4SLinus Torvalds {
10037eaceaccSJens Axboe 	lock_page(page);
10043e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
10053e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
10061da177e4SLinus Torvalds 	unlock_page(page);
10071da177e4SLinus Torvalds }
10081da177e4SLinus Torvalds 
1009*c3f4a9a2SMel Gorman void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason)
10108cd7c588SMel Gorman {
10118cd7c588SMel Gorman 	wait_queue_head_t *wqh = &pgdat->reclaim_wait[reason];
1012*c3f4a9a2SMel Gorman 	long timeout, ret;
10138cd7c588SMel Gorman 	DEFINE_WAIT(wait);
10148cd7c588SMel Gorman 
10158cd7c588SMel Gorman 	/*
10168cd7c588SMel Gorman 	 * Do not throttle IO workers, kthreads other than kswapd or
10178cd7c588SMel Gorman 	 * workqueues. They may be required for reclaim to make
10188cd7c588SMel Gorman 	 * forward progress (e.g. journalling workqueues or kthreads).
10198cd7c588SMel Gorman 	 */
10208cd7c588SMel Gorman 	if (!current_is_kswapd() &&
10218cd7c588SMel Gorman 	    current->flags & (PF_IO_WORKER|PF_KTHREAD))
10228cd7c588SMel Gorman 		return;
10238cd7c588SMel Gorman 
1024*c3f4a9a2SMel Gorman 	/*
1025*c3f4a9a2SMel Gorman 	 * These figures are pulled out of thin air.
1026*c3f4a9a2SMel Gorman 	 * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many
1027*c3f4a9a2SMel Gorman 	 * parallel reclaimers which is a short-lived event so the timeout is
1028*c3f4a9a2SMel Gorman 	 * short. Failing to make progress or waiting on writeback are
1029*c3f4a9a2SMel Gorman 	 * potentially long-lived events so use a longer timeout. This is shaky
1030*c3f4a9a2SMel Gorman 	 * logic as a failure to make progress could be due to anything from
1031*c3f4a9a2SMel Gorman 	 * writeback to a slow device to excessive references pages at the tail
1032*c3f4a9a2SMel Gorman 	 * of the inactive LRU.
1033*c3f4a9a2SMel Gorman 	 */
1034*c3f4a9a2SMel Gorman 	switch(reason) {
1035*c3f4a9a2SMel Gorman 	case VMSCAN_THROTTLE_WRITEBACK:
1036*c3f4a9a2SMel Gorman 		timeout = HZ/10;
1037*c3f4a9a2SMel Gorman 
1038*c3f4a9a2SMel Gorman 		if (atomic_inc_return(&pgdat->nr_writeback_throttled) == 1) {
10398cd7c588SMel Gorman 			WRITE_ONCE(pgdat->nr_reclaim_start,
10408cd7c588SMel Gorman 				node_page_state(pgdat, NR_THROTTLED_WRITTEN));
10418cd7c588SMel Gorman 		}
10428cd7c588SMel Gorman 
1043*c3f4a9a2SMel Gorman 		break;
1044*c3f4a9a2SMel Gorman 	case VMSCAN_THROTTLE_NOPROGRESS:
1045*c3f4a9a2SMel Gorman 		timeout = HZ/10;
1046*c3f4a9a2SMel Gorman 		break;
1047*c3f4a9a2SMel Gorman 	case VMSCAN_THROTTLE_ISOLATED:
1048*c3f4a9a2SMel Gorman 		timeout = HZ/50;
1049*c3f4a9a2SMel Gorman 		break;
1050*c3f4a9a2SMel Gorman 	default:
1051*c3f4a9a2SMel Gorman 		WARN_ON_ONCE(1);
1052*c3f4a9a2SMel Gorman 		timeout = HZ;
1053*c3f4a9a2SMel Gorman 		break;
1054*c3f4a9a2SMel Gorman 	}
1055*c3f4a9a2SMel Gorman 
10568cd7c588SMel Gorman 	prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE);
10578cd7c588SMel Gorman 	ret = schedule_timeout(timeout);
10588cd7c588SMel Gorman 	finish_wait(wqh, &wait);
1059d818fca1SMel Gorman 
1060*c3f4a9a2SMel Gorman 	if (reason == VMSCAN_THROTTLE_WRITEBACK)
10618cd7c588SMel Gorman 		atomic_dec(&pgdat->nr_writeback_throttled);
10628cd7c588SMel Gorman 
10638cd7c588SMel Gorman 	trace_mm_vmscan_throttled(pgdat->node_id, jiffies_to_usecs(timeout),
10648cd7c588SMel Gorman 				jiffies_to_usecs(timeout - ret),
10658cd7c588SMel Gorman 				reason);
10668cd7c588SMel Gorman }
10678cd7c588SMel Gorman 
10688cd7c588SMel Gorman /*
10698cd7c588SMel Gorman  * Account for pages written if tasks are throttled waiting on dirty
10708cd7c588SMel Gorman  * pages to clean. If enough pages have been cleaned since throttling
10718cd7c588SMel Gorman  * started then wakeup the throttled tasks.
10728cd7c588SMel Gorman  */
10738cd7c588SMel Gorman void __acct_reclaim_writeback(pg_data_t *pgdat, struct page *page,
10748cd7c588SMel Gorman 							int nr_throttled)
10758cd7c588SMel Gorman {
10768cd7c588SMel Gorman 	unsigned long nr_written;
10778cd7c588SMel Gorman 
10788cd7c588SMel Gorman 	inc_node_page_state(page, NR_THROTTLED_WRITTEN);
10798cd7c588SMel Gorman 
10808cd7c588SMel Gorman 	/*
10818cd7c588SMel Gorman 	 * This is an inaccurate read as the per-cpu deltas may not
10828cd7c588SMel Gorman 	 * be synchronised. However, given that the system is
10838cd7c588SMel Gorman 	 * writeback throttled, it is not worth taking the penalty
10848cd7c588SMel Gorman 	 * of getting an accurate count. At worst, the throttle
10858cd7c588SMel Gorman 	 * timeout guarantees forward progress.
10868cd7c588SMel Gorman 	 */
10878cd7c588SMel Gorman 	nr_written = node_page_state(pgdat, NR_THROTTLED_WRITTEN) -
10888cd7c588SMel Gorman 		READ_ONCE(pgdat->nr_reclaim_start);
10898cd7c588SMel Gorman 
10908cd7c588SMel Gorman 	if (nr_written > SWAP_CLUSTER_MAX * nr_throttled)
10918cd7c588SMel Gorman 		wake_up(&pgdat->reclaim_wait[VMSCAN_THROTTLE_WRITEBACK]);
10928cd7c588SMel Gorman }
10938cd7c588SMel Gorman 
109404e62a29SChristoph Lameter /* possible outcome of pageout() */
109504e62a29SChristoph Lameter typedef enum {
109604e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
109704e62a29SChristoph Lameter 	PAGE_KEEP,
109804e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
109904e62a29SChristoph Lameter 	PAGE_ACTIVATE,
110004e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
110104e62a29SChristoph Lameter 	PAGE_SUCCESS,
110204e62a29SChristoph Lameter 	/* page is clean and locked */
110304e62a29SChristoph Lameter 	PAGE_CLEAN,
110404e62a29SChristoph Lameter } pageout_t;
110504e62a29SChristoph Lameter 
11061da177e4SLinus Torvalds /*
11071742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
11081742f19fSAndrew Morton  * Calls ->writepage().
11091da177e4SLinus Torvalds  */
1110cb16556dSYang Shi static pageout_t pageout(struct page *page, struct address_space *mapping)
11111da177e4SLinus Torvalds {
11121da177e4SLinus Torvalds 	/*
11131da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
11141da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
11151da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
11161da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
11171da177e4SLinus Torvalds 	 * PagePrivate for that.
11181da177e4SLinus Torvalds 	 *
11198174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
11201da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
11211da177e4SLinus Torvalds 	 * will block.
11221da177e4SLinus Torvalds 	 *
11231da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
11241da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
11251da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
11261da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
11271da177e4SLinus Torvalds 	 */
11281da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
11291da177e4SLinus Torvalds 		return PAGE_KEEP;
11301da177e4SLinus Torvalds 	if (!mapping) {
11311da177e4SLinus Torvalds 		/*
11321da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
11331da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
11341da177e4SLinus Torvalds 		 */
1135266cf658SDavid Howells 		if (page_has_private(page)) {
11361da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
11371da177e4SLinus Torvalds 				ClearPageDirty(page);
1138b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
11391da177e4SLinus Torvalds 				return PAGE_CLEAN;
11401da177e4SLinus Torvalds 			}
11411da177e4SLinus Torvalds 		}
11421da177e4SLinus Torvalds 		return PAGE_KEEP;
11431da177e4SLinus Torvalds 	}
11441da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
11451da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
1146cb16556dSYang Shi 	if (!may_write_to_inode(mapping->host))
11471da177e4SLinus Torvalds 		return PAGE_KEEP;
11481da177e4SLinus Torvalds 
11491da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
11501da177e4SLinus Torvalds 		int res;
11511da177e4SLinus Torvalds 		struct writeback_control wbc = {
11521da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
11531da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
1154111ebb6eSOGAWA Hirofumi 			.range_start = 0,
1155111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
11561da177e4SLinus Torvalds 			.for_reclaim = 1,
11571da177e4SLinus Torvalds 		};
11581da177e4SLinus Torvalds 
11591da177e4SLinus Torvalds 		SetPageReclaim(page);
11601da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
11611da177e4SLinus Torvalds 		if (res < 0)
11621da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
1163994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
11641da177e4SLinus Torvalds 			ClearPageReclaim(page);
11651da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
11661da177e4SLinus Torvalds 		}
1167c661b078SAndy Whitcroft 
11681da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
11691da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
11701da177e4SLinus Torvalds 			ClearPageReclaim(page);
11711da177e4SLinus Torvalds 		}
11723aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
1173c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
11741da177e4SLinus Torvalds 		return PAGE_SUCCESS;
11751da177e4SLinus Torvalds 	}
11761da177e4SLinus Torvalds 
11771da177e4SLinus Torvalds 	return PAGE_CLEAN;
11781da177e4SLinus Torvalds }
11791da177e4SLinus Torvalds 
1180a649fd92SAndrew Morton /*
1181e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
1182e286781dSNick Piggin  * gets returned with a refcount of 0.
1183a649fd92SAndrew Morton  */
1184a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
1185b910718aSJohannes Weiner 			    bool reclaimed, struct mem_cgroup *target_memcg)
118649d2e9ccSChristoph Lameter {
1187bd4c82c2SHuang Ying 	int refcount;
1188aae466b0SJoonsoo Kim 	void *shadow = NULL;
1189c4843a75SGreg Thelen 
119028e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
119128e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
119249d2e9ccSChristoph Lameter 
119330472509SJohannes Weiner 	xa_lock_irq(&mapping->i_pages);
119449d2e9ccSChristoph Lameter 	/*
11950fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
11960fd0e6b0SNick Piggin 	 *
11970fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
11980fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
11990fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
12000fd0e6b0SNick Piggin 	 * here, then the following race may occur:
12010fd0e6b0SNick Piggin 	 *
12020fd0e6b0SNick Piggin 	 * get_user_pages(&page);
12030fd0e6b0SNick Piggin 	 * [user mapping goes away]
12040fd0e6b0SNick Piggin 	 * write_to(page);
12050fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
12060fd0e6b0SNick Piggin 	 * SetPageDirty(page);
12070fd0e6b0SNick Piggin 	 * put_page(page);
12080fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
12090fd0e6b0SNick Piggin 	 *
12100fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
12110fd0e6b0SNick Piggin 	 *
12120fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
12130fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
12140139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
12150fd0e6b0SNick Piggin 	 *
12160fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
1217b93b0163SMatthew Wilcox 	 * and thus under the i_pages lock, then this ordering is not required.
121849d2e9ccSChristoph Lameter 	 */
1219906d278dSWilliam Kucharski 	refcount = 1 + compound_nr(page);
1220bd4c82c2SHuang Ying 	if (!page_ref_freeze(page, refcount))
122149d2e9ccSChristoph Lameter 		goto cannot_free;
12221c4c3b99SJiang Biao 	/* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
1223e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
1224bd4c82c2SHuang Ying 		page_ref_unfreeze(page, refcount);
122549d2e9ccSChristoph Lameter 		goto cannot_free;
1226e286781dSNick Piggin 	}
122749d2e9ccSChristoph Lameter 
122849d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
122949d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
12300a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
1231aae466b0SJoonsoo Kim 		if (reclaimed && !mapping_exiting(mapping))
1232aae466b0SJoonsoo Kim 			shadow = workingset_eviction(page, target_memcg);
1233aae466b0SJoonsoo Kim 		__delete_from_swap_cache(page, swap, shadow);
123430472509SJohannes Weiner 		xa_unlock_irq(&mapping->i_pages);
123575f6d6d2SMinchan Kim 		put_swap_page(page, swap);
1236e286781dSNick Piggin 	} else {
12376072d13cSLinus Torvalds 		void (*freepage)(struct page *);
12386072d13cSLinus Torvalds 
12396072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
1240a528910eSJohannes Weiner 		/*
1241a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
1242a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
1243a528910eSJohannes Weiner 		 *
1244a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
1245238c3046Sdylan-meiners 		 * already exiting.  This is not just an optimization,
1246a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
1247a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
1248a528910eSJohannes Weiner 		 * back.
1249f9fe48beSRoss Zwisler 		 *
1250f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
1251f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
1252f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
1253f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
1254b93b0163SMatthew Wilcox 		 * same address_space.
1255a528910eSJohannes Weiner 		 */
12569de4f22aSHuang Ying 		if (reclaimed && page_is_file_lru(page) &&
1257f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
1258b910718aSJohannes Weiner 			shadow = workingset_eviction(page, target_memcg);
125962cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
126030472509SJohannes Weiner 		xa_unlock_irq(&mapping->i_pages);
12616072d13cSLinus Torvalds 
12626072d13cSLinus Torvalds 		if (freepage != NULL)
12636072d13cSLinus Torvalds 			freepage(page);
1264e286781dSNick Piggin 	}
1265e286781dSNick Piggin 
126649d2e9ccSChristoph Lameter 	return 1;
126749d2e9ccSChristoph Lameter 
126849d2e9ccSChristoph Lameter cannot_free:
126930472509SJohannes Weiner 	xa_unlock_irq(&mapping->i_pages);
127049d2e9ccSChristoph Lameter 	return 0;
127149d2e9ccSChristoph Lameter }
127249d2e9ccSChristoph Lameter 
12731da177e4SLinus Torvalds /*
1274e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
1275e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
1276e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
1277e286781dSNick Piggin  * this page.
1278e286781dSNick Piggin  */
1279e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
1280e286781dSNick Piggin {
1281b910718aSJohannes Weiner 	if (__remove_mapping(mapping, page, false, NULL)) {
1282e286781dSNick Piggin 		/*
1283e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
1284e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
1285e286781dSNick Piggin 		 * atomic operation.
1286e286781dSNick Piggin 		 */
1287fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
1288e286781dSNick Piggin 		return 1;
1289e286781dSNick Piggin 	}
1290e286781dSNick Piggin 	return 0;
1291e286781dSNick Piggin }
1292e286781dSNick Piggin 
1293894bc310SLee Schermerhorn /**
1294894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
1295894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
1296894bc310SLee Schermerhorn  *
1297894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
1298894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
1299894bc310SLee Schermerhorn  *
1300894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
1301894bc310SLee Schermerhorn  */
1302894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
1303894bc310SLee Schermerhorn {
1304c53954a0SMel Gorman 	lru_cache_add(page);
1305894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
1306894bc310SLee Schermerhorn }
1307894bc310SLee Schermerhorn 
1308dfc8d636SJohannes Weiner enum page_references {
1309dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
1310dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
131164574746SJohannes Weiner 	PAGEREF_KEEP,
1312dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
1313dfc8d636SJohannes Weiner };
1314dfc8d636SJohannes Weiner 
1315dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
1316dfc8d636SJohannes Weiner 						  struct scan_control *sc)
1317dfc8d636SJohannes Weiner {
131864574746SJohannes Weiner 	int referenced_ptes, referenced_page;
1319dfc8d636SJohannes Weiner 	unsigned long vm_flags;
1320dfc8d636SJohannes Weiner 
1321c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1322c3ac9a8aSJohannes Weiner 					  &vm_flags);
132364574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
1324dfc8d636SJohannes Weiner 
1325dfc8d636SJohannes Weiner 	/*
1326dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
1327dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
1328dfc8d636SJohannes Weiner 	 */
1329dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
1330dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
1331dfc8d636SJohannes Weiner 
133264574746SJohannes Weiner 	if (referenced_ptes) {
133364574746SJohannes Weiner 		/*
133464574746SJohannes Weiner 		 * All mapped pages start out with page table
133564574746SJohannes Weiner 		 * references from the instantiating fault, so we need
133664574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
133764574746SJohannes Weiner 		 * than once.
133864574746SJohannes Weiner 		 *
133964574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
134064574746SJohannes Weiner 		 * inactive list.  Another page table reference will
134164574746SJohannes Weiner 		 * lead to its activation.
134264574746SJohannes Weiner 		 *
134364574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
134464574746SJohannes Weiner 		 * so that recently deactivated but used pages are
134564574746SJohannes Weiner 		 * quickly recovered.
134664574746SJohannes Weiner 		 */
134764574746SJohannes Weiner 		SetPageReferenced(page);
134864574746SJohannes Weiner 
134934dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
1350dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
1351dfc8d636SJohannes Weiner 
1352c909e993SKonstantin Khlebnikov 		/*
1353c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
1354c909e993SKonstantin Khlebnikov 		 */
1355b518154eSJoonsoo Kim 		if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
1356c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
1357c909e993SKonstantin Khlebnikov 
135864574746SJohannes Weiner 		return PAGEREF_KEEP;
135964574746SJohannes Weiner 	}
136064574746SJohannes Weiner 
1361dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
13622e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
1363dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
136464574746SJohannes Weiner 
136564574746SJohannes Weiner 	return PAGEREF_RECLAIM;
1366dfc8d636SJohannes Weiner }
1367dfc8d636SJohannes Weiner 
1368e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
1369e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
1370e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
1371e2be15f6SMel Gorman {
1372b4597226SMel Gorman 	struct address_space *mapping;
1373b4597226SMel Gorman 
1374e2be15f6SMel Gorman 	/*
1375e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
1376e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
1377e2be15f6SMel Gorman 	 */
13789de4f22aSHuang Ying 	if (!page_is_file_lru(page) ||
1379802a3a92SShaohua Li 	    (PageAnon(page) && !PageSwapBacked(page))) {
1380e2be15f6SMel Gorman 		*dirty = false;
1381e2be15f6SMel Gorman 		*writeback = false;
1382e2be15f6SMel Gorman 		return;
1383e2be15f6SMel Gorman 	}
1384e2be15f6SMel Gorman 
1385e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
1386e2be15f6SMel Gorman 	*dirty = PageDirty(page);
1387e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
1388b4597226SMel Gorman 
1389b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
1390b4597226SMel Gorman 	if (!page_has_private(page))
1391b4597226SMel Gorman 		return;
1392b4597226SMel Gorman 
1393b4597226SMel Gorman 	mapping = page_mapping(page);
1394b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
1395b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1396e2be15f6SMel Gorman }
1397e2be15f6SMel Gorman 
139826aa2d19SDave Hansen static struct page *alloc_demote_page(struct page *page, unsigned long node)
139926aa2d19SDave Hansen {
140026aa2d19SDave Hansen 	struct migration_target_control mtc = {
140126aa2d19SDave Hansen 		/*
140226aa2d19SDave Hansen 		 * Allocate from 'node', or fail quickly and quietly.
140326aa2d19SDave Hansen 		 * When this happens, 'page' will likely just be discarded
140426aa2d19SDave Hansen 		 * instead of migrated.
140526aa2d19SDave Hansen 		 */
140626aa2d19SDave Hansen 		.gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
140726aa2d19SDave Hansen 			    __GFP_THISNODE  | __GFP_NOWARN |
140826aa2d19SDave Hansen 			    __GFP_NOMEMALLOC | GFP_NOWAIT,
140926aa2d19SDave Hansen 		.nid = node
141026aa2d19SDave Hansen 	};
141126aa2d19SDave Hansen 
141226aa2d19SDave Hansen 	return alloc_migration_target(page, (unsigned long)&mtc);
141326aa2d19SDave Hansen }
141426aa2d19SDave Hansen 
141526aa2d19SDave Hansen /*
141626aa2d19SDave Hansen  * Take pages on @demote_list and attempt to demote them to
141726aa2d19SDave Hansen  * another node.  Pages which are not demoted are left on
141826aa2d19SDave Hansen  * @demote_pages.
141926aa2d19SDave Hansen  */
142026aa2d19SDave Hansen static unsigned int demote_page_list(struct list_head *demote_pages,
142126aa2d19SDave Hansen 				     struct pglist_data *pgdat)
142226aa2d19SDave Hansen {
142326aa2d19SDave Hansen 	int target_nid = next_demotion_node(pgdat->node_id);
142426aa2d19SDave Hansen 	unsigned int nr_succeeded;
142526aa2d19SDave Hansen 
142626aa2d19SDave Hansen 	if (list_empty(demote_pages))
142726aa2d19SDave Hansen 		return 0;
142826aa2d19SDave Hansen 
142926aa2d19SDave Hansen 	if (target_nid == NUMA_NO_NODE)
143026aa2d19SDave Hansen 		return 0;
143126aa2d19SDave Hansen 
143226aa2d19SDave Hansen 	/* Demotion ignores all cpuset and mempolicy settings */
1433cb75463cSKai Song 	migrate_pages(demote_pages, alloc_demote_page, NULL,
143426aa2d19SDave Hansen 			    target_nid, MIGRATE_ASYNC, MR_DEMOTION,
143526aa2d19SDave Hansen 			    &nr_succeeded);
143626aa2d19SDave Hansen 
1437668e4147SYang Shi 	if (current_is_kswapd())
1438668e4147SYang Shi 		__count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1439668e4147SYang Shi 	else
1440668e4147SYang Shi 		__count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1441668e4147SYang Shi 
144226aa2d19SDave Hansen 	return nr_succeeded;
144326aa2d19SDave Hansen }
144426aa2d19SDave Hansen 
1445e286781dSNick Piggin /*
14461742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
14471da177e4SLinus Torvalds  */
1448730ec8c0SManinder Singh static unsigned int shrink_page_list(struct list_head *page_list,
1449599d0c95SMel Gorman 				     struct pglist_data *pgdat,
1450f84f6e2bSMel Gorman 				     struct scan_control *sc,
14513c710c1aSMichal Hocko 				     struct reclaim_stat *stat,
14528940b34aSMinchan Kim 				     bool ignore_references)
14531da177e4SLinus Torvalds {
14541da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
1455abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
145626aa2d19SDave Hansen 	LIST_HEAD(demote_pages);
1457730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
1458730ec8c0SManinder Singh 	unsigned int pgactivate = 0;
145926aa2d19SDave Hansen 	bool do_demote_pass;
14601da177e4SLinus Torvalds 
1461060f005fSKirill Tkhai 	memset(stat, 0, sizeof(*stat));
14621da177e4SLinus Torvalds 	cond_resched();
146326aa2d19SDave Hansen 	do_demote_pass = can_demote(pgdat->node_id, sc);
14641da177e4SLinus Torvalds 
146526aa2d19SDave Hansen retry:
14661da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
14671da177e4SLinus Torvalds 		struct address_space *mapping;
14681da177e4SLinus Torvalds 		struct page *page;
14698940b34aSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM;
14704b793062SKirill Tkhai 		bool dirty, writeback, may_enter_fs;
147198879b3bSYang Shi 		unsigned int nr_pages;
14721da177e4SLinus Torvalds 
14731da177e4SLinus Torvalds 		cond_resched();
14741da177e4SLinus Torvalds 
14751da177e4SLinus Torvalds 		page = lru_to_page(page_list);
14761da177e4SLinus Torvalds 		list_del(&page->lru);
14771da177e4SLinus Torvalds 
1478529ae9aaSNick Piggin 		if (!trylock_page(page))
14791da177e4SLinus Torvalds 			goto keep;
14801da177e4SLinus Torvalds 
1481309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
14821da177e4SLinus Torvalds 
1483d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
148498879b3bSYang Shi 
148598879b3bSYang Shi 		/* Account the number of base pages even though THP */
148698879b3bSYang Shi 		sc->nr_scanned += nr_pages;
148780e43426SChristoph Lameter 
148839b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
1489ad6b6704SMinchan Kim 			goto activate_locked;
1490894bc310SLee Schermerhorn 
1491a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
149280e43426SChristoph Lameter 			goto keep_locked;
149380e43426SChristoph Lameter 
1494c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1495c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1496c661b078SAndy Whitcroft 
1497e62e384eSMichal Hocko 		/*
1498894befecSAndrey Ryabinin 		 * The number of dirty pages determines if a node is marked
14998cd7c588SMel Gorman 		 * reclaim_congested. kswapd will stall and start writing
15008cd7c588SMel Gorman 		 * pages if the tail of the LRU is all dirty unqueued pages.
1501e2be15f6SMel Gorman 		 */
1502e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
1503e2be15f6SMel Gorman 		if (dirty || writeback)
1504060f005fSKirill Tkhai 			stat->nr_dirty++;
1505e2be15f6SMel Gorman 
1506e2be15f6SMel Gorman 		if (dirty && !writeback)
1507060f005fSKirill Tkhai 			stat->nr_unqueued_dirty++;
1508e2be15f6SMel Gorman 
1509d04e8acdSMel Gorman 		/*
1510d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
1511d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
1512d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
1513d04e8acdSMel Gorman 		 * end of the LRU a second time.
1514d04e8acdSMel Gorman 		 */
1515e2be15f6SMel Gorman 		mapping = page_mapping(page);
15161da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
1517703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
1518d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
1519060f005fSKirill Tkhai 			stat->nr_congested++;
1520e2be15f6SMel Gorman 
1521e2be15f6SMel Gorman 		/*
1522283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
1523283aba9fSMel Gorman 		 * are three cases to consider.
1524e62e384eSMichal Hocko 		 *
1525283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
1526283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
1527283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
1528283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
1529283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
1530283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
1531283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
1532b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
1533b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
1534c3b94f44SHugh Dickins 		 *
153597c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
1536ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1537ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1538ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
153997c9341fSTejun Heo 		 *    reclaim and continue scanning.
1540283aba9fSMel Gorman 		 *
1541ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1542ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1543283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1544283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1545283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1546283aba9fSMel Gorman 		 *    would probably show more reasons.
1547283aba9fSMel Gorman 		 *
15487fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1549283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1550283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1551283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1552283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1553c55e8d03SJohannes Weiner 		 *
1554c55e8d03SJohannes Weiner 		 * In cases 1) and 2) we activate the pages to get them out of
1555c55e8d03SJohannes Weiner 		 * the way while we continue scanning for clean pages on the
1556c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1557c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1558c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1559c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1560c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1561c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1562e62e384eSMichal Hocko 		 */
1563283aba9fSMel Gorman 		if (PageWriteback(page)) {
1564283aba9fSMel Gorman 			/* Case 1 above */
1565283aba9fSMel Gorman 			if (current_is_kswapd() &&
1566283aba9fSMel Gorman 			    PageReclaim(page) &&
1567599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1568060f005fSKirill Tkhai 				stat->nr_immediate++;
1569c55e8d03SJohannes Weiner 				goto activate_locked;
1570283aba9fSMel Gorman 
1571283aba9fSMel Gorman 			/* Case 2 above */
1572b5ead35eSJohannes Weiner 			} else if (writeback_throttling_sane(sc) ||
1573ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1574c3b94f44SHugh Dickins 				/*
1575c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1576c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1577c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1578c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1579c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1580c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1581c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1582c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1583c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1584c3b94f44SHugh Dickins 				 */
1585c3b94f44SHugh Dickins 				SetPageReclaim(page);
1586060f005fSKirill Tkhai 				stat->nr_writeback++;
1587c55e8d03SJohannes Weiner 				goto activate_locked;
1588283aba9fSMel Gorman 
1589283aba9fSMel Gorman 			/* Case 3 above */
1590283aba9fSMel Gorman 			} else {
15917fadc820SHugh Dickins 				unlock_page(page);
1592c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
15937fadc820SHugh Dickins 				/* then go back and try same page again */
15947fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
15957fadc820SHugh Dickins 				continue;
1596e62e384eSMichal Hocko 			}
1597283aba9fSMel Gorman 		}
15981da177e4SLinus Torvalds 
15998940b34aSMinchan Kim 		if (!ignore_references)
16006a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
160102c6de8dSMinchan Kim 
1602dfc8d636SJohannes Weiner 		switch (references) {
1603dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
16041da177e4SLinus Torvalds 			goto activate_locked;
160564574746SJohannes Weiner 		case PAGEREF_KEEP:
160698879b3bSYang Shi 			stat->nr_ref_keep += nr_pages;
160764574746SJohannes Weiner 			goto keep_locked;
1608dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1609dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1610dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1611dfc8d636SJohannes Weiner 		}
16121da177e4SLinus Torvalds 
16131da177e4SLinus Torvalds 		/*
161426aa2d19SDave Hansen 		 * Before reclaiming the page, try to relocate
161526aa2d19SDave Hansen 		 * its contents to another node.
161626aa2d19SDave Hansen 		 */
161726aa2d19SDave Hansen 		if (do_demote_pass &&
161826aa2d19SDave Hansen 		    (thp_migration_supported() || !PageTransHuge(page))) {
161926aa2d19SDave Hansen 			list_add(&page->lru, &demote_pages);
162026aa2d19SDave Hansen 			unlock_page(page);
162126aa2d19SDave Hansen 			continue;
162226aa2d19SDave Hansen 		}
162326aa2d19SDave Hansen 
162426aa2d19SDave Hansen 		/*
16251da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
16261da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1627802a3a92SShaohua Li 		 * Lazyfree page could be freed directly
16281da177e4SLinus Torvalds 		 */
1629bd4c82c2SHuang Ying 		if (PageAnon(page) && PageSwapBacked(page)) {
1630bd4c82c2SHuang Ying 			if (!PageSwapCache(page)) {
163163eb6b93SHugh Dickins 				if (!(sc->gfp_mask & __GFP_IO))
163263eb6b93SHugh Dickins 					goto keep_locked;
1633feb889fbSLinus Torvalds 				if (page_maybe_dma_pinned(page))
1634feb889fbSLinus Torvalds 					goto keep_locked;
1635747552b1SHuang Ying 				if (PageTransHuge(page)) {
1636b8f593cdSHuang Ying 					/* cannot split THP, skip it */
1637747552b1SHuang Ying 					if (!can_split_huge_page(page, NULL))
1638b8f593cdSHuang Ying 						goto activate_locked;
1639747552b1SHuang Ying 					/*
1640747552b1SHuang Ying 					 * Split pages without a PMD map right
1641747552b1SHuang Ying 					 * away. Chances are some or all of the
1642747552b1SHuang Ying 					 * tail pages can be freed without IO.
1643747552b1SHuang Ying 					 */
1644747552b1SHuang Ying 					if (!compound_mapcount(page) &&
1645bd4c82c2SHuang Ying 					    split_huge_page_to_list(page,
1646bd4c82c2SHuang Ying 								    page_list))
1647747552b1SHuang Ying 						goto activate_locked;
1648747552b1SHuang Ying 				}
16490f074658SMinchan Kim 				if (!add_to_swap(page)) {
16500f074658SMinchan Kim 					if (!PageTransHuge(page))
165198879b3bSYang Shi 						goto activate_locked_split;
1652bd4c82c2SHuang Ying 					/* Fallback to swap normal pages */
1653bd4c82c2SHuang Ying 					if (split_huge_page_to_list(page,
1654bd4c82c2SHuang Ying 								    page_list))
16550f074658SMinchan Kim 						goto activate_locked;
1656fe490cc0SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1657fe490cc0SHuang Ying 					count_vm_event(THP_SWPOUT_FALLBACK);
1658fe490cc0SHuang Ying #endif
16590f074658SMinchan Kim 					if (!add_to_swap(page))
166098879b3bSYang Shi 						goto activate_locked_split;
16610f074658SMinchan Kim 				}
16620f074658SMinchan Kim 
16634b793062SKirill Tkhai 				may_enter_fs = true;
16641da177e4SLinus Torvalds 
1665e2be15f6SMel Gorman 				/* Adding to swap updated mapping */
16661da177e4SLinus Torvalds 				mapping = page_mapping(page);
1667bd4c82c2SHuang Ying 			}
16687751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
16697751b2daSKirill A. Shutemov 			/* Split file THP */
16707751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
16717751b2daSKirill A. Shutemov 				goto keep_locked;
1672e2be15f6SMel Gorman 		}
16731da177e4SLinus Torvalds 
16741da177e4SLinus Torvalds 		/*
167598879b3bSYang Shi 		 * THP may get split above, need minus tail pages and update
167698879b3bSYang Shi 		 * nr_pages to avoid accounting tail pages twice.
167798879b3bSYang Shi 		 *
167898879b3bSYang Shi 		 * The tail pages that are added into swap cache successfully
167998879b3bSYang Shi 		 * reach here.
168098879b3bSYang Shi 		 */
168198879b3bSYang Shi 		if ((nr_pages > 1) && !PageTransHuge(page)) {
168298879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
168398879b3bSYang Shi 			nr_pages = 1;
168498879b3bSYang Shi 		}
168598879b3bSYang Shi 
168698879b3bSYang Shi 		/*
16871da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
16881da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
16891da177e4SLinus Torvalds 		 */
1690802a3a92SShaohua Li 		if (page_mapped(page)) {
1691013339dfSShakeel Butt 			enum ttu_flags flags = TTU_BATCH_FLUSH;
16921f318a9bSJaewon Kim 			bool was_swapbacked = PageSwapBacked(page);
1693bd4c82c2SHuang Ying 
1694bd4c82c2SHuang Ying 			if (unlikely(PageTransHuge(page)))
1695bd4c82c2SHuang Ying 				flags |= TTU_SPLIT_HUGE_PMD;
16961f318a9bSJaewon Kim 
16971fb08ac6SYang Shi 			try_to_unmap(page, flags);
16981fb08ac6SYang Shi 			if (page_mapped(page)) {
169998879b3bSYang Shi 				stat->nr_unmap_fail += nr_pages;
17001f318a9bSJaewon Kim 				if (!was_swapbacked && PageSwapBacked(page))
17011f318a9bSJaewon Kim 					stat->nr_lazyfree_fail += nr_pages;
17021da177e4SLinus Torvalds 				goto activate_locked;
17031da177e4SLinus Torvalds 			}
17041da177e4SLinus Torvalds 		}
17051da177e4SLinus Torvalds 
17061da177e4SLinus Torvalds 		if (PageDirty(page)) {
1707ee72886dSMel Gorman 			/*
17084eda4823SJohannes Weiner 			 * Only kswapd can writeback filesystem pages
17094eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
17104eda4823SJohannes Weiner 			 * injecting inefficient single-page IO into
17114eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
17124eda4823SJohannes Weiner 			 * write pages when we've encountered many
17134eda4823SJohannes Weiner 			 * dirty pages, and when we've already scanned
17144eda4823SJohannes Weiner 			 * the rest of the LRU for clean pages and see
17154eda4823SJohannes Weiner 			 * the same dirty pages again (PageReclaim).
1716ee72886dSMel Gorman 			 */
17179de4f22aSHuang Ying 			if (page_is_file_lru(page) &&
17184eda4823SJohannes Weiner 			    (!current_is_kswapd() || !PageReclaim(page) ||
1719599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
172049ea7eb6SMel Gorman 				/*
172149ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
172249ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
172349ea7eb6SMel Gorman 				 * except we already have the page isolated
172449ea7eb6SMel Gorman 				 * and know it's dirty
172549ea7eb6SMel Gorman 				 */
1726c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
172749ea7eb6SMel Gorman 				SetPageReclaim(page);
172849ea7eb6SMel Gorman 
1729c55e8d03SJohannes Weiner 				goto activate_locked;
1730ee72886dSMel Gorman 			}
1731ee72886dSMel Gorman 
1732dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
17331da177e4SLinus Torvalds 				goto keep_locked;
17344dd4b920SAndrew Morton 			if (!may_enter_fs)
17351da177e4SLinus Torvalds 				goto keep_locked;
173652a8363eSChristoph Lameter 			if (!sc->may_writepage)
17371da177e4SLinus Torvalds 				goto keep_locked;
17381da177e4SLinus Torvalds 
1739d950c947SMel Gorman 			/*
1740d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1741d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1742d950c947SMel Gorman 			 * starts and then write it out here.
1743d950c947SMel Gorman 			 */
1744d950c947SMel Gorman 			try_to_unmap_flush_dirty();
1745cb16556dSYang Shi 			switch (pageout(page, mapping)) {
17461da177e4SLinus Torvalds 			case PAGE_KEEP:
17471da177e4SLinus Torvalds 				goto keep_locked;
17481da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
17491da177e4SLinus Torvalds 				goto activate_locked;
17501da177e4SLinus Torvalds 			case PAGE_SUCCESS:
17516c357848SMatthew Wilcox (Oracle) 				stat->nr_pageout += thp_nr_pages(page);
175296f8bf4fSJohannes Weiner 
17537d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
175441ac1999SMel Gorman 					goto keep;
17557d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
17561da177e4SLinus Torvalds 					goto keep;
17577d3579e8SKOSAKI Motohiro 
17581da177e4SLinus Torvalds 				/*
17591da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
17601da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
17611da177e4SLinus Torvalds 				 */
1762529ae9aaSNick Piggin 				if (!trylock_page(page))
17631da177e4SLinus Torvalds 					goto keep;
17641da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
17651da177e4SLinus Torvalds 					goto keep_locked;
17661da177e4SLinus Torvalds 				mapping = page_mapping(page);
176701359eb2SGustavo A. R. Silva 				fallthrough;
17681da177e4SLinus Torvalds 			case PAGE_CLEAN:
17691da177e4SLinus Torvalds 				; /* try to free the page below */
17701da177e4SLinus Torvalds 			}
17711da177e4SLinus Torvalds 		}
17721da177e4SLinus Torvalds 
17731da177e4SLinus Torvalds 		/*
17741da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
17751da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
17761da177e4SLinus Torvalds 		 * the page as well.
17771da177e4SLinus Torvalds 		 *
17781da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
17791da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
17801da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
17811da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
17821da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
17831da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
17841da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
17851da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
17861da177e4SLinus Torvalds 		 *
17871da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
17881da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
1789d12b8951SYang Shi 		 * truncate_cleanup_page().  We try to drop those buffers here
17901da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
17911da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
17921da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
17931da177e4SLinus Torvalds 		 */
1794266cf658SDavid Howells 		if (page_has_private(page)) {
17951da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
17961da177e4SLinus Torvalds 				goto activate_locked;
1797e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1798e286781dSNick Piggin 				unlock_page(page);
1799e286781dSNick Piggin 				if (put_page_testzero(page))
18001da177e4SLinus Torvalds 					goto free_it;
1801e286781dSNick Piggin 				else {
1802e286781dSNick Piggin 					/*
1803e286781dSNick Piggin 					 * rare race with speculative reference.
1804e286781dSNick Piggin 					 * the speculative reference will free
1805e286781dSNick Piggin 					 * this page shortly, so we may
1806e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1807e286781dSNick Piggin 					 * leave it off the LRU).
1808e286781dSNick Piggin 					 */
1809e286781dSNick Piggin 					nr_reclaimed++;
1810e286781dSNick Piggin 					continue;
1811e286781dSNick Piggin 				}
1812e286781dSNick Piggin 			}
18131da177e4SLinus Torvalds 		}
18141da177e4SLinus Torvalds 
1815802a3a92SShaohua Li 		if (PageAnon(page) && !PageSwapBacked(page)) {
1816802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
1817802a3a92SShaohua Li 			if (!page_ref_freeze(page, 1))
181849d2e9ccSChristoph Lameter 				goto keep_locked;
1819d17be2d9SMiaohe Lin 			/*
1820d17be2d9SMiaohe Lin 			 * The page has only one reference left, which is
1821d17be2d9SMiaohe Lin 			 * from the isolation. After the caller puts the
1822d17be2d9SMiaohe Lin 			 * page back on lru and drops the reference, the
1823d17be2d9SMiaohe Lin 			 * page will be freed anyway. It doesn't matter
1824d17be2d9SMiaohe Lin 			 * which lru it goes. So we don't bother checking
1825d17be2d9SMiaohe Lin 			 * PageDirty here.
1826d17be2d9SMiaohe Lin 			 */
1827802a3a92SShaohua Li 			count_vm_event(PGLAZYFREED);
18282262185cSRoman Gushchin 			count_memcg_page_event(page, PGLAZYFREED);
1829b910718aSJohannes Weiner 		} else if (!mapping || !__remove_mapping(mapping, page, true,
1830b910718aSJohannes Weiner 							 sc->target_mem_cgroup))
1831802a3a92SShaohua Li 			goto keep_locked;
18329a1ea439SHugh Dickins 
18339a1ea439SHugh Dickins 		unlock_page(page);
1834e286781dSNick Piggin free_it:
183598879b3bSYang Shi 		/*
183698879b3bSYang Shi 		 * THP may get swapped out in a whole, need account
183798879b3bSYang Shi 		 * all base pages.
183898879b3bSYang Shi 		 */
183998879b3bSYang Shi 		nr_reclaimed += nr_pages;
1840abe4c3b5SMel Gorman 
1841abe4c3b5SMel Gorman 		/*
1842abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1843abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1844abe4c3b5SMel Gorman 		 */
18457ae88534SYang Shi 		if (unlikely(PageTransHuge(page)))
1846ff45fc3cSMatthew Wilcox (Oracle) 			destroy_compound_page(page);
18477ae88534SYang Shi 		else
1848abe4c3b5SMel Gorman 			list_add(&page->lru, &free_pages);
18491da177e4SLinus Torvalds 		continue;
18501da177e4SLinus Torvalds 
185198879b3bSYang Shi activate_locked_split:
185298879b3bSYang Shi 		/*
185398879b3bSYang Shi 		 * The tail pages that are failed to add into swap cache
185498879b3bSYang Shi 		 * reach here.  Fixup nr_scanned and nr_pages.
185598879b3bSYang Shi 		 */
185698879b3bSYang Shi 		if (nr_pages > 1) {
185798879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
185898879b3bSYang Shi 			nr_pages = 1;
185998879b3bSYang Shi 		}
18601da177e4SLinus Torvalds activate_locked:
186168a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
1862ad6b6704SMinchan Kim 		if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1863ad6b6704SMinchan Kim 						PageMlocked(page)))
1864a2c43eedSHugh Dickins 			try_to_free_swap(page);
1865309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
1866ad6b6704SMinchan Kim 		if (!PageMlocked(page)) {
18679de4f22aSHuang Ying 			int type = page_is_file_lru(page);
18681da177e4SLinus Torvalds 			SetPageActive(page);
186998879b3bSYang Shi 			stat->nr_activate[type] += nr_pages;
18702262185cSRoman Gushchin 			count_memcg_page_event(page, PGACTIVATE);
1871ad6b6704SMinchan Kim 		}
18721da177e4SLinus Torvalds keep_locked:
18731da177e4SLinus Torvalds 		unlock_page(page);
18741da177e4SLinus Torvalds keep:
18751da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1876309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
18771da177e4SLinus Torvalds 	}
187826aa2d19SDave Hansen 	/* 'page_list' is always empty here */
187926aa2d19SDave Hansen 
188026aa2d19SDave Hansen 	/* Migrate pages selected for demotion */
188126aa2d19SDave Hansen 	nr_reclaimed += demote_page_list(&demote_pages, pgdat);
188226aa2d19SDave Hansen 	/* Pages that could not be demoted are still in @demote_pages */
188326aa2d19SDave Hansen 	if (!list_empty(&demote_pages)) {
188426aa2d19SDave Hansen 		/* Pages which failed to demoted go back on @page_list for retry: */
188526aa2d19SDave Hansen 		list_splice_init(&demote_pages, page_list);
188626aa2d19SDave Hansen 		do_demote_pass = false;
188726aa2d19SDave Hansen 		goto retry;
188826aa2d19SDave Hansen 	}
1889abe4c3b5SMel Gorman 
189098879b3bSYang Shi 	pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
189198879b3bSYang Shi 
1892747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
189372b252aeSMel Gorman 	try_to_unmap_flush();
18942d4894b5SMel Gorman 	free_unref_page_list(&free_pages);
1895abe4c3b5SMel Gorman 
18961da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1897886cf190SKirill Tkhai 	count_vm_events(PGACTIVATE, pgactivate);
18980a31bc97SJohannes Weiner 
189905ff5137SAndrew Morton 	return nr_reclaimed;
19001da177e4SLinus Torvalds }
19011da177e4SLinus Torvalds 
1902730ec8c0SManinder Singh unsigned int reclaim_clean_pages_from_list(struct zone *zone,
190302c6de8dSMinchan Kim 					    struct list_head *page_list)
190402c6de8dSMinchan Kim {
190502c6de8dSMinchan Kim 	struct scan_control sc = {
190602c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
190702c6de8dSMinchan Kim 		.may_unmap = 1,
190802c6de8dSMinchan Kim 	};
19091f318a9bSJaewon Kim 	struct reclaim_stat stat;
1910730ec8c0SManinder Singh 	unsigned int nr_reclaimed;
191102c6de8dSMinchan Kim 	struct page *page, *next;
191202c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
19132d2b8d2bSYu Zhao 	unsigned int noreclaim_flag;
191402c6de8dSMinchan Kim 
191502c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1916ae37c7ffSOscar Salvador 		if (!PageHuge(page) && page_is_file_lru(page) &&
1917ae37c7ffSOscar Salvador 		    !PageDirty(page) && !__PageMovable(page) &&
1918ae37c7ffSOscar Salvador 		    !PageUnevictable(page)) {
191902c6de8dSMinchan Kim 			ClearPageActive(page);
192002c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
192102c6de8dSMinchan Kim 		}
192202c6de8dSMinchan Kim 	}
192302c6de8dSMinchan Kim 
19242d2b8d2bSYu Zhao 	/*
19252d2b8d2bSYu Zhao 	 * We should be safe here since we are only dealing with file pages and
19262d2b8d2bSYu Zhao 	 * we are not kswapd and therefore cannot write dirty file pages. But
19272d2b8d2bSYu Zhao 	 * call memalloc_noreclaim_save() anyway, just in case these conditions
19282d2b8d2bSYu Zhao 	 * change in the future.
19292d2b8d2bSYu Zhao 	 */
19302d2b8d2bSYu Zhao 	noreclaim_flag = memalloc_noreclaim_save();
19311f318a9bSJaewon Kim 	nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1932013339dfSShakeel Butt 					&stat, true);
19332d2b8d2bSYu Zhao 	memalloc_noreclaim_restore(noreclaim_flag);
19342d2b8d2bSYu Zhao 
193502c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
19362da9f630SNicholas Piggin 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
19372da9f630SNicholas Piggin 			    -(long)nr_reclaimed);
19381f318a9bSJaewon Kim 	/*
19391f318a9bSJaewon Kim 	 * Since lazyfree pages are isolated from file LRU from the beginning,
19401f318a9bSJaewon Kim 	 * they will rotate back to anonymous LRU in the end if it failed to
19411f318a9bSJaewon Kim 	 * discard so isolated count will be mismatched.
19421f318a9bSJaewon Kim 	 * Compensate the isolated count for both LRU lists.
19431f318a9bSJaewon Kim 	 */
19441f318a9bSJaewon Kim 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
19451f318a9bSJaewon Kim 			    stat.nr_lazyfree_fail);
19461f318a9bSJaewon Kim 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
19472da9f630SNicholas Piggin 			    -(long)stat.nr_lazyfree_fail);
19481f318a9bSJaewon Kim 	return nr_reclaimed;
194902c6de8dSMinchan Kim }
195002c6de8dSMinchan Kim 
19515ad333ebSAndy Whitcroft /*
19525ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
19535ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
19545ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
19555ad333ebSAndy Whitcroft  *
19565ad333ebSAndy Whitcroft  * page:	page to consider
19575ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
19585ad333ebSAndy Whitcroft  *
1959c2135f7cSAlex Shi  * returns true on success, false on failure.
19605ad333ebSAndy Whitcroft  */
1961c2135f7cSAlex Shi bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
19625ad333ebSAndy Whitcroft {
19635ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
19645ad333ebSAndy Whitcroft 	if (!PageLRU(page))
1965c2135f7cSAlex Shi 		return false;
19665ad333ebSAndy Whitcroft 
1967e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1968e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1969c2135f7cSAlex Shi 		return false;
1970894bc310SLee Schermerhorn 
1971c8244935SMel Gorman 	/*
1972c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1973c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1974c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1975c8244935SMel Gorman 	 *
1976c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1977c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1978c8244935SMel Gorman 	 */
19791276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1980c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1981c8244935SMel Gorman 		if (PageWriteback(page))
1982c2135f7cSAlex Shi 			return false;
198339deaf85SMinchan Kim 
1984c8244935SMel Gorman 		if (PageDirty(page)) {
1985c8244935SMel Gorman 			struct address_space *mapping;
198669d763fcSMel Gorman 			bool migrate_dirty;
1987c8244935SMel Gorman 
1988c8244935SMel Gorman 			/*
1989c8244935SMel Gorman 			 * Only pages without mappings or that have a
1990c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
199169d763fcSMel Gorman 			 * without blocking. However, we can be racing with
199269d763fcSMel Gorman 			 * truncation so it's necessary to lock the page
199369d763fcSMel Gorman 			 * to stabilise the mapping as truncation holds
199469d763fcSMel Gorman 			 * the page lock until after the page is removed
199569d763fcSMel Gorman 			 * from the page cache.
1996c8244935SMel Gorman 			 */
199769d763fcSMel Gorman 			if (!trylock_page(page))
1998c2135f7cSAlex Shi 				return false;
199969d763fcSMel Gorman 
2000c8244935SMel Gorman 			mapping = page_mapping(page);
2001145e1a71SHugh Dickins 			migrate_dirty = !mapping || mapping->a_ops->migratepage;
200269d763fcSMel Gorman 			unlock_page(page);
200369d763fcSMel Gorman 			if (!migrate_dirty)
2004c2135f7cSAlex Shi 				return false;
2005c8244935SMel Gorman 		}
2006c8244935SMel Gorman 	}
2007c8244935SMel Gorman 
2008f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
2009c2135f7cSAlex Shi 		return false;
2010f80c0673SMinchan Kim 
2011c2135f7cSAlex Shi 	return true;
20125ad333ebSAndy Whitcroft }
20135ad333ebSAndy Whitcroft 
20147ee36a14SMel Gorman /*
20157ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
201655b65a57SEthon Paul  * be complete before mem_cgroup_update_lru_size due to a sanity check.
20177ee36a14SMel Gorman  */
20187ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
2019b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
20207ee36a14SMel Gorman {
20217ee36a14SMel Gorman 	int zid;
20227ee36a14SMel Gorman 
20237ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
20247ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
20257ee36a14SMel Gorman 			continue;
20267ee36a14SMel Gorman 
2027a892cb6bSWei Yang 		update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
20287ee36a14SMel Gorman 	}
20297ee36a14SMel Gorman 
20307ee36a14SMel Gorman }
20317ee36a14SMel Gorman 
2032f611fab7SMel Gorman /*
203315b44736SHugh Dickins  * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
203415b44736SHugh Dickins  *
203515b44736SHugh Dickins  * lruvec->lru_lock is heavily contended.  Some of the functions that
20361da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
20371da177e4SLinus Torvalds  * and working on them outside the LRU lock.
20381da177e4SLinus Torvalds  *
20391da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
20401da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
20411da177e4SLinus Torvalds  *
204215b44736SHugh Dickins  * Lru_lock must be held before calling this function.
20431da177e4SLinus Torvalds  *
2044791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
20455dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
20461da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
2047f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
2048fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
20493cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
20501da177e4SLinus Torvalds  *
20511da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
20521da177e4SLinus Torvalds  */
205369e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
20545dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
2055fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
2056a9e7c39fSKirill Tkhai 		enum lru_list lru)
20571da177e4SLinus Torvalds {
205875b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
205969e05944SAndrew Morton 	unsigned long nr_taken = 0;
2060599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
20617cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
20623db65812SJohannes Weiner 	unsigned long skipped = 0;
2063791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
2064b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
2065a9e7c39fSKirill Tkhai 	isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
20661da177e4SLinus Torvalds 
206798879b3bSYang Shi 	total_scan = 0;
2068791b48b6SMinchan Kim 	scan = 0;
206998879b3bSYang Shi 	while (scan < nr_to_scan && !list_empty(src)) {
20705ad333ebSAndy Whitcroft 		struct page *page;
20715ad333ebSAndy Whitcroft 
20721da177e4SLinus Torvalds 		page = lru_to_page(src);
20731da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
20741da177e4SLinus Torvalds 
2075d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
207698879b3bSYang Shi 		total_scan += nr_pages;
207798879b3bSYang Shi 
2078b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
2079b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
208098879b3bSYang Shi 			nr_skipped[page_zonenum(page)] += nr_pages;
2081b2e18757SMel Gorman 			continue;
2082b2e18757SMel Gorman 		}
2083b2e18757SMel Gorman 
2084791b48b6SMinchan Kim 		/*
2085791b48b6SMinchan Kim 		 * Do not count skipped pages because that makes the function
2086791b48b6SMinchan Kim 		 * return with no isolated pages if the LRU mostly contains
2087791b48b6SMinchan Kim 		 * ineligible pages.  This causes the VM to not reclaim any
2088791b48b6SMinchan Kim 		 * pages, triggering a premature OOM.
208998879b3bSYang Shi 		 *
209098879b3bSYang Shi 		 * Account all tail pages of THP.  This would not cause
209198879b3bSYang Shi 		 * premature OOM since __isolate_lru_page() returns -EBUSY
209298879b3bSYang Shi 		 * only when the page is being freed somewhere else.
2093791b48b6SMinchan Kim 		 */
209498879b3bSYang Shi 		scan += nr_pages;
2095c2135f7cSAlex Shi 		if (!__isolate_lru_page_prepare(page, mode)) {
2096c2135f7cSAlex Shi 			/* It is being freed elsewhere */
2097c2135f7cSAlex Shi 			list_move(&page->lru, src);
2098c2135f7cSAlex Shi 			continue;
2099c2135f7cSAlex Shi 		}
21009df41314SAlex Shi 		/*
21019df41314SAlex Shi 		 * Be careful not to clear PageLRU until after we're
21029df41314SAlex Shi 		 * sure the page is not being freed elsewhere -- the
21039df41314SAlex Shi 		 * page release code relies on it.
21049df41314SAlex Shi 		 */
2105c2135f7cSAlex Shi 		if (unlikely(!get_page_unless_zero(page))) {
2106c2135f7cSAlex Shi 			list_move(&page->lru, src);
2107c2135f7cSAlex Shi 			continue;
2108c2135f7cSAlex Shi 		}
21099df41314SAlex Shi 
21109df41314SAlex Shi 		if (!TestClearPageLRU(page)) {
2111c2135f7cSAlex Shi 			/* Another thread is already isolating this page */
21129df41314SAlex Shi 			put_page(page);
2113c2135f7cSAlex Shi 			list_move(&page->lru, src);
2114c2135f7cSAlex Shi 			continue;
21159df41314SAlex Shi 		}
21169df41314SAlex Shi 
2117599d0c95SMel Gorman 		nr_taken += nr_pages;
2118599d0c95SMel Gorman 		nr_zone_taken[page_zonenum(page)] += nr_pages;
21195ad333ebSAndy Whitcroft 		list_move(&page->lru, dst);
21205ad333ebSAndy Whitcroft 	}
21211da177e4SLinus Torvalds 
2122b2e18757SMel Gorman 	/*
2123b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
2124b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
2125b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2126b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
2127b2e18757SMel Gorman 	 * system at risk of premature OOM.
2128b2e18757SMel Gorman 	 */
21297cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
21307cc30fcfSMel Gorman 		int zid;
21317cc30fcfSMel Gorman 
21323db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
21337cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
21347cc30fcfSMel Gorman 			if (!nr_skipped[zid])
21357cc30fcfSMel Gorman 				continue;
21367cc30fcfSMel Gorman 
21377cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
21381265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
21397cc30fcfSMel Gorman 		}
21407cc30fcfSMel Gorman 	}
2141791b48b6SMinchan Kim 	*nr_scanned = total_scan;
21421265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
2143791b48b6SMinchan Kim 				    total_scan, skipped, nr_taken, mode, lru);
2144b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
21451da177e4SLinus Torvalds 	return nr_taken;
21461da177e4SLinus Torvalds }
21471da177e4SLinus Torvalds 
214862695a84SNick Piggin /**
214962695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
215062695a84SNick Piggin  * @page: page to isolate from its LRU list
215162695a84SNick Piggin  *
215262695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
215362695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
215462695a84SNick Piggin  *
215562695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
215662695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
215762695a84SNick Piggin  *
215862695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
2159894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
2160894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
2161894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
216262695a84SNick Piggin  *
216362695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
216462695a84SNick Piggin  * found will be decremented.
216562695a84SNick Piggin  *
216662695a84SNick Piggin  * Restrictions:
2167a5d09bedSMike Rapoport  *
216862695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
216901c4776bSHui Su  *     fundamental difference from isolate_lru_pages (which is called
217062695a84SNick Piggin  *     without a stable reference).
217162695a84SNick Piggin  * (2) the lru_lock must not be held.
217262695a84SNick Piggin  * (3) interrupts must be enabled.
217362695a84SNick Piggin  */
217462695a84SNick Piggin int isolate_lru_page(struct page *page)
217562695a84SNick Piggin {
217662695a84SNick Piggin 	int ret = -EBUSY;
217762695a84SNick Piggin 
2178309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
2179cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
21800c917313SKonstantin Khlebnikov 
2181d25b5bd8SAlex Shi 	if (TestClearPageLRU(page)) {
2182fa9add64SHugh Dickins 		struct lruvec *lruvec;
218362695a84SNick Piggin 
21840c917313SKonstantin Khlebnikov 		get_page(page);
21856168d0daSAlex Shi 		lruvec = lock_page_lruvec_irq(page);
218646ae6b2cSYu Zhao 		del_page_from_lru_list(page, lruvec);
21876168d0daSAlex Shi 		unlock_page_lruvec_irq(lruvec);
2188fa9add64SHugh Dickins 		ret = 0;
218962695a84SNick Piggin 	}
2190d25b5bd8SAlex Shi 
219162695a84SNick Piggin 	return ret;
219262695a84SNick Piggin }
219362695a84SNick Piggin 
21945ad333ebSAndy Whitcroft /*
2195d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
2196178821b8SXianting Tian  * then get rescheduled. When there are massive number of tasks doing page
2197d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2198d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
2199d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
220035cd7815SRik van Riel  */
2201599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
220235cd7815SRik van Riel 		struct scan_control *sc)
220335cd7815SRik van Riel {
220435cd7815SRik van Riel 	unsigned long inactive, isolated;
2205d818fca1SMel Gorman 	bool too_many;
220635cd7815SRik van Riel 
220735cd7815SRik van Riel 	if (current_is_kswapd())
220835cd7815SRik van Riel 		return 0;
220935cd7815SRik van Riel 
2210b5ead35eSJohannes Weiner 	if (!writeback_throttling_sane(sc))
221135cd7815SRik van Riel 		return 0;
221235cd7815SRik van Riel 
221335cd7815SRik van Riel 	if (file) {
2214599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2215599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
221635cd7815SRik van Riel 	} else {
2217599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2218599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
221935cd7815SRik van Riel 	}
222035cd7815SRik van Riel 
22213cf23841SFengguang Wu 	/*
22223cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
22233cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
22243cf23841SFengguang Wu 	 * deadlock.
22253cf23841SFengguang Wu 	 */
2226d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
22273cf23841SFengguang Wu 		inactive >>= 3;
22283cf23841SFengguang Wu 
2229d818fca1SMel Gorman 	too_many = isolated > inactive;
2230d818fca1SMel Gorman 
2231d818fca1SMel Gorman 	/* Wake up tasks throttled due to too_many_isolated. */
2232d818fca1SMel Gorman 	if (!too_many)
2233d818fca1SMel Gorman 		wake_throttle_isolated(pgdat);
2234d818fca1SMel Gorman 
2235d818fca1SMel Gorman 	return too_many;
223635cd7815SRik van Riel }
223735cd7815SRik van Riel 
2238a222f341SKirill Tkhai /*
223915b44736SHugh Dickins  * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
224015b44736SHugh Dickins  * On return, @list is reused as a list of pages to be freed by the caller.
2241a222f341SKirill Tkhai  *
2242a222f341SKirill Tkhai  * Returns the number of pages moved to the given lruvec.
2243a222f341SKirill Tkhai  */
22449ef56b78SMuchun Song static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2245a222f341SKirill Tkhai 				      struct list_head *list)
224666635629SMel Gorman {
2247a222f341SKirill Tkhai 	int nr_pages, nr_moved = 0;
22483f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
2249a222f341SKirill Tkhai 	struct page *page;
225066635629SMel Gorman 
2251a222f341SKirill Tkhai 	while (!list_empty(list)) {
2252a222f341SKirill Tkhai 		page = lru_to_page(list);
2253309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
2254a222f341SKirill Tkhai 		list_del(&page->lru);
22553d06afabSAlex Shi 		if (unlikely(!page_evictable(page))) {
22566168d0daSAlex Shi 			spin_unlock_irq(&lruvec->lru_lock);
225766635629SMel Gorman 			putback_lru_page(page);
22586168d0daSAlex Shi 			spin_lock_irq(&lruvec->lru_lock);
225966635629SMel Gorman 			continue;
226066635629SMel Gorman 		}
2261fa9add64SHugh Dickins 
22623d06afabSAlex Shi 		/*
22633d06afabSAlex Shi 		 * The SetPageLRU needs to be kept here for list integrity.
22643d06afabSAlex Shi 		 * Otherwise:
22653d06afabSAlex Shi 		 *   #0 move_pages_to_lru             #1 release_pages
22663d06afabSAlex Shi 		 *   if !put_page_testzero
22673d06afabSAlex Shi 		 *				      if (put_page_testzero())
22683d06afabSAlex Shi 		 *				        !PageLRU //skip lru_lock
22693d06afabSAlex Shi 		 *     SetPageLRU()
22703d06afabSAlex Shi 		 *     list_add(&page->lru,)
22713d06afabSAlex Shi 		 *                                        list_add(&page->lru,)
22723d06afabSAlex Shi 		 */
22737a608572SLinus Torvalds 		SetPageLRU(page);
2274a222f341SKirill Tkhai 
22753d06afabSAlex Shi 		if (unlikely(put_page_testzero(page))) {
227687560179SYu Zhao 			__clear_page_lru_flags(page);
22772bcf8879SHugh Dickins 
22782bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
22796168d0daSAlex Shi 				spin_unlock_irq(&lruvec->lru_lock);
2280ff45fc3cSMatthew Wilcox (Oracle) 				destroy_compound_page(page);
22816168d0daSAlex Shi 				spin_lock_irq(&lruvec->lru_lock);
22822bcf8879SHugh Dickins 			} else
22832bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
22843d06afabSAlex Shi 
22853d06afabSAlex Shi 			continue;
22863d06afabSAlex Shi 		}
22873d06afabSAlex Shi 
2288afca9157SAlex Shi 		/*
2289afca9157SAlex Shi 		 * All pages were isolated from the same lruvec (and isolation
2290afca9157SAlex Shi 		 * inhibits memcg migration).
2291afca9157SAlex Shi 		 */
22927467c391SMuchun Song 		VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
22933a9c9788SYu Zhao 		add_page_to_lru_list(page, lruvec);
22943d06afabSAlex Shi 		nr_pages = thp_nr_pages(page);
2295a222f341SKirill Tkhai 		nr_moved += nr_pages;
229631d8fcacSJohannes Weiner 		if (PageActive(page))
229731d8fcacSJohannes Weiner 			workingset_age_nonresident(lruvec, nr_pages);
229866635629SMel Gorman 	}
229966635629SMel Gorman 
23003f79768fSHugh Dickins 	/*
23013f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
23023f79768fSHugh Dickins 	 */
2303a222f341SKirill Tkhai 	list_splice(&pages_to_free, list);
2304a222f341SKirill Tkhai 
2305a222f341SKirill Tkhai 	return nr_moved;
230666635629SMel Gorman }
230766635629SMel Gorman 
230866635629SMel Gorman /*
2309399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
2310a37b0715SNeilBrown  * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
2311399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
2312399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
2313399ba0b9SNeilBrown  */
2314399ba0b9SNeilBrown static int current_may_throttle(void)
2315399ba0b9SNeilBrown {
2316a37b0715SNeilBrown 	return !(current->flags & PF_LOCAL_THROTTLE) ||
2317399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
2318399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
2319399ba0b9SNeilBrown }
2320399ba0b9SNeilBrown 
2321399ba0b9SNeilBrown /*
2322b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
23231742f19fSAndrew Morton  * of reclaimed pages
23241da177e4SLinus Torvalds  */
23259ef56b78SMuchun Song static unsigned long
23261a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
23279e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
23281da177e4SLinus Torvalds {
23291da177e4SLinus Torvalds 	LIST_HEAD(page_list);
2330e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
2331730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
2332e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
2333060f005fSKirill Tkhai 	struct reclaim_stat stat;
2334497a6c1bSJohannes Weiner 	bool file = is_file_lru(lru);
2335f46b7912SKirill Tkhai 	enum vm_event_item item;
2336599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2337db73ee0dSMichal Hocko 	bool stalled = false;
233878dc583dSKOSAKI Motohiro 
2339599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
2340db73ee0dSMichal Hocko 		if (stalled)
2341db73ee0dSMichal Hocko 			return 0;
2342db73ee0dSMichal Hocko 
2343db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
2344db73ee0dSMichal Hocko 		stalled = true;
2345*c3f4a9a2SMel Gorman 		reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
234635cd7815SRik van Riel 
234735cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
234835cd7815SRik van Riel 		if (fatal_signal_pending(current))
234935cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
235035cd7815SRik van Riel 	}
235135cd7815SRik van Riel 
23521da177e4SLinus Torvalds 	lru_add_drain();
2353f80c0673SMinchan Kim 
23546168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
23551da177e4SLinus Torvalds 
23565dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
2357a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
235895d918fcSKonstantin Khlebnikov 
2359599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2360f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
2361b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
2362f46b7912SKirill Tkhai 		__count_vm_events(item, nr_scanned);
2363f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
2364497a6c1bSJohannes Weiner 	__count_vm_events(PGSCAN_ANON + file, nr_scanned);
2365497a6c1bSJohannes Weiner 
23666168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
2367d563c050SHillf Danton 
2368d563c050SHillf Danton 	if (nr_taken == 0)
236966635629SMel Gorman 		return 0;
2370b35ea17bSKOSAKI Motohiro 
2371013339dfSShakeel Butt 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
2372c661b078SAndy Whitcroft 
23736168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2374497a6c1bSJohannes Weiner 	move_pages_to_lru(lruvec, &page_list);
2375497a6c1bSJohannes Weiner 
2376497a6c1bSJohannes Weiner 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2377f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
2378b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
2379f46b7912SKirill Tkhai 		__count_vm_events(item, nr_reclaimed);
2380f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
2381497a6c1bSJohannes Weiner 	__count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
23826168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
23833f79768fSHugh Dickins 
238475cc3c91SAlex Shi 	lru_note_cost(lruvec, file, stat.nr_pageout);
2385747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
23862d4894b5SMel Gorman 	free_unref_page_list(&page_list);
2387e11da5b4SMel Gorman 
238892df3a72SMel Gorman 	/*
23891c610d5fSAndrey Ryabinin 	 * If dirty pages are scanned that are not queued for IO, it
23901c610d5fSAndrey Ryabinin 	 * implies that flushers are not doing their job. This can
23911c610d5fSAndrey Ryabinin 	 * happen when memory pressure pushes dirty pages to the end of
23921c610d5fSAndrey Ryabinin 	 * the LRU before the dirty limits are breached and the dirty
23931c610d5fSAndrey Ryabinin 	 * data has expired. It can also happen when the proportion of
23941c610d5fSAndrey Ryabinin 	 * dirty pages grows not through writes but through memory
23951c610d5fSAndrey Ryabinin 	 * pressure reclaiming all the clean cache. And in some cases,
23961c610d5fSAndrey Ryabinin 	 * the flushers simply cannot keep up with the allocation
23971c610d5fSAndrey Ryabinin 	 * rate. Nudge the flusher threads in case they are asleep.
23981c610d5fSAndrey Ryabinin 	 */
23991c610d5fSAndrey Ryabinin 	if (stat.nr_unqueued_dirty == nr_taken)
24001c610d5fSAndrey Ryabinin 		wakeup_flusher_threads(WB_REASON_VMSCAN);
24011c610d5fSAndrey Ryabinin 
2402d108c772SAndrey Ryabinin 	sc->nr.dirty += stat.nr_dirty;
2403d108c772SAndrey Ryabinin 	sc->nr.congested += stat.nr_congested;
2404d108c772SAndrey Ryabinin 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2405d108c772SAndrey Ryabinin 	sc->nr.writeback += stat.nr_writeback;
2406d108c772SAndrey Ryabinin 	sc->nr.immediate += stat.nr_immediate;
2407d108c772SAndrey Ryabinin 	sc->nr.taken += nr_taken;
2408d108c772SAndrey Ryabinin 	if (file)
2409d108c772SAndrey Ryabinin 		sc->nr.file_taken += nr_taken;
24108e950282SMel Gorman 
2411599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2412d51d1e64SSteven Rostedt 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
241305ff5137SAndrew Morton 	return nr_reclaimed;
24141da177e4SLinus Torvalds }
24151da177e4SLinus Torvalds 
241615b44736SHugh Dickins /*
241715b44736SHugh Dickins  * shrink_active_list() moves pages from the active LRU to the inactive LRU.
241815b44736SHugh Dickins  *
241915b44736SHugh Dickins  * We move them the other way if the page is referenced by one or more
242015b44736SHugh Dickins  * processes.
242115b44736SHugh Dickins  *
242215b44736SHugh Dickins  * If the pages are mostly unmapped, the processing is fast and it is
242315b44736SHugh Dickins  * appropriate to hold lru_lock across the whole operation.  But if
242415b44736SHugh Dickins  * the pages are mapped, the processing is slow (page_referenced()), so
242515b44736SHugh Dickins  * we should drop lru_lock around each page.  It's impossible to balance
242615b44736SHugh Dickins  * this, so instead we remove the pages from the LRU while processing them.
242715b44736SHugh Dickins  * It is safe to rely on PG_active against the non-LRU pages in here because
242815b44736SHugh Dickins  * nobody will play with that bit on a non-LRU page.
242915b44736SHugh Dickins  *
243015b44736SHugh Dickins  * The downside is that we have to touch page->_refcount against each page.
243115b44736SHugh Dickins  * But we had to alter page->flags anyway.
243215b44736SHugh Dickins  */
2433f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
24341a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
2435f16015fbSJohannes Weiner 			       struct scan_control *sc,
24369e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
24371cfb419bSKAMEZAWA Hiroyuki {
243844c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
2439f626012dSHugh Dickins 	unsigned long nr_scanned;
24406fe6b7e3SWu Fengguang 	unsigned long vm_flags;
24411cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
24428cab4754SWu Fengguang 	LIST_HEAD(l_active);
2443b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
24441cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
24459d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
24469d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
24473cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
2448599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
24491cfb419bSKAMEZAWA Hiroyuki 
24501da177e4SLinus Torvalds 	lru_add_drain();
2451f80c0673SMinchan Kim 
24526168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2453925b7673SJohannes Weiner 
24545dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2455a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
245689b5fae5SJohannes Weiner 
2457599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
24581cfb419bSKAMEZAWA Hiroyuki 
2459912c0572SShakeel Butt 	if (!cgroup_reclaim(sc))
2460599d0c95SMel Gorman 		__count_vm_events(PGREFILL, nr_scanned);
24612fa2690cSYafang Shao 	__count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
24629d5e6a9fSHugh Dickins 
24636168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
24641da177e4SLinus Torvalds 
24651da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
24661da177e4SLinus Torvalds 		cond_resched();
24671da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
24681da177e4SLinus Torvalds 		list_del(&page->lru);
24697e9cd484SRik van Riel 
247039b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
2471894bc310SLee Schermerhorn 			putback_lru_page(page);
2472894bc310SLee Schermerhorn 			continue;
2473894bc310SLee Schermerhorn 		}
2474894bc310SLee Schermerhorn 
2475cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
2476cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
2477cc715d99SMel Gorman 				if (page_has_private(page))
2478cc715d99SMel Gorman 					try_to_release_page(page, 0);
2479cc715d99SMel Gorman 				unlock_page(page);
2480cc715d99SMel Gorman 			}
2481cc715d99SMel Gorman 		}
2482cc715d99SMel Gorman 
2483c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
2484c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
24858cab4754SWu Fengguang 			/*
24868cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
24878cab4754SWu Fengguang 			 * give them one more trip around the active list. So
24888cab4754SWu Fengguang 			 * that executable code get better chances to stay in
24898cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
24908cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
24918cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
24928cab4754SWu Fengguang 			 * so we ignore them here.
24938cab4754SWu Fengguang 			 */
24949de4f22aSHuang Ying 			if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
24956c357848SMatthew Wilcox (Oracle) 				nr_rotated += thp_nr_pages(page);
24968cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
24978cab4754SWu Fengguang 				continue;
24988cab4754SWu Fengguang 			}
24998cab4754SWu Fengguang 		}
25007e9cd484SRik van Riel 
25015205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
25021899ad18SJohannes Weiner 		SetPageWorkingset(page);
25031da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
25041da177e4SLinus Torvalds 	}
25051da177e4SLinus Torvalds 
2506b555749aSAndrew Morton 	/*
25078cab4754SWu Fengguang 	 * Move pages back to the lru list.
2508b555749aSAndrew Morton 	 */
25096168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2510556adecbSRik van Riel 
2511a222f341SKirill Tkhai 	nr_activate = move_pages_to_lru(lruvec, &l_active);
2512a222f341SKirill Tkhai 	nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2513f372d89eSKirill Tkhai 	/* Keep all free pages in l_active list */
2514f372d89eSKirill Tkhai 	list_splice(&l_inactive, &l_active);
25159851ac13SKirill Tkhai 
25169851ac13SKirill Tkhai 	__count_vm_events(PGDEACTIVATE, nr_deactivate);
25179851ac13SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
25189851ac13SKirill Tkhai 
2519599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
25206168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
25212bcf8879SHugh Dickins 
2522f372d89eSKirill Tkhai 	mem_cgroup_uncharge_list(&l_active);
2523f372d89eSKirill Tkhai 	free_unref_page_list(&l_active);
25249d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
25259d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
25261da177e4SLinus Torvalds }
25271da177e4SLinus Torvalds 
25281a4e58ccSMinchan Kim unsigned long reclaim_pages(struct list_head *page_list)
25291a4e58ccSMinchan Kim {
2530f661d007SYang Shi 	int nid = NUMA_NO_NODE;
2531730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
25321a4e58ccSMinchan Kim 	LIST_HEAD(node_page_list);
25331a4e58ccSMinchan Kim 	struct reclaim_stat dummy_stat;
25341a4e58ccSMinchan Kim 	struct page *page;
25352d2b8d2bSYu Zhao 	unsigned int noreclaim_flag;
25361a4e58ccSMinchan Kim 	struct scan_control sc = {
25371a4e58ccSMinchan Kim 		.gfp_mask = GFP_KERNEL,
25381a4e58ccSMinchan Kim 		.may_writepage = 1,
25391a4e58ccSMinchan Kim 		.may_unmap = 1,
25401a4e58ccSMinchan Kim 		.may_swap = 1,
254126aa2d19SDave Hansen 		.no_demotion = 1,
25421a4e58ccSMinchan Kim 	};
25431a4e58ccSMinchan Kim 
25442d2b8d2bSYu Zhao 	noreclaim_flag = memalloc_noreclaim_save();
25452d2b8d2bSYu Zhao 
25461a4e58ccSMinchan Kim 	while (!list_empty(page_list)) {
25471a4e58ccSMinchan Kim 		page = lru_to_page(page_list);
2548f661d007SYang Shi 		if (nid == NUMA_NO_NODE) {
25491a4e58ccSMinchan Kim 			nid = page_to_nid(page);
25501a4e58ccSMinchan Kim 			INIT_LIST_HEAD(&node_page_list);
25511a4e58ccSMinchan Kim 		}
25521a4e58ccSMinchan Kim 
25531a4e58ccSMinchan Kim 		if (nid == page_to_nid(page)) {
25541a4e58ccSMinchan Kim 			ClearPageActive(page);
25551a4e58ccSMinchan Kim 			list_move(&page->lru, &node_page_list);
25561a4e58ccSMinchan Kim 			continue;
25571a4e58ccSMinchan Kim 		}
25581a4e58ccSMinchan Kim 
25591a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
25601a4e58ccSMinchan Kim 						NODE_DATA(nid),
2561013339dfSShakeel Butt 						&sc, &dummy_stat, false);
25621a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
25631a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
25641a4e58ccSMinchan Kim 			list_del(&page->lru);
25651a4e58ccSMinchan Kim 			putback_lru_page(page);
25661a4e58ccSMinchan Kim 		}
25671a4e58ccSMinchan Kim 
2568f661d007SYang Shi 		nid = NUMA_NO_NODE;
25691a4e58ccSMinchan Kim 	}
25701a4e58ccSMinchan Kim 
25711a4e58ccSMinchan Kim 	if (!list_empty(&node_page_list)) {
25721a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
25731a4e58ccSMinchan Kim 						NODE_DATA(nid),
2574013339dfSShakeel Butt 						&sc, &dummy_stat, false);
25751a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
25761a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
25771a4e58ccSMinchan Kim 			list_del(&page->lru);
25781a4e58ccSMinchan Kim 			putback_lru_page(page);
25791a4e58ccSMinchan Kim 		}
25801a4e58ccSMinchan Kim 	}
25811a4e58ccSMinchan Kim 
25822d2b8d2bSYu Zhao 	memalloc_noreclaim_restore(noreclaim_flag);
25832d2b8d2bSYu Zhao 
25841a4e58ccSMinchan Kim 	return nr_reclaimed;
25851a4e58ccSMinchan Kim }
25861a4e58ccSMinchan Kim 
2587b91ac374SJohannes Weiner static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2588b91ac374SJohannes Weiner 				 struct lruvec *lruvec, struct scan_control *sc)
2589b91ac374SJohannes Weiner {
2590b91ac374SJohannes Weiner 	if (is_active_lru(lru)) {
2591b91ac374SJohannes Weiner 		if (sc->may_deactivate & (1 << is_file_lru(lru)))
2592b91ac374SJohannes Weiner 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2593b91ac374SJohannes Weiner 		else
2594b91ac374SJohannes Weiner 			sc->skipped_deactivate = 1;
2595b91ac374SJohannes Weiner 		return 0;
2596b91ac374SJohannes Weiner 	}
2597b91ac374SJohannes Weiner 
2598b91ac374SJohannes Weiner 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2599b91ac374SJohannes Weiner }
2600b91ac374SJohannes Weiner 
260159dc76b0SRik van Riel /*
260259dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
260359dc76b0SRik van Riel  * to do too much work.
260414797e23SKOSAKI Motohiro  *
260559dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
260659dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
260759dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
260859dc76b0SRik van Riel  *
260959dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
261059dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
261159dc76b0SRik van Riel  *
26122a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
26132a2e4885SJohannes Weiner  *
261459dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
26153a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
261659dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
261759dc76b0SRik van Riel  *
261859dc76b0SRik van Riel  * total     target    max
261959dc76b0SRik van Riel  * memory    ratio     inactive
262059dc76b0SRik van Riel  * -------------------------------------
262159dc76b0SRik van Riel  *   10MB       1         5MB
262259dc76b0SRik van Riel  *  100MB       1        50MB
262359dc76b0SRik van Riel  *    1GB       3       250MB
262459dc76b0SRik van Riel  *   10GB      10       0.9GB
262559dc76b0SRik van Riel  *  100GB      31         3GB
262659dc76b0SRik van Riel  *    1TB     101        10GB
262759dc76b0SRik van Riel  *   10TB     320        32GB
262814797e23SKOSAKI Motohiro  */
2629b91ac374SJohannes Weiner static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
263014797e23SKOSAKI Motohiro {
2631b91ac374SJohannes Weiner 	enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
26322a2e4885SJohannes Weiner 	unsigned long inactive, active;
26332a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
263459dc76b0SRik van Riel 	unsigned long gb;
263559dc76b0SRik van Riel 
2636b91ac374SJohannes Weiner 	inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2637b91ac374SJohannes Weiner 	active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2638f8d1a311SMel Gorman 
263959dc76b0SRik van Riel 	gb = (inactive + active) >> (30 - PAGE_SHIFT);
26404002570cSJoonsoo Kim 	if (gb)
264159dc76b0SRik van Riel 		inactive_ratio = int_sqrt(10 * gb);
2642b39415b2SRik van Riel 	else
264359dc76b0SRik van Riel 		inactive_ratio = 1;
2644fd538803SMichal Hocko 
264559dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2646b39415b2SRik van Riel }
2647b39415b2SRik van Riel 
26489a265114SJohannes Weiner enum scan_balance {
26499a265114SJohannes Weiner 	SCAN_EQUAL,
26509a265114SJohannes Weiner 	SCAN_FRACT,
26519a265114SJohannes Weiner 	SCAN_ANON,
26529a265114SJohannes Weiner 	SCAN_FILE,
26539a265114SJohannes Weiner };
26549a265114SJohannes Weiner 
26551da177e4SLinus Torvalds /*
26564f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
26574f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
26584f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
26594f98a2feSRik van Riel  * onto the active list instead of evict.
26604f98a2feSRik van Riel  *
2661be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2662be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
26634f98a2feSRik van Riel  */
2664afaf07a6SJohannes Weiner static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2665afaf07a6SJohannes Weiner 			   unsigned long *nr)
26664f98a2feSRik van Riel {
2667a2a36488SKeith Busch 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2668afaf07a6SJohannes Weiner 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2669d483a5ddSJohannes Weiner 	unsigned long anon_cost, file_cost, total_cost;
267033377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
2671ed017373SYu Zhao 	u64 fraction[ANON_AND_FILE];
26729a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
26739a265114SJohannes Weiner 	enum scan_balance scan_balance;
26749a265114SJohannes Weiner 	unsigned long ap, fp;
26759a265114SJohannes Weiner 	enum lru_list lru;
267676a33fc3SShaohua Li 
267776a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2678a2a36488SKeith Busch 	if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
26799a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
268076a33fc3SShaohua Li 		goto out;
268176a33fc3SShaohua Li 	}
26824f98a2feSRik van Riel 
268310316b31SJohannes Weiner 	/*
268410316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
268510316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
268610316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
268710316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
268810316b31SJohannes Weiner 	 * too expensive.
268910316b31SJohannes Weiner 	 */
2690b5ead35eSJohannes Weiner 	if (cgroup_reclaim(sc) && !swappiness) {
26919a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
269210316b31SJohannes Weiner 		goto out;
269310316b31SJohannes Weiner 	}
269410316b31SJohannes Weiner 
269510316b31SJohannes Weiner 	/*
269610316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
269710316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
269810316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
269910316b31SJohannes Weiner 	 */
270002695175SJohannes Weiner 	if (!sc->priority && swappiness) {
27019a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
270210316b31SJohannes Weiner 		goto out;
270310316b31SJohannes Weiner 	}
270410316b31SJohannes Weiner 
270511d16c25SJohannes Weiner 	/*
270653138ceaSJohannes Weiner 	 * If the system is almost out of file pages, force-scan anon.
270762376251SJohannes Weiner 	 */
2708b91ac374SJohannes Weiner 	if (sc->file_is_tiny) {
270962376251SJohannes Weiner 		scan_balance = SCAN_ANON;
271062376251SJohannes Weiner 		goto out;
271162376251SJohannes Weiner 	}
271262376251SJohannes Weiner 
271362376251SJohannes Weiner 	/*
2714b91ac374SJohannes Weiner 	 * If there is enough inactive page cache, we do not reclaim
2715b91ac374SJohannes Weiner 	 * anything from the anonymous working right now.
2716e9868505SRik van Riel 	 */
2717b91ac374SJohannes Weiner 	if (sc->cache_trim_mode) {
27189a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2719e9868505SRik van Riel 		goto out;
27204f98a2feSRik van Riel 	}
27214f98a2feSRik van Riel 
27229a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
27234f98a2feSRik van Riel 	/*
2724314b57fbSJohannes Weiner 	 * Calculate the pressure balance between anon and file pages.
2725314b57fbSJohannes Weiner 	 *
2726314b57fbSJohannes Weiner 	 * The amount of pressure we put on each LRU is inversely
2727314b57fbSJohannes Weiner 	 * proportional to the cost of reclaiming each list, as
2728314b57fbSJohannes Weiner 	 * determined by the share of pages that are refaulting, times
2729314b57fbSJohannes Weiner 	 * the relative IO cost of bringing back a swapped out
2730314b57fbSJohannes Weiner 	 * anonymous page vs reloading a filesystem page (swappiness).
2731314b57fbSJohannes Weiner 	 *
2732d483a5ddSJohannes Weiner 	 * Although we limit that influence to ensure no list gets
2733d483a5ddSJohannes Weiner 	 * left behind completely: at least a third of the pressure is
2734d483a5ddSJohannes Weiner 	 * applied, before swappiness.
2735d483a5ddSJohannes Weiner 	 *
2736314b57fbSJohannes Weiner 	 * With swappiness at 100, anon and file have equal IO cost.
273758c37f6eSKOSAKI Motohiro 	 */
2738d483a5ddSJohannes Weiner 	total_cost = sc->anon_cost + sc->file_cost;
2739d483a5ddSJohannes Weiner 	anon_cost = total_cost + sc->anon_cost;
2740d483a5ddSJohannes Weiner 	file_cost = total_cost + sc->file_cost;
2741d483a5ddSJohannes Weiner 	total_cost = anon_cost + file_cost;
274258c37f6eSKOSAKI Motohiro 
2743d483a5ddSJohannes Weiner 	ap = swappiness * (total_cost + 1);
2744d483a5ddSJohannes Weiner 	ap /= anon_cost + 1;
27454f98a2feSRik van Riel 
2746d483a5ddSJohannes Weiner 	fp = (200 - swappiness) * (total_cost + 1);
2747d483a5ddSJohannes Weiner 	fp /= file_cost + 1;
27484f98a2feSRik van Riel 
274976a33fc3SShaohua Li 	fraction[0] = ap;
275076a33fc3SShaohua Li 	fraction[1] = fp;
2751a4fe1631SJohannes Weiner 	denominator = ap + fp;
275276a33fc3SShaohua Li out:
27534111304dSHugh Dickins 	for_each_evictable_lru(lru) {
27544111304dSHugh Dickins 		int file = is_file_lru(lru);
27559783aa99SChris Down 		unsigned long lruvec_size;
2756f56ce412SJohannes Weiner 		unsigned long low, min;
275776a33fc3SShaohua Li 		unsigned long scan;
275876a33fc3SShaohua Li 
27599783aa99SChris Down 		lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2760f56ce412SJohannes Weiner 		mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2761f56ce412SJohannes Weiner 				      &min, &low);
27629783aa99SChris Down 
2763f56ce412SJohannes Weiner 		if (min || low) {
27649783aa99SChris Down 			/*
27659783aa99SChris Down 			 * Scale a cgroup's reclaim pressure by proportioning
27669783aa99SChris Down 			 * its current usage to its memory.low or memory.min
27679783aa99SChris Down 			 * setting.
27689783aa99SChris Down 			 *
27699783aa99SChris Down 			 * This is important, as otherwise scanning aggression
27709783aa99SChris Down 			 * becomes extremely binary -- from nothing as we
27719783aa99SChris Down 			 * approach the memory protection threshold, to totally
27729783aa99SChris Down 			 * nominal as we exceed it.  This results in requiring
27739783aa99SChris Down 			 * setting extremely liberal protection thresholds. It
27749783aa99SChris Down 			 * also means we simply get no protection at all if we
27759783aa99SChris Down 			 * set it too low, which is not ideal.
27761bc63fb1SChris Down 			 *
27771bc63fb1SChris Down 			 * If there is any protection in place, we reduce scan
27781bc63fb1SChris Down 			 * pressure by how much of the total memory used is
27791bc63fb1SChris Down 			 * within protection thresholds.
27809783aa99SChris Down 			 *
27819de7ca46SChris Down 			 * There is one special case: in the first reclaim pass,
27829de7ca46SChris Down 			 * we skip over all groups that are within their low
27839de7ca46SChris Down 			 * protection. If that fails to reclaim enough pages to
27849de7ca46SChris Down 			 * satisfy the reclaim goal, we come back and override
27859de7ca46SChris Down 			 * the best-effort low protection. However, we still
27869de7ca46SChris Down 			 * ideally want to honor how well-behaved groups are in
27879de7ca46SChris Down 			 * that case instead of simply punishing them all
27889de7ca46SChris Down 			 * equally. As such, we reclaim them based on how much
27891bc63fb1SChris Down 			 * memory they are using, reducing the scan pressure
27901bc63fb1SChris Down 			 * again by how much of the total memory used is under
27911bc63fb1SChris Down 			 * hard protection.
27929783aa99SChris Down 			 */
27931bc63fb1SChris Down 			unsigned long cgroup_size = mem_cgroup_size(memcg);
2794f56ce412SJohannes Weiner 			unsigned long protection;
2795f56ce412SJohannes Weiner 
2796f56ce412SJohannes Weiner 			/* memory.low scaling, make sure we retry before OOM */
2797f56ce412SJohannes Weiner 			if (!sc->memcg_low_reclaim && low > min) {
2798f56ce412SJohannes Weiner 				protection = low;
2799f56ce412SJohannes Weiner 				sc->memcg_low_skipped = 1;
2800f56ce412SJohannes Weiner 			} else {
2801f56ce412SJohannes Weiner 				protection = min;
2802f56ce412SJohannes Weiner 			}
28031bc63fb1SChris Down 
28041bc63fb1SChris Down 			/* Avoid TOCTOU with earlier protection check */
28051bc63fb1SChris Down 			cgroup_size = max(cgroup_size, protection);
28061bc63fb1SChris Down 
28071bc63fb1SChris Down 			scan = lruvec_size - lruvec_size * protection /
280832d4f4b7SRik van Riel 				(cgroup_size + 1);
28099783aa99SChris Down 
28109783aa99SChris Down 			/*
28111bc63fb1SChris Down 			 * Minimally target SWAP_CLUSTER_MAX pages to keep
281255b65a57SEthon Paul 			 * reclaim moving forwards, avoiding decrementing
28139de7ca46SChris Down 			 * sc->priority further than desirable.
28149783aa99SChris Down 			 */
28151bc63fb1SChris Down 			scan = max(scan, SWAP_CLUSTER_MAX);
28169783aa99SChris Down 		} else {
28179783aa99SChris Down 			scan = lruvec_size;
28189783aa99SChris Down 		}
28199783aa99SChris Down 
28209783aa99SChris Down 		scan >>= sc->priority;
28219783aa99SChris Down 
2822688035f7SJohannes Weiner 		/*
2823688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2824688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2825688035f7SJohannes Weiner 		 */
2826688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
28279783aa99SChris Down 			scan = min(lruvec_size, SWAP_CLUSTER_MAX);
28289a265114SJohannes Weiner 
28299a265114SJohannes Weiner 		switch (scan_balance) {
28309a265114SJohannes Weiner 		case SCAN_EQUAL:
28319a265114SJohannes Weiner 			/* Scan lists relative to size */
28329a265114SJohannes Weiner 			break;
28339a265114SJohannes Weiner 		case SCAN_FRACT:
28349a265114SJohannes Weiner 			/*
28359a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
28369a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
283776073c64SGavin Shan 			 * Make sure we don't miss the last page on
283876073c64SGavin Shan 			 * the offlined memory cgroups because of a
283976073c64SGavin Shan 			 * round-off error.
28409a265114SJohannes Weiner 			 */
284176073c64SGavin Shan 			scan = mem_cgroup_online(memcg) ?
284276073c64SGavin Shan 			       div64_u64(scan * fraction[file], denominator) :
284376073c64SGavin Shan 			       DIV64_U64_ROUND_UP(scan * fraction[file],
28446f04f48dSSuleiman Souhlal 						  denominator);
28459a265114SJohannes Weiner 			break;
28469a265114SJohannes Weiner 		case SCAN_FILE:
28479a265114SJohannes Weiner 		case SCAN_ANON:
28489a265114SJohannes Weiner 			/* Scan one type exclusively */
2849e072bff6SMateusz Nosek 			if ((scan_balance == SCAN_FILE) != file)
28509a265114SJohannes Weiner 				scan = 0;
28519a265114SJohannes Weiner 			break;
28529a265114SJohannes Weiner 		default:
28539a265114SJohannes Weiner 			/* Look ma, no brain */
28549a265114SJohannes Weiner 			BUG();
28559a265114SJohannes Weiner 		}
28566b4f7799SJohannes Weiner 
28574111304dSHugh Dickins 		nr[lru] = scan;
285876a33fc3SShaohua Li 	}
28596e08a369SWu Fengguang }
28604f98a2feSRik van Riel 
28612f368a9fSDave Hansen /*
28622f368a9fSDave Hansen  * Anonymous LRU management is a waste if there is
28632f368a9fSDave Hansen  * ultimately no way to reclaim the memory.
28642f368a9fSDave Hansen  */
28652f368a9fSDave Hansen static bool can_age_anon_pages(struct pglist_data *pgdat,
28662f368a9fSDave Hansen 			       struct scan_control *sc)
28672f368a9fSDave Hansen {
28682f368a9fSDave Hansen 	/* Aging the anon LRU is valuable if swap is present: */
28692f368a9fSDave Hansen 	if (total_swap_pages > 0)
28702f368a9fSDave Hansen 		return true;
28712f368a9fSDave Hansen 
28722f368a9fSDave Hansen 	/* Also valuable if anon pages can be demoted: */
28732f368a9fSDave Hansen 	return can_demote(pgdat->node_id, sc);
28742f368a9fSDave Hansen }
28752f368a9fSDave Hansen 
2876afaf07a6SJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
28779b4f98cdSJohannes Weiner {
28789b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2879e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
28809b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
28819b4f98cdSJohannes Weiner 	enum lru_list lru;
28829b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
28839b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
28849b4f98cdSJohannes Weiner 	struct blk_plug plug;
28851a501907SMel Gorman 	bool scan_adjusted;
28869b4f98cdSJohannes Weiner 
2887afaf07a6SJohannes Weiner 	get_scan_count(lruvec, sc, nr);
28889b4f98cdSJohannes Weiner 
2889e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2890e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2891e82e0561SMel Gorman 
28921a501907SMel Gorman 	/*
28931a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
28941a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
28951a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
28961a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
28971a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
28981a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
28991a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
29001a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
29011a501907SMel Gorman 	 * dropped to zero at the first pass.
29021a501907SMel Gorman 	 */
2903b5ead35eSJohannes Weiner 	scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
29041a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
29051a501907SMel Gorman 
29069b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
29079b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
29089b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2909e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2910e82e0561SMel Gorman 		unsigned long nr_scanned;
2911e82e0561SMel Gorman 
29129b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
29139b4f98cdSJohannes Weiner 			if (nr[lru]) {
29149b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
29159b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
29169b4f98cdSJohannes Weiner 
29179b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
29183b991208SJohannes Weiner 							    lruvec, sc);
29199b4f98cdSJohannes Weiner 			}
29209b4f98cdSJohannes Weiner 		}
2921e82e0561SMel Gorman 
2922bd041733SMichal Hocko 		cond_resched();
2923bd041733SMichal Hocko 
2924e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2925e82e0561SMel Gorman 			continue;
2926e82e0561SMel Gorman 
29279b4f98cdSJohannes Weiner 		/*
2928e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
29291a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2930e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2931e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2932e82e0561SMel Gorman 		 * proportional to the original scan target.
2933e82e0561SMel Gorman 		 */
2934e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2935e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2936e82e0561SMel Gorman 
29371a501907SMel Gorman 		/*
29381a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
29391a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
29401a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
29411a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
29421a501907SMel Gorman 		 */
29431a501907SMel Gorman 		if (!nr_file || !nr_anon)
29441a501907SMel Gorman 			break;
29451a501907SMel Gorman 
2946e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2947e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2948e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2949e82e0561SMel Gorman 			lru = LRU_BASE;
2950e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2951e82e0561SMel Gorman 		} else {
2952e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2953e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2954e82e0561SMel Gorman 			lru = LRU_FILE;
2955e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2956e82e0561SMel Gorman 		}
2957e82e0561SMel Gorman 
2958e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2959e82e0561SMel Gorman 		nr[lru] = 0;
2960e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2961e82e0561SMel Gorman 
2962e82e0561SMel Gorman 		/*
2963e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2964e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2965e82e0561SMel Gorman 		 */
2966e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2967e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2968e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2969e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2970e82e0561SMel Gorman 
2971e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2972e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2973e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2974e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2975e82e0561SMel Gorman 
2976e82e0561SMel Gorman 		scan_adjusted = true;
29779b4f98cdSJohannes Weiner 	}
29789b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
29799b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
29809b4f98cdSJohannes Weiner 
29819b4f98cdSJohannes Weiner 	/*
29829b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
29839b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
29849b4f98cdSJohannes Weiner 	 */
29852f368a9fSDave Hansen 	if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
29862f368a9fSDave Hansen 	    inactive_is_low(lruvec, LRU_INACTIVE_ANON))
29879b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
29889b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
29899b4f98cdSJohannes Weiner }
29909b4f98cdSJohannes Weiner 
299123b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
29929e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
299323b9da55SMel Gorman {
2994d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
299523b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
29969e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
299723b9da55SMel Gorman 		return true;
299823b9da55SMel Gorman 
299923b9da55SMel Gorman 	return false;
300023b9da55SMel Gorman }
300123b9da55SMel Gorman 
30024f98a2feSRik van Riel /*
300323b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
300423b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
300523b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
3006df3a45f9SQiwu Chen  * calls try_to_compact_pages() that it will have enough free pages to succeed.
300723b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
30083e7d3449SMel Gorman  */
3009a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
30103e7d3449SMel Gorman 					unsigned long nr_reclaimed,
30113e7d3449SMel Gorman 					struct scan_control *sc)
30123e7d3449SMel Gorman {
30133e7d3449SMel Gorman 	unsigned long pages_for_compaction;
30143e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
3015a9dd0a83SMel Gorman 	int z;
30163e7d3449SMel Gorman 
30173e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
30189e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
30193e7d3449SMel Gorman 		return false;
30203e7d3449SMel Gorman 
30213e7d3449SMel Gorman 	/*
30225ee04716SVlastimil Babka 	 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
30235ee04716SVlastimil Babka 	 * number of pages that were scanned. This will return to the caller
30245ee04716SVlastimil Babka 	 * with the risk reclaim/compaction and the resulting allocation attempt
30255ee04716SVlastimil Babka 	 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
30265ee04716SVlastimil Babka 	 * allocations through requiring that the full LRU list has been scanned
30275ee04716SVlastimil Babka 	 * first, by assuming that zero delta of sc->nr_scanned means full LRU
30285ee04716SVlastimil Babka 	 * scan, but that approximation was wrong, and there were corner cases
30295ee04716SVlastimil Babka 	 * where always a non-zero amount of pages were scanned.
30302876592fSMel Gorman 	 */
30312876592fSMel Gorman 	if (!nr_reclaimed)
30322876592fSMel Gorman 		return false;
30333e7d3449SMel Gorman 
30343e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
3035a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
3036a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
30376aa303deSMel Gorman 		if (!managed_zone(zone))
3038a9dd0a83SMel Gorman 			continue;
3039a9dd0a83SMel Gorman 
3040a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
3041cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
30423e7d3449SMel Gorman 		case COMPACT_CONTINUE:
30433e7d3449SMel Gorman 			return false;
30443e7d3449SMel Gorman 		default:
3045a9dd0a83SMel Gorman 			/* check next zone */
3046a9dd0a83SMel Gorman 			;
30473e7d3449SMel Gorman 		}
30483e7d3449SMel Gorman 	}
30491c6c1597SHillf Danton 
30501c6c1597SHillf Danton 	/*
30511c6c1597SHillf Danton 	 * If we have not reclaimed enough pages for compaction and the
30521c6c1597SHillf Danton 	 * inactive lists are large enough, continue reclaiming
30531c6c1597SHillf Danton 	 */
30541c6c1597SHillf Danton 	pages_for_compaction = compact_gap(sc->order);
30551c6c1597SHillf Danton 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
3056a2a36488SKeith Busch 	if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
30571c6c1597SHillf Danton 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
30581c6c1597SHillf Danton 
30595ee04716SVlastimil Babka 	return inactive_lru_pages > pages_for_compaction;
3060a9dd0a83SMel Gorman }
30613e7d3449SMel Gorman 
30620f6a5cffSJohannes Weiner static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
3063f16015fbSJohannes Weiner {
30640f6a5cffSJohannes Weiner 	struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
3065694fbc0fSAndrew Morton 	struct mem_cgroup *memcg;
3066d108c772SAndrey Ryabinin 
30670f6a5cffSJohannes Weiner 	memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
3068694fbc0fSAndrew Morton 	do {
3069afaf07a6SJohannes Weiner 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
30708e8ae645SJohannes Weiner 		unsigned long reclaimed;
3071cb731d6cSVladimir Davydov 		unsigned long scanned;
30729b4f98cdSJohannes Weiner 
3073e3336cabSXunlei Pang 		/*
3074e3336cabSXunlei Pang 		 * This loop can become CPU-bound when target memcgs
3075e3336cabSXunlei Pang 		 * aren't eligible for reclaim - either because they
3076e3336cabSXunlei Pang 		 * don't have any reclaimable pages, or because their
3077e3336cabSXunlei Pang 		 * memory is explicitly protected. Avoid soft lockups.
3078e3336cabSXunlei Pang 		 */
3079e3336cabSXunlei Pang 		cond_resched();
3080e3336cabSXunlei Pang 
308145c7f7e1SChris Down 		mem_cgroup_calculate_protection(target_memcg, memcg);
308245c7f7e1SChris Down 
308345c7f7e1SChris Down 		if (mem_cgroup_below_min(memcg)) {
3084bf8d5d52SRoman Gushchin 			/*
3085bf8d5d52SRoman Gushchin 			 * Hard protection.
3086bf8d5d52SRoman Gushchin 			 * If there is no reclaimable memory, OOM.
3087bf8d5d52SRoman Gushchin 			 */
3088bf8d5d52SRoman Gushchin 			continue;
308945c7f7e1SChris Down 		} else if (mem_cgroup_below_low(memcg)) {
3090bf8d5d52SRoman Gushchin 			/*
3091bf8d5d52SRoman Gushchin 			 * Soft protection.
3092bf8d5d52SRoman Gushchin 			 * Respect the protection only as long as
3093bf8d5d52SRoman Gushchin 			 * there is an unprotected supply
3094bf8d5d52SRoman Gushchin 			 * of reclaimable memory from other cgroups.
3095bf8d5d52SRoman Gushchin 			 */
3096d6622f63SYisheng Xie 			if (!sc->memcg_low_reclaim) {
3097d6622f63SYisheng Xie 				sc->memcg_low_skipped = 1;
3098241994edSJohannes Weiner 				continue;
3099d6622f63SYisheng Xie 			}
3100e27be240SJohannes Weiner 			memcg_memory_event(memcg, MEMCG_LOW);
3101241994edSJohannes Weiner 		}
3102241994edSJohannes Weiner 
31038e8ae645SJohannes Weiner 		reclaimed = sc->nr_reclaimed;
3104cb731d6cSVladimir Davydov 		scanned = sc->nr_scanned;
3105afaf07a6SJohannes Weiner 
3106afaf07a6SJohannes Weiner 		shrink_lruvec(lruvec, sc);
3107f9be23d6SKonstantin Khlebnikov 
310828360f39SMel Gorman 		shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
310928360f39SMel Gorman 			    sc->priority);
3110cb731d6cSVladimir Davydov 
31118e8ae645SJohannes Weiner 		/* Record the group's reclaim efficiency */
31128e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, memcg, false,
31138e8ae645SJohannes Weiner 			   sc->nr_scanned - scanned,
31148e8ae645SJohannes Weiner 			   sc->nr_reclaimed - reclaimed);
31158e8ae645SJohannes Weiner 
31160f6a5cffSJohannes Weiner 	} while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
31170f6a5cffSJohannes Weiner }
31180f6a5cffSJohannes Weiner 
31196c9e0907SLiu Song static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
31200f6a5cffSJohannes Weiner {
31210f6a5cffSJohannes Weiner 	struct reclaim_state *reclaim_state = current->reclaim_state;
31220f6a5cffSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
31231b05117dSJohannes Weiner 	struct lruvec *target_lruvec;
31240f6a5cffSJohannes Weiner 	bool reclaimable = false;
3125b91ac374SJohannes Weiner 	unsigned long file;
31260f6a5cffSJohannes Weiner 
31271b05117dSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
31281b05117dSJohannes Weiner 
31290f6a5cffSJohannes Weiner again:
3130aa48e47eSShakeel Butt 	/*
3131aa48e47eSShakeel Butt 	 * Flush the memory cgroup stats, so that we read accurate per-memcg
3132aa48e47eSShakeel Butt 	 * lruvec stats for heuristics.
3133aa48e47eSShakeel Butt 	 */
3134aa48e47eSShakeel Butt 	mem_cgroup_flush_stats();
3135aa48e47eSShakeel Butt 
31360f6a5cffSJohannes Weiner 	memset(&sc->nr, 0, sizeof(sc->nr));
31370f6a5cffSJohannes Weiner 
31380f6a5cffSJohannes Weiner 	nr_reclaimed = sc->nr_reclaimed;
31390f6a5cffSJohannes Weiner 	nr_scanned = sc->nr_scanned;
31400f6a5cffSJohannes Weiner 
314153138ceaSJohannes Weiner 	/*
31427cf111bcSJohannes Weiner 	 * Determine the scan balance between anon and file LRUs.
31437cf111bcSJohannes Weiner 	 */
31446168d0daSAlex Shi 	spin_lock_irq(&target_lruvec->lru_lock);
31457cf111bcSJohannes Weiner 	sc->anon_cost = target_lruvec->anon_cost;
31467cf111bcSJohannes Weiner 	sc->file_cost = target_lruvec->file_cost;
31476168d0daSAlex Shi 	spin_unlock_irq(&target_lruvec->lru_lock);
31487cf111bcSJohannes Weiner 
31497cf111bcSJohannes Weiner 	/*
3150b91ac374SJohannes Weiner 	 * Target desirable inactive:active list ratios for the anon
3151b91ac374SJohannes Weiner 	 * and file LRU lists.
3152b91ac374SJohannes Weiner 	 */
3153b91ac374SJohannes Weiner 	if (!sc->force_deactivate) {
3154b91ac374SJohannes Weiner 		unsigned long refaults;
3155b91ac374SJohannes Weiner 
3156170b04b7SJoonsoo Kim 		refaults = lruvec_page_state(target_lruvec,
3157170b04b7SJoonsoo Kim 				WORKINGSET_ACTIVATE_ANON);
3158170b04b7SJoonsoo Kim 		if (refaults != target_lruvec->refaults[0] ||
3159170b04b7SJoonsoo Kim 			inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
3160b91ac374SJohannes Weiner 			sc->may_deactivate |= DEACTIVATE_ANON;
3161b91ac374SJohannes Weiner 		else
3162b91ac374SJohannes Weiner 			sc->may_deactivate &= ~DEACTIVATE_ANON;
3163b91ac374SJohannes Weiner 
3164b91ac374SJohannes Weiner 		/*
3165b91ac374SJohannes Weiner 		 * When refaults are being observed, it means a new
3166b91ac374SJohannes Weiner 		 * workingset is being established. Deactivate to get
3167b91ac374SJohannes Weiner 		 * rid of any stale active pages quickly.
3168b91ac374SJohannes Weiner 		 */
3169b91ac374SJohannes Weiner 		refaults = lruvec_page_state(target_lruvec,
3170170b04b7SJoonsoo Kim 				WORKINGSET_ACTIVATE_FILE);
3171170b04b7SJoonsoo Kim 		if (refaults != target_lruvec->refaults[1] ||
3172b91ac374SJohannes Weiner 		    inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
3173b91ac374SJohannes Weiner 			sc->may_deactivate |= DEACTIVATE_FILE;
3174b91ac374SJohannes Weiner 		else
3175b91ac374SJohannes Weiner 			sc->may_deactivate &= ~DEACTIVATE_FILE;
3176b91ac374SJohannes Weiner 	} else
3177b91ac374SJohannes Weiner 		sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
3178b91ac374SJohannes Weiner 
3179b91ac374SJohannes Weiner 	/*
3180b91ac374SJohannes Weiner 	 * If we have plenty of inactive file pages that aren't
3181b91ac374SJohannes Weiner 	 * thrashing, try to reclaim those first before touching
3182b91ac374SJohannes Weiner 	 * anonymous pages.
3183b91ac374SJohannes Weiner 	 */
3184b91ac374SJohannes Weiner 	file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
3185b91ac374SJohannes Weiner 	if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
3186b91ac374SJohannes Weiner 		sc->cache_trim_mode = 1;
3187b91ac374SJohannes Weiner 	else
3188b91ac374SJohannes Weiner 		sc->cache_trim_mode = 0;
3189b91ac374SJohannes Weiner 
3190b91ac374SJohannes Weiner 	/*
319153138ceaSJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
319253138ceaSJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
319353138ceaSJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
319453138ceaSJohannes Weiner 	 * shrinks, so does the window for rotation from references.
319553138ceaSJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
319653138ceaSJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
319753138ceaSJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
319853138ceaSJohannes Weiner 	 */
319953138ceaSJohannes Weiner 	if (!cgroup_reclaim(sc)) {
320053138ceaSJohannes Weiner 		unsigned long total_high_wmark = 0;
3201b91ac374SJohannes Weiner 		unsigned long free, anon;
3202b91ac374SJohannes Weiner 		int z;
320353138ceaSJohannes Weiner 
320453138ceaSJohannes Weiner 		free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
320553138ceaSJohannes Weiner 		file = node_page_state(pgdat, NR_ACTIVE_FILE) +
320653138ceaSJohannes Weiner 			   node_page_state(pgdat, NR_INACTIVE_FILE);
320753138ceaSJohannes Weiner 
320853138ceaSJohannes Weiner 		for (z = 0; z < MAX_NR_ZONES; z++) {
320953138ceaSJohannes Weiner 			struct zone *zone = &pgdat->node_zones[z];
321053138ceaSJohannes Weiner 			if (!managed_zone(zone))
321153138ceaSJohannes Weiner 				continue;
321253138ceaSJohannes Weiner 
321353138ceaSJohannes Weiner 			total_high_wmark += high_wmark_pages(zone);
321453138ceaSJohannes Weiner 		}
321553138ceaSJohannes Weiner 
3216b91ac374SJohannes Weiner 		/*
3217b91ac374SJohannes Weiner 		 * Consider anon: if that's low too, this isn't a
3218b91ac374SJohannes Weiner 		 * runaway file reclaim problem, but rather just
3219b91ac374SJohannes Weiner 		 * extreme pressure. Reclaim as per usual then.
3220b91ac374SJohannes Weiner 		 */
3221b91ac374SJohannes Weiner 		anon = node_page_state(pgdat, NR_INACTIVE_ANON);
3222b91ac374SJohannes Weiner 
3223b91ac374SJohannes Weiner 		sc->file_is_tiny =
3224b91ac374SJohannes Weiner 			file + free <= total_high_wmark &&
3225b91ac374SJohannes Weiner 			!(sc->may_deactivate & DEACTIVATE_ANON) &&
3226b91ac374SJohannes Weiner 			anon >> sc->priority;
322753138ceaSJohannes Weiner 	}
322853138ceaSJohannes Weiner 
32290f6a5cffSJohannes Weiner 	shrink_node_memcgs(pgdat, sc);
323070ddf637SAnton Vorontsov 
32316b4f7799SJohannes Weiner 	if (reclaim_state) {
3232cb731d6cSVladimir Davydov 		sc->nr_reclaimed += reclaim_state->reclaimed_slab;
32336b4f7799SJohannes Weiner 		reclaim_state->reclaimed_slab = 0;
32346b4f7799SJohannes Weiner 	}
32356b4f7799SJohannes Weiner 
32368e8ae645SJohannes Weiner 	/* Record the subtree's reclaim efficiency */
32371b05117dSJohannes Weiner 	vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
323870ddf637SAnton Vorontsov 		   sc->nr_scanned - nr_scanned,
323970ddf637SAnton Vorontsov 		   sc->nr_reclaimed - nr_reclaimed);
324070ddf637SAnton Vorontsov 
32412344d7e4SJohannes Weiner 	if (sc->nr_reclaimed - nr_reclaimed)
32422344d7e4SJohannes Weiner 		reclaimable = true;
32432344d7e4SJohannes Weiner 
3244e3c1ac58SAndrey Ryabinin 	if (current_is_kswapd()) {
3245d108c772SAndrey Ryabinin 		/*
3246e3c1ac58SAndrey Ryabinin 		 * If reclaim is isolating dirty pages under writeback,
3247e3c1ac58SAndrey Ryabinin 		 * it implies that the long-lived page allocation rate
3248e3c1ac58SAndrey Ryabinin 		 * is exceeding the page laundering rate. Either the
3249e3c1ac58SAndrey Ryabinin 		 * global limits are not being effective at throttling
3250e3c1ac58SAndrey Ryabinin 		 * processes due to the page distribution throughout
3251e3c1ac58SAndrey Ryabinin 		 * zones or there is heavy usage of a slow backing
3252e3c1ac58SAndrey Ryabinin 		 * device. The only option is to throttle from reclaim
3253e3c1ac58SAndrey Ryabinin 		 * context which is not ideal as there is no guarantee
3254d108c772SAndrey Ryabinin 		 * the dirtying process is throttled in the same way
3255d108c772SAndrey Ryabinin 		 * balance_dirty_pages() manages.
3256d108c772SAndrey Ryabinin 		 *
3257e3c1ac58SAndrey Ryabinin 		 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
3258e3c1ac58SAndrey Ryabinin 		 * count the number of pages under pages flagged for
3259e3c1ac58SAndrey Ryabinin 		 * immediate reclaim and stall if any are encountered
3260e3c1ac58SAndrey Ryabinin 		 * in the nr_immediate check below.
3261d108c772SAndrey Ryabinin 		 */
3262d108c772SAndrey Ryabinin 		if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
3263d108c772SAndrey Ryabinin 			set_bit(PGDAT_WRITEBACK, &pgdat->flags);
3264d108c772SAndrey Ryabinin 
3265d108c772SAndrey Ryabinin 		/* Allow kswapd to start writing pages during reclaim.*/
3266d108c772SAndrey Ryabinin 		if (sc->nr.unqueued_dirty == sc->nr.file_taken)
3267d108c772SAndrey Ryabinin 			set_bit(PGDAT_DIRTY, &pgdat->flags);
3268d108c772SAndrey Ryabinin 
3269d108c772SAndrey Ryabinin 		/*
32701eba09c1SRandy Dunlap 		 * If kswapd scans pages marked for immediate
3271d108c772SAndrey Ryabinin 		 * reclaim and under writeback (nr_immediate), it
3272d108c772SAndrey Ryabinin 		 * implies that pages are cycling through the LRU
32738cd7c588SMel Gorman 		 * faster than they are written so forcibly stall
32748cd7c588SMel Gorman 		 * until some pages complete writeback.
3275d108c772SAndrey Ryabinin 		 */
3276d108c772SAndrey Ryabinin 		if (sc->nr.immediate)
3277*c3f4a9a2SMel Gorman 			reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
3278d108c772SAndrey Ryabinin 	}
3279d108c772SAndrey Ryabinin 
3280d108c772SAndrey Ryabinin 	/*
32818cd7c588SMel Gorman 	 * Tag a node/memcg as congested if all the dirty pages were marked
32828cd7c588SMel Gorman 	 * for writeback and immediate reclaim (counted in nr.congested).
32831b05117dSJohannes Weiner 	 *
3284e3c1ac58SAndrey Ryabinin 	 * Legacy memcg will stall in page writeback so avoid forcibly
32858cd7c588SMel Gorman 	 * stalling in reclaim_throttle().
3286e3c1ac58SAndrey Ryabinin 	 */
32871b05117dSJohannes Weiner 	if ((current_is_kswapd() ||
32881b05117dSJohannes Weiner 	     (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
3289e3c1ac58SAndrey Ryabinin 	    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
32901b05117dSJohannes Weiner 		set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
3291e3c1ac58SAndrey Ryabinin 
3292e3c1ac58SAndrey Ryabinin 	/*
32938cd7c588SMel Gorman 	 * Stall direct reclaim for IO completions if the lruvec is
32948cd7c588SMel Gorman 	 * node is congested. Allow kswapd to continue until it
3295d108c772SAndrey Ryabinin 	 * starts encountering unqueued dirty pages or cycling through
3296d108c772SAndrey Ryabinin 	 * the LRU too quickly.
3297d108c772SAndrey Ryabinin 	 */
32981b05117dSJohannes Weiner 	if (!current_is_kswapd() && current_may_throttle() &&
32991b05117dSJohannes Weiner 	    !sc->hibernation_mode &&
33001b05117dSJohannes Weiner 	    test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
3301*c3f4a9a2SMel Gorman 		reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
3302d108c772SAndrey Ryabinin 
3303d2af3397SJohannes Weiner 	if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
3304d2af3397SJohannes Weiner 				    sc))
3305d2af3397SJohannes Weiner 		goto again;
33062344d7e4SJohannes Weiner 
3307c73322d0SJohannes Weiner 	/*
3308c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
3309c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
3310c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
3311c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
3312c73322d0SJohannes Weiner 	 */
3313c73322d0SJohannes Weiner 	if (reclaimable)
3314c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
3315f16015fbSJohannes Weiner }
3316f16015fbSJohannes Weiner 
331753853e2dSVlastimil Babka /*
3318fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
3319fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
3320fdd4c614SVlastimil Babka  * should reclaim first.
332153853e2dSVlastimil Babka  */
33224f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
3323fe4b1b24SMel Gorman {
332431483b6aSMel Gorman 	unsigned long watermark;
3325fdd4c614SVlastimil Babka 	enum compact_result suitable;
3326fe4b1b24SMel Gorman 
3327fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
3328fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
3329fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
3330fdd4c614SVlastimil Babka 		return true;
3331fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
3332fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
3333fe4b1b24SMel Gorman 		return false;
3334fe4b1b24SMel Gorman 
3335fdd4c614SVlastimil Babka 	/*
3336fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
3337fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
3338fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
3339fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
3340fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
3341fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
3342fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
3343fdd4c614SVlastimil Babka 	 */
3344fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
3345fdd4c614SVlastimil Babka 
3346fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
3347fe4b1b24SMel Gorman }
3348fe4b1b24SMel Gorman 
334969392a40SMel Gorman static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc)
335069392a40SMel Gorman {
335169392a40SMel Gorman 	/* If reclaim is making progress, wake any throttled tasks. */
335269392a40SMel Gorman 	if (sc->nr_reclaimed) {
335369392a40SMel Gorman 		wait_queue_head_t *wqh;
335469392a40SMel Gorman 
335569392a40SMel Gorman 		wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS];
335669392a40SMel Gorman 		if (waitqueue_active(wqh))
335769392a40SMel Gorman 			wake_up(wqh);
335869392a40SMel Gorman 
335969392a40SMel Gorman 		return;
336069392a40SMel Gorman 	}
336169392a40SMel Gorman 
336269392a40SMel Gorman 	/*
336369392a40SMel Gorman 	 * Do not throttle kswapd on NOPROGRESS as it will throttle on
336469392a40SMel Gorman 	 * VMSCAN_THROTTLE_WRITEBACK if there are too many pages under
336569392a40SMel Gorman 	 * writeback and marked for immediate reclaim at the tail of
336669392a40SMel Gorman 	 * the LRU.
336769392a40SMel Gorman 	 */
336869392a40SMel Gorman 	if (current_is_kswapd())
336969392a40SMel Gorman 		return;
337069392a40SMel Gorman 
337169392a40SMel Gorman 	/* Throttle if making no progress at high prioities. */
337269392a40SMel Gorman 	if (sc->priority < DEF_PRIORITY - 2)
3373*c3f4a9a2SMel Gorman 		reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS);
337469392a40SMel Gorman }
337569392a40SMel Gorman 
33761da177e4SLinus Torvalds /*
33771da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
33781da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
33791da177e4SLinus Torvalds  * request.
33801da177e4SLinus Torvalds  *
33811da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
33821da177e4SLinus Torvalds  * scan then give up on it.
33831da177e4SLinus Torvalds  */
33840a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
33851da177e4SLinus Torvalds {
3386dd1a239fSMel Gorman 	struct zoneref *z;
338754a6eb5cSMel Gorman 	struct zone *zone;
33880608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
33890608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3390619d0d76SWeijie Yang 	gfp_t orig_mask;
339179dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
33921cfb419bSKAMEZAWA Hiroyuki 
3393cc715d99SMel Gorman 	/*
3394cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
3395cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
3396cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
3397cc715d99SMel Gorman 	 */
3398619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
3399b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
3400cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
34014f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
3402b2e18757SMel Gorman 	}
3403cc715d99SMel Gorman 
3404d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
3405b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
3406b2e18757SMel Gorman 		/*
34071cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
34081cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
34091cfb419bSKAMEZAWA Hiroyuki 		 */
3410b5ead35eSJohannes Weiner 		if (!cgroup_reclaim(sc)) {
3411344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
3412344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
34131da177e4SLinus Torvalds 				continue;
341465ec02cbSVladimir Davydov 
3415e0887c19SRik van Riel 			/*
3416e0c23279SMel Gorman 			 * If we already have plenty of memory free for
3417e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
3418e0c23279SMel Gorman 			 * Even though compaction is invoked for any
3419e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
3420e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
3421c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
3422c7cfa37bSCopot Alexandru 			 * page allocations.
3423e0887c19SRik van Riel 			 */
34240b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
34250b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
34264f588331SMel Gorman 			    compaction_ready(zone, sc)) {
34270b06496aSJohannes Weiner 				sc->compaction_ready = true;
3428e0887c19SRik van Riel 				continue;
3429e0887c19SRik van Riel 			}
34300b06496aSJohannes Weiner 
34310608f43dSAndrew Morton 			/*
343279dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
343379dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
343479dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
343579dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
343679dafcdcSMel Gorman 			 */
343779dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
343879dafcdcSMel Gorman 				continue;
343979dafcdcSMel Gorman 
344079dafcdcSMel Gorman 			/*
34410608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
34420608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
34430608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
34440608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
34450608f43dSAndrew Morton 			 */
34460608f43dSAndrew Morton 			nr_soft_scanned = 0;
3447ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
34480608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
34490608f43dSAndrew Morton 						&nr_soft_scanned);
34500608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
34510608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
3452ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
3453ac34a1a3SKAMEZAWA Hiroyuki 		}
3454d149e3b2SYing Han 
345579dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
345679dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
345779dafcdcSMel Gorman 			continue;
345879dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
3459970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
346069392a40SMel Gorman 		consider_reclaim_throttle(zone->zone_pgdat, sc);
34611da177e4SLinus Torvalds 	}
3462e0c23279SMel Gorman 
346365ec02cbSVladimir Davydov 	/*
3464619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
3465619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
3466619d0d76SWeijie Yang 	 */
3467619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
34681da177e4SLinus Torvalds }
34691da177e4SLinus Torvalds 
3470b910718aSJohannes Weiner static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
34712a2e4885SJohannes Weiner {
3472b910718aSJohannes Weiner 	struct lruvec *target_lruvec;
34732a2e4885SJohannes Weiner 	unsigned long refaults;
34742a2e4885SJohannes Weiner 
3475b910718aSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
3476170b04b7SJoonsoo Kim 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
3477170b04b7SJoonsoo Kim 	target_lruvec->refaults[0] = refaults;
3478170b04b7SJoonsoo Kim 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
3479170b04b7SJoonsoo Kim 	target_lruvec->refaults[1] = refaults;
34802a2e4885SJohannes Weiner }
34812a2e4885SJohannes Weiner 
34821da177e4SLinus Torvalds /*
34831da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
34841da177e4SLinus Torvalds  *
34851da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
34861da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
34871da177e4SLinus Torvalds  *
34881da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
34891da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
34905b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
34915b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
34925b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
34935b0830cbSJens Axboe  * work, and the allocation attempt will fail.
3494a41f24eaSNishanth Aravamudan  *
3495a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
3496a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
34971da177e4SLinus Torvalds  */
3498dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
34993115cd91SVladimir Davydov 					  struct scan_control *sc)
35001da177e4SLinus Torvalds {
3501241994edSJohannes Weiner 	int initial_priority = sc->priority;
35022a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
35032a2e4885SJohannes Weiner 	struct zoneref *z;
35042a2e4885SJohannes Weiner 	struct zone *zone;
3505241994edSJohannes Weiner retry:
3506873b4771SKeika Kobayashi 	delayacct_freepages_start();
3507873b4771SKeika Kobayashi 
3508b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
35097cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
35101da177e4SLinus Torvalds 
35119e3b2f8cSKonstantin Khlebnikov 	do {
351270ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
351370ddf637SAnton Vorontsov 				sc->priority);
351466e1707bSBalbir Singh 		sc->nr_scanned = 0;
35150a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
3516e0c23279SMel Gorman 
3517bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
35180b06496aSJohannes Weiner 			break;
35190b06496aSJohannes Weiner 
35200b06496aSJohannes Weiner 		if (sc->compaction_ready)
35210b06496aSJohannes Weiner 			break;
35221da177e4SLinus Torvalds 
35231da177e4SLinus Torvalds 		/*
35240e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
35250e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
35260e50ce3bSMinchan Kim 		 */
35270e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
35280e50ce3bSMinchan Kim 			sc->may_writepage = 1;
35290b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
3530bb21c7ceSKOSAKI Motohiro 
35312a2e4885SJohannes Weiner 	last_pgdat = NULL;
35322a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
35332a2e4885SJohannes Weiner 					sc->nodemask) {
35342a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
35352a2e4885SJohannes Weiner 			continue;
35362a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
35371b05117dSJohannes Weiner 
35382a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
35391b05117dSJohannes Weiner 
35401b05117dSJohannes Weiner 		if (cgroup_reclaim(sc)) {
35411b05117dSJohannes Weiner 			struct lruvec *lruvec;
35421b05117dSJohannes Weiner 
35431b05117dSJohannes Weiner 			lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
35441b05117dSJohannes Weiner 						   zone->zone_pgdat);
35451b05117dSJohannes Weiner 			clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
35461b05117dSJohannes Weiner 		}
35472a2e4885SJohannes Weiner 	}
35482a2e4885SJohannes Weiner 
3549873b4771SKeika Kobayashi 	delayacct_freepages_end();
3550873b4771SKeika Kobayashi 
3551bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
3552bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
3553bb21c7ceSKOSAKI Motohiro 
35540cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
35550b06496aSJohannes Weiner 	if (sc->compaction_ready)
35567335084dSMel Gorman 		return 1;
35577335084dSMel Gorman 
3558b91ac374SJohannes Weiner 	/*
3559b91ac374SJohannes Weiner 	 * We make inactive:active ratio decisions based on the node's
3560b91ac374SJohannes Weiner 	 * composition of memory, but a restrictive reclaim_idx or a
3561b91ac374SJohannes Weiner 	 * memory.low cgroup setting can exempt large amounts of
3562b91ac374SJohannes Weiner 	 * memory from reclaim. Neither of which are very common, so
3563b91ac374SJohannes Weiner 	 * instead of doing costly eligibility calculations of the
3564b91ac374SJohannes Weiner 	 * entire cgroup subtree up front, we assume the estimates are
3565b91ac374SJohannes Weiner 	 * good, and retry with forcible deactivation if that fails.
3566b91ac374SJohannes Weiner 	 */
3567b91ac374SJohannes Weiner 	if (sc->skipped_deactivate) {
3568b91ac374SJohannes Weiner 		sc->priority = initial_priority;
3569b91ac374SJohannes Weiner 		sc->force_deactivate = 1;
3570b91ac374SJohannes Weiner 		sc->skipped_deactivate = 0;
3571b91ac374SJohannes Weiner 		goto retry;
3572b91ac374SJohannes Weiner 	}
3573b91ac374SJohannes Weiner 
3574241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
3575d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
3576241994edSJohannes Weiner 		sc->priority = initial_priority;
3577b91ac374SJohannes Weiner 		sc->force_deactivate = 0;
3578d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
3579d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
3580241994edSJohannes Weiner 		goto retry;
3581241994edSJohannes Weiner 	}
3582241994edSJohannes Weiner 
3583bb21c7ceSKOSAKI Motohiro 	return 0;
35841da177e4SLinus Torvalds }
35851da177e4SLinus Torvalds 
3586c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
35875515061dSMel Gorman {
35885515061dSMel Gorman 	struct zone *zone;
35895515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
35905515061dSMel Gorman 	unsigned long free_pages = 0;
35915515061dSMel Gorman 	int i;
35925515061dSMel Gorman 	bool wmark_ok;
35935515061dSMel Gorman 
3594c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3595c73322d0SJohannes Weiner 		return true;
3596c73322d0SJohannes Weiner 
35975515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
35985515061dSMel Gorman 		zone = &pgdat->node_zones[i];
3599d450abd8SJohannes Weiner 		if (!managed_zone(zone))
3600d450abd8SJohannes Weiner 			continue;
3601d450abd8SJohannes Weiner 
3602d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
3603675becceSMel Gorman 			continue;
3604675becceSMel Gorman 
36055515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
36065515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
36075515061dSMel Gorman 	}
36085515061dSMel Gorman 
3609675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
3610675becceSMel Gorman 	if (!pfmemalloc_reserve)
3611675becceSMel Gorman 		return true;
3612675becceSMel Gorman 
36135515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
36145515061dSMel Gorman 
36155515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
36165515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
361797a225e6SJoonsoo Kim 		if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
361897a225e6SJoonsoo Kim 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
36195644e1fbSQian Cai 
36205515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
36215515061dSMel Gorman 	}
36225515061dSMel Gorman 
36235515061dSMel Gorman 	return wmark_ok;
36245515061dSMel Gorman }
36255515061dSMel Gorman 
36265515061dSMel Gorman /*
36275515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
36285515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
36295515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
363050694c28SMel Gorman  * when the low watermark is reached.
363150694c28SMel Gorman  *
363250694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
363350694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
36345515061dSMel Gorman  */
363550694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
36365515061dSMel Gorman 					nodemask_t *nodemask)
36375515061dSMel Gorman {
3638675becceSMel Gorman 	struct zoneref *z;
36395515061dSMel Gorman 	struct zone *zone;
3640675becceSMel Gorman 	pg_data_t *pgdat = NULL;
36415515061dSMel Gorman 
36425515061dSMel Gorman 	/*
36435515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
36445515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
36455515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
36465515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
36475515061dSMel Gorman 	 * processes to block on log_wait_commit().
36485515061dSMel Gorman 	 */
36495515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
365050694c28SMel Gorman 		goto out;
365150694c28SMel Gorman 
365250694c28SMel Gorman 	/*
365350694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
365450694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
365550694c28SMel Gorman 	 */
365650694c28SMel Gorman 	if (fatal_signal_pending(current))
365750694c28SMel Gorman 		goto out;
36585515061dSMel Gorman 
3659675becceSMel Gorman 	/*
3660675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
3661675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3662675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
3663675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
3664675becceSMel Gorman 	 *
3665675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
3666675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
3667675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
3668675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
3669675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
3670675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
3671675becceSMel Gorman 	 * should make reasonable progress.
3672675becceSMel Gorman 	 */
3673675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
367417636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
3675675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
3676675becceSMel Gorman 			continue;
3677675becceSMel Gorman 
3678675becceSMel Gorman 		/* Throttle based on the first usable node */
36795515061dSMel Gorman 		pgdat = zone->zone_pgdat;
3680c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
368150694c28SMel Gorman 			goto out;
3682675becceSMel Gorman 		break;
3683675becceSMel Gorman 	}
3684675becceSMel Gorman 
3685675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
3686675becceSMel Gorman 	if (!pgdat)
3687675becceSMel Gorman 		goto out;
36885515061dSMel Gorman 
368968243e76SMel Gorman 	/* Account for the throttling */
369068243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
369168243e76SMel Gorman 
36925515061dSMel Gorman 	/*
36935515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
36945515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
36955515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
36965515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
36975515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
36985515061dSMel Gorman 	 * second before continuing.
36995515061dSMel Gorman 	 */
37002e786d9eSMiaohe Lin 	if (!(gfp_mask & __GFP_FS))
37015515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3702c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
37032e786d9eSMiaohe Lin 	else
37045515061dSMel Gorman 		/* Throttle until kswapd wakes the process */
37055515061dSMel Gorman 		wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3706c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat));
370750694c28SMel Gorman 
370850694c28SMel Gorman 	if (fatal_signal_pending(current))
370950694c28SMel Gorman 		return true;
371050694c28SMel Gorman 
371150694c28SMel Gorman out:
371250694c28SMel Gorman 	return false;
37135515061dSMel Gorman }
37145515061dSMel Gorman 
3715dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3716327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
371766e1707bSBalbir Singh {
371833906bc5SMel Gorman 	unsigned long nr_reclaimed;
371966e1707bSBalbir Singh 	struct scan_control sc = {
372022fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3721f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3722b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
3723ee814fe2SJohannes Weiner 		.order = order,
3724ee814fe2SJohannes Weiner 		.nodemask = nodemask,
3725ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
3726ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3727a6dc60f8SJohannes Weiner 		.may_unmap = 1,
37282e2e4259SKOSAKI Motohiro 		.may_swap = 1,
372966e1707bSBalbir Singh 	};
373066e1707bSBalbir Singh 
37315515061dSMel Gorman 	/*
3732bb451fdfSGreg Thelen 	 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3733bb451fdfSGreg Thelen 	 * Confirm they are large enough for max values.
3734bb451fdfSGreg Thelen 	 */
3735bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3736bb451fdfSGreg Thelen 	BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3737bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3738bb451fdfSGreg Thelen 
3739bb451fdfSGreg Thelen 	/*
374050694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
374150694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
374250694c28SMel Gorman 	 * point.
37435515061dSMel Gorman 	 */
3744f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
37455515061dSMel Gorman 		return 1;
37465515061dSMel Gorman 
37471732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
37483481c37fSYafang Shao 	trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
374933906bc5SMel Gorman 
37503115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
375133906bc5SMel Gorman 
375233906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
37531732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
375433906bc5SMel Gorman 
375533906bc5SMel Gorman 	return nr_reclaimed;
375666e1707bSBalbir Singh }
375766e1707bSBalbir Singh 
3758c255a458SAndrew Morton #ifdef CONFIG_MEMCG
375966e1707bSBalbir Singh 
3760d2e5fb92SMichal Hocko /* Only used by soft limit reclaim. Do not reuse for anything else. */
3761a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
37624e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
3763ef8f2327SMel Gorman 						pg_data_t *pgdat,
37640ae5e89cSYing Han 						unsigned long *nr_scanned)
37654e416953SBalbir Singh {
3766afaf07a6SJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
37674e416953SBalbir Singh 	struct scan_control sc = {
3768b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3769ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
37704e416953SBalbir Singh 		.may_writepage = !laptop_mode,
37714e416953SBalbir Singh 		.may_unmap = 1,
3772b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
37734e416953SBalbir Singh 		.may_swap = !noswap,
37744e416953SBalbir Singh 	};
37750ae5e89cSYing Han 
3776d2e5fb92SMichal Hocko 	WARN_ON_ONCE(!current->reclaim_state);
3777d2e5fb92SMichal Hocko 
37784e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
37794e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3780bdce6d9eSKOSAKI Motohiro 
37819e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
37823481c37fSYafang Shao 						      sc.gfp_mask);
3783bdce6d9eSKOSAKI Motohiro 
37844e416953SBalbir Singh 	/*
37854e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
37864e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3787a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
37884e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
37894e416953SBalbir Singh 	 * the priority and make it zero.
37904e416953SBalbir Singh 	 */
3791afaf07a6SJohannes Weiner 	shrink_lruvec(lruvec, &sc);
3792bdce6d9eSKOSAKI Motohiro 
3793bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3794bdce6d9eSKOSAKI Motohiro 
37950ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
37960308f7cfSYafang Shao 
37974e416953SBalbir Singh 	return sc.nr_reclaimed;
37984e416953SBalbir Singh }
37994e416953SBalbir Singh 
380072835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3801b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
38028c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3803b70a2a21SJohannes Weiner 					   bool may_swap)
380466e1707bSBalbir Singh {
3805bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3806499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
380766e1707bSBalbir Singh 	struct scan_control sc = {
3808b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
38097dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3810ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3811b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3812ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3813ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
381466e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3815a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3816b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3817a09ed5e0SYing Han 	};
3818fa40d1eeSShakeel Butt 	/*
3819fa40d1eeSShakeel Butt 	 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
3820fa40d1eeSShakeel Butt 	 * equal pressure on all the nodes. This is based on the assumption that
3821fa40d1eeSShakeel Butt 	 * the reclaim does not bail out early.
3822fa40d1eeSShakeel Butt 	 */
3823fa40d1eeSShakeel Butt 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
382466e1707bSBalbir Singh 
38251732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
38263481c37fSYafang Shao 	trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
3827499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3828eb414681SJohannes Weiner 
38293115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3830eb414681SJohannes Weiner 
3831499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3832bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
38331732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3834bdce6d9eSKOSAKI Motohiro 
3835bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
383666e1707bSBalbir Singh }
383766e1707bSBalbir Singh #endif
383866e1707bSBalbir Singh 
38391d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3840ef8f2327SMel Gorman 				struct scan_control *sc)
3841f16015fbSJohannes Weiner {
3842b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3843b91ac374SJohannes Weiner 	struct lruvec *lruvec;
3844b95a2f2dSJohannes Weiner 
38452f368a9fSDave Hansen 	if (!can_age_anon_pages(pgdat, sc))
3846b95a2f2dSJohannes Weiner 		return;
3847b95a2f2dSJohannes Weiner 
3848b91ac374SJohannes Weiner 	lruvec = mem_cgroup_lruvec(NULL, pgdat);
3849b91ac374SJohannes Weiner 	if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
3850b91ac374SJohannes Weiner 		return;
3851b91ac374SJohannes Weiner 
3852b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3853b95a2f2dSJohannes Weiner 	do {
3854b91ac374SJohannes Weiner 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
38551a93be0eSKonstantin Khlebnikov 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
38569e3b2f8cSKonstantin Khlebnikov 				   sc, LRU_ACTIVE_ANON);
3857b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3858b95a2f2dSJohannes Weiner 	} while (memcg);
3859f16015fbSJohannes Weiner }
3860f16015fbSJohannes Weiner 
386197a225e6SJoonsoo Kim static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
38621c30844dSMel Gorman {
38631c30844dSMel Gorman 	int i;
38641c30844dSMel Gorman 	struct zone *zone;
38651c30844dSMel Gorman 
38661c30844dSMel Gorman 	/*
38671c30844dSMel Gorman 	 * Check for watermark boosts top-down as the higher zones
38681c30844dSMel Gorman 	 * are more likely to be boosted. Both watermarks and boosts
38691eba09c1SRandy Dunlap 	 * should not be checked at the same time as reclaim would
38701c30844dSMel Gorman 	 * start prematurely when there is no boosting and a lower
38711c30844dSMel Gorman 	 * zone is balanced.
38721c30844dSMel Gorman 	 */
387397a225e6SJoonsoo Kim 	for (i = highest_zoneidx; i >= 0; i--) {
38741c30844dSMel Gorman 		zone = pgdat->node_zones + i;
38751c30844dSMel Gorman 		if (!managed_zone(zone))
38761c30844dSMel Gorman 			continue;
38771c30844dSMel Gorman 
38781c30844dSMel Gorman 		if (zone->watermark_boost)
38791c30844dSMel Gorman 			return true;
38801c30844dSMel Gorman 	}
38811c30844dSMel Gorman 
38821c30844dSMel Gorman 	return false;
38831c30844dSMel Gorman }
38841c30844dSMel Gorman 
3885e716f2ebSMel Gorman /*
3886e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
388797a225e6SJoonsoo Kim  * and highest_zoneidx
3888e716f2ebSMel Gorman  */
388997a225e6SJoonsoo Kim static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
389060cefed4SJohannes Weiner {
3891e716f2ebSMel Gorman 	int i;
3892e716f2ebSMel Gorman 	unsigned long mark = -1;
3893e716f2ebSMel Gorman 	struct zone *zone;
389460cefed4SJohannes Weiner 
38951c30844dSMel Gorman 	/*
38961c30844dSMel Gorman 	 * Check watermarks bottom-up as lower zones are more likely to
38971c30844dSMel Gorman 	 * meet watermarks.
38981c30844dSMel Gorman 	 */
389997a225e6SJoonsoo Kim 	for (i = 0; i <= highest_zoneidx; i++) {
3900e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
39016256c6b4SMel Gorman 
3902e716f2ebSMel Gorman 		if (!managed_zone(zone))
3903e716f2ebSMel Gorman 			continue;
3904e716f2ebSMel Gorman 
3905e716f2ebSMel Gorman 		mark = high_wmark_pages(zone);
390697a225e6SJoonsoo Kim 		if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
39076256c6b4SMel Gorman 			return true;
390860cefed4SJohannes Weiner 	}
390960cefed4SJohannes Weiner 
3910e716f2ebSMel Gorman 	/*
391197a225e6SJoonsoo Kim 	 * If a node has no populated zone within highest_zoneidx, it does not
3912e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3913e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3914e716f2ebSMel Gorman 	 */
3915e716f2ebSMel Gorman 	if (mark == -1)
3916e716f2ebSMel Gorman 		return true;
3917e716f2ebSMel Gorman 
3918e716f2ebSMel Gorman 	return false;
3919e716f2ebSMel Gorman }
3920e716f2ebSMel Gorman 
3921631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
3922631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
3923631b6e08SMel Gorman {
39241b05117dSJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
39251b05117dSJohannes Weiner 
39261b05117dSJohannes Weiner 	clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3927631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
3928631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3929631b6e08SMel Gorman }
3930631b6e08SMel Gorman 
39311741c877SMel Gorman /*
39325515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
39335515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
39345515061dSMel Gorman  *
39355515061dSMel Gorman  * Returns true if kswapd is ready to sleep
39365515061dSMel Gorman  */
393797a225e6SJoonsoo Kim static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
393897a225e6SJoonsoo Kim 				int highest_zoneidx)
3939f50de2d3SMel Gorman {
39405515061dSMel Gorman 	/*
39419e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3942c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
39439e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
39449e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
39459e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
39469e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
39479e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
39489e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
39499e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
39509e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
39519e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
39525515061dSMel Gorman 	 */
39539e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
39549e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3955f50de2d3SMel Gorman 
3956c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3957c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3958c73322d0SJohannes Weiner 		return true;
3959c73322d0SJohannes Weiner 
396097a225e6SJoonsoo Kim 	if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
3961631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
3962333b0a45SShantanu Goel 		return true;
39631d82de61SMel Gorman 	}
39641d82de61SMel Gorman 
3965333b0a45SShantanu Goel 	return false;
3966f50de2d3SMel Gorman }
3967f50de2d3SMel Gorman 
39681da177e4SLinus Torvalds /*
39691d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
39701d82de61SMel Gorman  * zone that is currently unbalanced.
3971b8e83b94SMel Gorman  *
3972b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3973283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3974283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
397575485363SMel Gorman  */
39761d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3977accf6242SVlastimil Babka 			       struct scan_control *sc)
397875485363SMel Gorman {
39791d82de61SMel Gorman 	struct zone *zone;
39801d82de61SMel Gorman 	int z;
398175485363SMel Gorman 
39821d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
39831d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3984970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
39851d82de61SMel Gorman 		zone = pgdat->node_zones + z;
39866aa303deSMel Gorman 		if (!managed_zone(zone))
39871d82de61SMel Gorman 			continue;
39887c954f6dSMel Gorman 
39891d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
39907c954f6dSMel Gorman 	}
39917c954f6dSMel Gorman 
39921d82de61SMel Gorman 	/*
39931d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
39941d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
39951d82de61SMel Gorman 	 */
3996970a39a3SMel Gorman 	shrink_node(pgdat, sc);
39971d82de61SMel Gorman 
39981d82de61SMel Gorman 	/*
39991d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
40001d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
40011d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
40021d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
40031d82de61SMel Gorman 	 * can direct reclaim/compact.
40041d82de61SMel Gorman 	 */
40059861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
40061d82de61SMel Gorman 		sc->order = 0;
40071d82de61SMel Gorman 
4008b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
400975485363SMel Gorman }
401075485363SMel Gorman 
4011c49c2c47SMel Gorman /* Page allocator PCP high watermark is lowered if reclaim is active. */
4012c49c2c47SMel Gorman static inline void
4013c49c2c47SMel Gorman update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
4014c49c2c47SMel Gorman {
4015c49c2c47SMel Gorman 	int i;
4016c49c2c47SMel Gorman 	struct zone *zone;
4017c49c2c47SMel Gorman 
4018c49c2c47SMel Gorman 	for (i = 0; i <= highest_zoneidx; i++) {
4019c49c2c47SMel Gorman 		zone = pgdat->node_zones + i;
4020c49c2c47SMel Gorman 
4021c49c2c47SMel Gorman 		if (!managed_zone(zone))
4022c49c2c47SMel Gorman 			continue;
4023c49c2c47SMel Gorman 
4024c49c2c47SMel Gorman 		if (active)
4025c49c2c47SMel Gorman 			set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
4026c49c2c47SMel Gorman 		else
4027c49c2c47SMel Gorman 			clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
4028c49c2c47SMel Gorman 	}
4029c49c2c47SMel Gorman }
4030c49c2c47SMel Gorman 
4031c49c2c47SMel Gorman static inline void
4032c49c2c47SMel Gorman set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
4033c49c2c47SMel Gorman {
4034c49c2c47SMel Gorman 	update_reclaim_active(pgdat, highest_zoneidx, true);
4035c49c2c47SMel Gorman }
4036c49c2c47SMel Gorman 
4037c49c2c47SMel Gorman static inline void
4038c49c2c47SMel Gorman clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
4039c49c2c47SMel Gorman {
4040c49c2c47SMel Gorman 	update_reclaim_active(pgdat, highest_zoneidx, false);
4041c49c2c47SMel Gorman }
4042c49c2c47SMel Gorman 
404375485363SMel Gorman /*
40441d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
40451d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
40461d82de61SMel Gorman  * balanced.
40471da177e4SLinus Torvalds  *
40481d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
40491da177e4SLinus Torvalds  *
40501da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
405141858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
40528bb4e7a2SWei Yang  * found to have free_pages <= high_wmark_pages(zone), any page in that zone
40531d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
40541d82de61SMel Gorman  * balanced.
40551da177e4SLinus Torvalds  */
405697a225e6SJoonsoo Kim static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
40571da177e4SLinus Torvalds {
40581da177e4SLinus Torvalds 	int i;
40590608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
40600608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
4061eb414681SJohannes Weiner 	unsigned long pflags;
40621c30844dSMel Gorman 	unsigned long nr_boost_reclaim;
40631c30844dSMel Gorman 	unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
40641c30844dSMel Gorman 	bool boosted;
40651d82de61SMel Gorman 	struct zone *zone;
4066179e9639SAndrew Morton 	struct scan_control sc = {
4067179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
4068ee814fe2SJohannes Weiner 		.order = order,
4069a6dc60f8SJohannes Weiner 		.may_unmap = 1,
4070179e9639SAndrew Morton 	};
407193781325SOmar Sandoval 
40721732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
4073eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
40744f3eaf45SMatthew Wilcox (Oracle) 	__fs_reclaim_acquire(_THIS_IP_);
407593781325SOmar Sandoval 
4076f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
40771da177e4SLinus Torvalds 
40781c30844dSMel Gorman 	/*
40791c30844dSMel Gorman 	 * Account for the reclaim boost. Note that the zone boost is left in
40801c30844dSMel Gorman 	 * place so that parallel allocations that are near the watermark will
40811c30844dSMel Gorman 	 * stall or direct reclaim until kswapd is finished.
40821c30844dSMel Gorman 	 */
40831c30844dSMel Gorman 	nr_boost_reclaim = 0;
408497a225e6SJoonsoo Kim 	for (i = 0; i <= highest_zoneidx; i++) {
40851c30844dSMel Gorman 		zone = pgdat->node_zones + i;
40861c30844dSMel Gorman 		if (!managed_zone(zone))
40871c30844dSMel Gorman 			continue;
40881c30844dSMel Gorman 
40891c30844dSMel Gorman 		nr_boost_reclaim += zone->watermark_boost;
40901c30844dSMel Gorman 		zone_boosts[i] = zone->watermark_boost;
40911c30844dSMel Gorman 	}
40921c30844dSMel Gorman 	boosted = nr_boost_reclaim;
40931c30844dSMel Gorman 
40941c30844dSMel Gorman restart:
4095c49c2c47SMel Gorman 	set_reclaim_active(pgdat, highest_zoneidx);
40961c30844dSMel Gorman 	sc.priority = DEF_PRIORITY;
40979e3b2f8cSKonstantin Khlebnikov 	do {
4098c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
4099b8e83b94SMel Gorman 		bool raise_priority = true;
41001c30844dSMel Gorman 		bool balanced;
410193781325SOmar Sandoval 		bool ret;
4102b8e83b94SMel Gorman 
410397a225e6SJoonsoo Kim 		sc.reclaim_idx = highest_zoneidx;
41041da177e4SLinus Torvalds 
410586c79f6bSMel Gorman 		/*
410684c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
410784c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
410884c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
410984c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
411084c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
411184c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
411284c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
411384c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
411486c79f6bSMel Gorman 		 */
411586c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
411686c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
411786c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
41186aa303deSMel Gorman 				if (!managed_zone(zone))
411986c79f6bSMel Gorman 					continue;
412086c79f6bSMel Gorman 
4121970a39a3SMel Gorman 				sc.reclaim_idx = i;
412286c79f6bSMel Gorman 				break;
412386c79f6bSMel Gorman 			}
412486c79f6bSMel Gorman 		}
412586c79f6bSMel Gorman 
412686c79f6bSMel Gorman 		/*
41271c30844dSMel Gorman 		 * If the pgdat is imbalanced then ignore boosting and preserve
41281c30844dSMel Gorman 		 * the watermarks for a later time and restart. Note that the
41291c30844dSMel Gorman 		 * zone watermarks will be still reset at the end of balancing
41301c30844dSMel Gorman 		 * on the grounds that the normal reclaim should be enough to
41311c30844dSMel Gorman 		 * re-evaluate if boosting is required when kswapd next wakes.
413286c79f6bSMel Gorman 		 */
413397a225e6SJoonsoo Kim 		balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
41341c30844dSMel Gorman 		if (!balanced && nr_boost_reclaim) {
41351c30844dSMel Gorman 			nr_boost_reclaim = 0;
41361c30844dSMel Gorman 			goto restart;
41371c30844dSMel Gorman 		}
41381c30844dSMel Gorman 
41391c30844dSMel Gorman 		/*
41401c30844dSMel Gorman 		 * If boosting is not active then only reclaim if there are no
41411c30844dSMel Gorman 		 * eligible zones. Note that sc.reclaim_idx is not used as
41421c30844dSMel Gorman 		 * buffer_heads_over_limit may have adjusted it.
41431c30844dSMel Gorman 		 */
41441c30844dSMel Gorman 		if (!nr_boost_reclaim && balanced)
41451da177e4SLinus Torvalds 			goto out;
4146e1dbeda6SAndrew Morton 
41471c30844dSMel Gorman 		/* Limit the priority of boosting to avoid reclaim writeback */
41481c30844dSMel Gorman 		if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
41491c30844dSMel Gorman 			raise_priority = false;
41501c30844dSMel Gorman 
41511c30844dSMel Gorman 		/*
41521c30844dSMel Gorman 		 * Do not writeback or swap pages for boosted reclaim. The
41531c30844dSMel Gorman 		 * intent is to relieve pressure not issue sub-optimal IO
41541c30844dSMel Gorman 		 * from reclaim context. If no pages are reclaimed, the
41551c30844dSMel Gorman 		 * reclaim will be aborted.
41561c30844dSMel Gorman 		 */
41571c30844dSMel Gorman 		sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
41581c30844dSMel Gorman 		sc.may_swap = !nr_boost_reclaim;
41591c30844dSMel Gorman 
41601da177e4SLinus Torvalds 		/*
41611d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
41621d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
41631d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
41641d82de61SMel Gorman 		 * about consistent aging.
41651d82de61SMel Gorman 		 */
4166ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
41671d82de61SMel Gorman 
41681d82de61SMel Gorman 		/*
4169b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
4170b7ea3c41SMel Gorman 		 * even in laptop mode.
4171b7ea3c41SMel Gorman 		 */
4172047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
4173b7ea3c41SMel Gorman 			sc.may_writepage = 1;
4174b7ea3c41SMel Gorman 
41751d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
41761da177e4SLinus Torvalds 		sc.nr_scanned = 0;
41770608f43dSAndrew Morton 		nr_soft_scanned = 0;
4178ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
41791d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
41800608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
41810608f43dSAndrew Morton 
418232a4330dSRik van Riel 		/*
41831d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
41841d82de61SMel Gorman 		 * enough pages are already being scanned that that high
41851d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
418632a4330dSRik van Riel 		 */
4187970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
4188b8e83b94SMel Gorman 			raise_priority = false;
4189d7868daeSMel Gorman 
41905515061dSMel Gorman 		/*
41915515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
41925515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
41935515061dSMel Gorman 		 * able to safely make forward progress. Wake them
41945515061dSMel Gorman 		 */
41955515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
4196c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
4197cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
41985515061dSMel Gorman 
4199b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
42004f3eaf45SMatthew Wilcox (Oracle) 		__fs_reclaim_release(_THIS_IP_);
420193781325SOmar Sandoval 		ret = try_to_freeze();
42024f3eaf45SMatthew Wilcox (Oracle) 		__fs_reclaim_acquire(_THIS_IP_);
420393781325SOmar Sandoval 		if (ret || kthread_should_stop())
4204b8e83b94SMel Gorman 			break;
4205b8e83b94SMel Gorman 
4206b8e83b94SMel Gorman 		/*
4207b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
4208b8e83b94SMel Gorman 		 * progress in reclaiming pages
4209b8e83b94SMel Gorman 		 */
4210c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
42111c30844dSMel Gorman 		nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
42121c30844dSMel Gorman 
42131c30844dSMel Gorman 		/*
42141c30844dSMel Gorman 		 * If reclaim made no progress for a boost, stop reclaim as
42151c30844dSMel Gorman 		 * IO cannot be queued and it could be an infinite loop in
42161c30844dSMel Gorman 		 * extreme circumstances.
42171c30844dSMel Gorman 		 */
42181c30844dSMel Gorman 		if (nr_boost_reclaim && !nr_reclaimed)
42191c30844dSMel Gorman 			break;
42201c30844dSMel Gorman 
4221c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
4222b8e83b94SMel Gorman 			sc.priority--;
42231d82de61SMel Gorman 	} while (sc.priority >= 1);
42241da177e4SLinus Torvalds 
4225c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
4226c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
4227c73322d0SJohannes Weiner 
4228b8e83b94SMel Gorman out:
4229c49c2c47SMel Gorman 	clear_reclaim_active(pgdat, highest_zoneidx);
4230c49c2c47SMel Gorman 
42311c30844dSMel Gorman 	/* If reclaim was boosted, account for the reclaim done in this pass */
42321c30844dSMel Gorman 	if (boosted) {
42331c30844dSMel Gorman 		unsigned long flags;
42341c30844dSMel Gorman 
423597a225e6SJoonsoo Kim 		for (i = 0; i <= highest_zoneidx; i++) {
42361c30844dSMel Gorman 			if (!zone_boosts[i])
42371c30844dSMel Gorman 				continue;
42381c30844dSMel Gorman 
42391c30844dSMel Gorman 			/* Increments are under the zone lock */
42401c30844dSMel Gorman 			zone = pgdat->node_zones + i;
42411c30844dSMel Gorman 			spin_lock_irqsave(&zone->lock, flags);
42421c30844dSMel Gorman 			zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
42431c30844dSMel Gorman 			spin_unlock_irqrestore(&zone->lock, flags);
42441c30844dSMel Gorman 		}
42451c30844dSMel Gorman 
42461c30844dSMel Gorman 		/*
42471c30844dSMel Gorman 		 * As there is now likely space, wakeup kcompact to defragment
42481c30844dSMel Gorman 		 * pageblocks.
42491c30844dSMel Gorman 		 */
425097a225e6SJoonsoo Kim 		wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
42511c30844dSMel Gorman 	}
42521c30844dSMel Gorman 
42532a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
42544f3eaf45SMatthew Wilcox (Oracle) 	__fs_reclaim_release(_THIS_IP_);
4255eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
42561732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
4257e5ca8071SYafang Shao 
42580abdee2bSMel Gorman 	/*
42591d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
42601d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
42611d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
42621d82de61SMel Gorman 	 * remain at the higher level.
42630abdee2bSMel Gorman 	 */
42641d82de61SMel Gorman 	return sc.order;
42651da177e4SLinus Torvalds }
42661da177e4SLinus Torvalds 
4267e716f2ebSMel Gorman /*
426897a225e6SJoonsoo Kim  * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
426997a225e6SJoonsoo Kim  * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
427097a225e6SJoonsoo Kim  * not a valid index then either kswapd runs for first time or kswapd couldn't
427197a225e6SJoonsoo Kim  * sleep after previous reclaim attempt (node is still unbalanced). In that
427297a225e6SJoonsoo Kim  * case return the zone index of the previous kswapd reclaim cycle.
4273e716f2ebSMel Gorman  */
427497a225e6SJoonsoo Kim static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
427597a225e6SJoonsoo Kim 					   enum zone_type prev_highest_zoneidx)
4276e716f2ebSMel Gorman {
427797a225e6SJoonsoo Kim 	enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
42785644e1fbSQian Cai 
427997a225e6SJoonsoo Kim 	return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
4280e716f2ebSMel Gorman }
4281e716f2ebSMel Gorman 
428238087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
428397a225e6SJoonsoo Kim 				unsigned int highest_zoneidx)
4284f0bc0a60SKOSAKI Motohiro {
4285f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
4286f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
4287f0bc0a60SKOSAKI Motohiro 
4288f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
4289f0bc0a60SKOSAKI Motohiro 		return;
4290f0bc0a60SKOSAKI Motohiro 
4291f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
4292f0bc0a60SKOSAKI Motohiro 
4293333b0a45SShantanu Goel 	/*
4294333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
4295333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
4296333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
4297333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
4298333b0a45SShantanu Goel 	 * succeed.
4299333b0a45SShantanu Goel 	 */
430097a225e6SJoonsoo Kim 	if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
4301fd901c95SVlastimil Babka 		/*
4302fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
4303fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
4304fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
4305fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
4306fd901c95SVlastimil Babka 		 */
4307fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
4308fd901c95SVlastimil Babka 
4309fd901c95SVlastimil Babka 		/*
4310fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
4311fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
4312fd901c95SVlastimil Babka 		 */
431397a225e6SJoonsoo Kim 		wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
4314fd901c95SVlastimil Babka 
4315f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
431638087d9bSMel Gorman 
431738087d9bSMel Gorman 		/*
431897a225e6SJoonsoo Kim 		 * If woken prematurely then reset kswapd_highest_zoneidx and
431938087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
432038087d9bSMel Gorman 		 * the previous request that slept prematurely.
432138087d9bSMel Gorman 		 */
432238087d9bSMel Gorman 		if (remaining) {
432397a225e6SJoonsoo Kim 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
432497a225e6SJoonsoo Kim 					kswapd_highest_zoneidx(pgdat,
432597a225e6SJoonsoo Kim 							highest_zoneidx));
43265644e1fbSQian Cai 
43275644e1fbSQian Cai 			if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
43285644e1fbSQian Cai 				WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
432938087d9bSMel Gorman 		}
433038087d9bSMel Gorman 
4331f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
4332f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
4333f0bc0a60SKOSAKI Motohiro 	}
4334f0bc0a60SKOSAKI Motohiro 
4335f0bc0a60SKOSAKI Motohiro 	/*
4336f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
4337f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
4338f0bc0a60SKOSAKI Motohiro 	 */
4339d9f21d42SMel Gorman 	if (!remaining &&
434097a225e6SJoonsoo Kim 	    prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
4341f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
4342f0bc0a60SKOSAKI Motohiro 
4343f0bc0a60SKOSAKI Motohiro 		/*
4344f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
4345f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
4346f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
4347f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
4348f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
4349f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
4350f0bc0a60SKOSAKI Motohiro 		 */
4351f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
43521c7e7f6cSAaditya Kumar 
43531c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
4354f0bc0a60SKOSAKI Motohiro 			schedule();
43551c7e7f6cSAaditya Kumar 
4356f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
4357f0bc0a60SKOSAKI Motohiro 	} else {
4358f0bc0a60SKOSAKI Motohiro 		if (remaining)
4359f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
4360f0bc0a60SKOSAKI Motohiro 		else
4361f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
4362f0bc0a60SKOSAKI Motohiro 	}
4363f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
4364f0bc0a60SKOSAKI Motohiro }
4365f0bc0a60SKOSAKI Motohiro 
43661da177e4SLinus Torvalds /*
43671da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
43681da177e4SLinus Torvalds  * from the init process.
43691da177e4SLinus Torvalds  *
43701da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
43711da177e4SLinus Torvalds  * free memory available even if there is no other activity
43721da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
43731da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
43741da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
43751da177e4SLinus Torvalds  *
43761da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
43771da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
43781da177e4SLinus Torvalds  */
43791da177e4SLinus Torvalds static int kswapd(void *p)
43801da177e4SLinus Torvalds {
4381e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
438297a225e6SJoonsoo Kim 	unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
43831da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t *)p;
43841da177e4SLinus Torvalds 	struct task_struct *tsk = current;
4385a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
43861da177e4SLinus Torvalds 
4387174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
4388c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
43891da177e4SLinus Torvalds 
43901da177e4SLinus Torvalds 	/*
43911da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
43921da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
43931da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
43941da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
43951da177e4SLinus Torvalds 	 *
43961da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
43971da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
43981da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
43991da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
44001da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
44011da177e4SLinus Torvalds 	 */
4402930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
440383144186SRafael J. Wysocki 	set_freezable();
44041da177e4SLinus Torvalds 
44055644e1fbSQian Cai 	WRITE_ONCE(pgdat->kswapd_order, 0);
440697a225e6SJoonsoo Kim 	WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
44078cd7c588SMel Gorman 	atomic_set(&pgdat->nr_writeback_throttled, 0);
44081da177e4SLinus Torvalds 	for ( ; ; ) {
44096f6313d4SJeff Liu 		bool ret;
44103e1d1d28SChristoph Lameter 
44115644e1fbSQian Cai 		alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
441297a225e6SJoonsoo Kim 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
441397a225e6SJoonsoo Kim 							highest_zoneidx);
4414e716f2ebSMel Gorman 
441538087d9bSMel Gorman kswapd_try_sleep:
441638087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
441797a225e6SJoonsoo Kim 					highest_zoneidx);
4418215ddd66SMel Gorman 
441997a225e6SJoonsoo Kim 		/* Read the new order and highest_zoneidx */
44202b47a24cSLukas Bulwahn 		alloc_order = READ_ONCE(pgdat->kswapd_order);
442197a225e6SJoonsoo Kim 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
442297a225e6SJoonsoo Kim 							highest_zoneidx);
44235644e1fbSQian Cai 		WRITE_ONCE(pgdat->kswapd_order, 0);
442497a225e6SJoonsoo Kim 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
44251da177e4SLinus Torvalds 
44268fe23e05SDavid Rientjes 		ret = try_to_freeze();
44278fe23e05SDavid Rientjes 		if (kthread_should_stop())
44288fe23e05SDavid Rientjes 			break;
44298fe23e05SDavid Rientjes 
44308fe23e05SDavid Rientjes 		/*
44318fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
44328fe23e05SDavid Rientjes 		 * after returning from the refrigerator
4433b1296cc4SRafael J. Wysocki 		 */
443438087d9bSMel Gorman 		if (ret)
443538087d9bSMel Gorman 			continue;
44361d82de61SMel Gorman 
443738087d9bSMel Gorman 		/*
443838087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
443938087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
444038087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
444138087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
444238087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
444338087d9bSMel Gorman 		 * request (alloc_order).
444438087d9bSMel Gorman 		 */
444597a225e6SJoonsoo Kim 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
4446e5146b12SMel Gorman 						alloc_order);
444797a225e6SJoonsoo Kim 		reclaim_order = balance_pgdat(pgdat, alloc_order,
444897a225e6SJoonsoo Kim 						highest_zoneidx);
444938087d9bSMel Gorman 		if (reclaim_order < alloc_order)
445038087d9bSMel Gorman 			goto kswapd_try_sleep;
445133906bc5SMel Gorman 	}
4452b0a8cc58STakamori Yamaguchi 
445371abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
445471abdc15SJohannes Weiner 
44551da177e4SLinus Torvalds 	return 0;
44561da177e4SLinus Torvalds }
44571da177e4SLinus Torvalds 
44581da177e4SLinus Torvalds /*
44595ecd9d40SDavid Rientjes  * A zone is low on free memory or too fragmented for high-order memory.  If
44605ecd9d40SDavid Rientjes  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
44615ecd9d40SDavid Rientjes  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
44625ecd9d40SDavid Rientjes  * has failed or is not needed, still wake up kcompactd if only compaction is
44635ecd9d40SDavid Rientjes  * needed.
44641da177e4SLinus Torvalds  */
44655ecd9d40SDavid Rientjes void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
446697a225e6SJoonsoo Kim 		   enum zone_type highest_zoneidx)
44671da177e4SLinus Torvalds {
44681da177e4SLinus Torvalds 	pg_data_t *pgdat;
44695644e1fbSQian Cai 	enum zone_type curr_idx;
44701da177e4SLinus Torvalds 
44716aa303deSMel Gorman 	if (!managed_zone(zone))
44721da177e4SLinus Torvalds 		return;
44731da177e4SLinus Torvalds 
44745ecd9d40SDavid Rientjes 	if (!cpuset_zone_allowed(zone, gfp_flags))
44751da177e4SLinus Torvalds 		return;
4476dffcac2cSShakeel Butt 
44775644e1fbSQian Cai 	pgdat = zone->zone_pgdat;
447897a225e6SJoonsoo Kim 	curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
44795644e1fbSQian Cai 
448097a225e6SJoonsoo Kim 	if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
448197a225e6SJoonsoo Kim 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
44825644e1fbSQian Cai 
44835644e1fbSQian Cai 	if (READ_ONCE(pgdat->kswapd_order) < order)
44845644e1fbSQian Cai 		WRITE_ONCE(pgdat->kswapd_order, order);
44855644e1fbSQian Cai 
44868d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
44871da177e4SLinus Torvalds 		return;
4488e1a55637SMel Gorman 
44895ecd9d40SDavid Rientjes 	/* Hopeless node, leave it to direct reclaim if possible */
44905ecd9d40SDavid Rientjes 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
449197a225e6SJoonsoo Kim 	    (pgdat_balanced(pgdat, order, highest_zoneidx) &&
449297a225e6SJoonsoo Kim 	     !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
44935ecd9d40SDavid Rientjes 		/*
44945ecd9d40SDavid Rientjes 		 * There may be plenty of free memory available, but it's too
44955ecd9d40SDavid Rientjes 		 * fragmented for high-order allocations.  Wake up kcompactd
44965ecd9d40SDavid Rientjes 		 * and rely on compaction_suitable() to determine if it's
44975ecd9d40SDavid Rientjes 		 * needed.  If it fails, it will defer subsequent attempts to
44985ecd9d40SDavid Rientjes 		 * ratelimit its work.
44995ecd9d40SDavid Rientjes 		 */
45005ecd9d40SDavid Rientjes 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
450197a225e6SJoonsoo Kim 			wakeup_kcompactd(pgdat, order, highest_zoneidx);
4502c73322d0SJohannes Weiner 		return;
45035ecd9d40SDavid Rientjes 	}
4504c73322d0SJohannes Weiner 
450597a225e6SJoonsoo Kim 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
45065ecd9d40SDavid Rientjes 				      gfp_flags);
45078d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
45081da177e4SLinus Torvalds }
45091da177e4SLinus Torvalds 
4510c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
45111da177e4SLinus Torvalds /*
45127b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
4513d6277db4SRafael J. Wysocki  * freed pages.
4514d6277db4SRafael J. Wysocki  *
4515d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
4516d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
4517d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
45181da177e4SLinus Torvalds  */
45197b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
45201da177e4SLinus Torvalds {
4521d6277db4SRafael J. Wysocki 	struct scan_control sc = {
45227b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
4523ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
4524b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
45259e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
4526ee814fe2SJohannes Weiner 		.may_writepage = 1,
4527ee814fe2SJohannes Weiner 		.may_unmap = 1,
4528ee814fe2SJohannes Weiner 		.may_swap = 1,
4529ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
45301da177e4SLinus Torvalds 	};
45317b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
45327b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
4533499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
45341da177e4SLinus Torvalds 
4535d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
453693781325SOmar Sandoval 	noreclaim_flag = memalloc_noreclaim_save();
45371732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
4538d6277db4SRafael J. Wysocki 
45393115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4540d6277db4SRafael J. Wysocki 
45411732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
4542499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
454393781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4544d6277db4SRafael J. Wysocki 
45457b51755cSKOSAKI Motohiro 	return nr_reclaimed;
45461da177e4SLinus Torvalds }
4547c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
45481da177e4SLinus Torvalds 
45493218ae14SYasunori Goto /*
45503218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
45513218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
45523218ae14SYasunori Goto  */
4553b87c517aSMiaohe Lin void kswapd_run(int nid)
45543218ae14SYasunori Goto {
45553218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
45563218ae14SYasunori Goto 
45573218ae14SYasunori Goto 	if (pgdat->kswapd)
4558b87c517aSMiaohe Lin 		return;
45593218ae14SYasunori Goto 
45603218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
45613218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
45623218ae14SYasunori Goto 		/* failure at boot is fatal */
4563c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
4564d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
4565d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
45663218ae14SYasunori Goto 	}
45673218ae14SYasunori Goto }
45683218ae14SYasunori Goto 
45698fe23e05SDavid Rientjes /*
4570d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
4571bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
45728fe23e05SDavid Rientjes  */
45738fe23e05SDavid Rientjes void kswapd_stop(int nid)
45748fe23e05SDavid Rientjes {
45758fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
45768fe23e05SDavid Rientjes 
4577d8adde17SJiang Liu 	if (kswapd) {
45788fe23e05SDavid Rientjes 		kthread_stop(kswapd);
4579d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
4580d8adde17SJiang Liu 	}
45818fe23e05SDavid Rientjes }
45828fe23e05SDavid Rientjes 
45831da177e4SLinus Torvalds static int __init kswapd_init(void)
45841da177e4SLinus Torvalds {
45856b700b5bSWei Yang 	int nid;
458669e05944SAndrew Morton 
45871da177e4SLinus Torvalds 	swap_setup();
458848fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
45893218ae14SYasunori Goto  		kswapd_run(nid);
45901da177e4SLinus Torvalds 	return 0;
45911da177e4SLinus Torvalds }
45921da177e4SLinus Torvalds 
45931da177e4SLinus Torvalds module_init(kswapd_init)
45949eeff239SChristoph Lameter 
45959eeff239SChristoph Lameter #ifdef CONFIG_NUMA
45969eeff239SChristoph Lameter /*
4597a5f5f91dSMel Gorman  * Node reclaim mode
45989eeff239SChristoph Lameter  *
4599a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
46009eeff239SChristoph Lameter  * the watermarks.
46019eeff239SChristoph Lameter  */
4602a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
46039eeff239SChristoph Lameter 
460451998364SDave Hansen /*
4605a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
4606a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
4607a92f7126SChristoph Lameter  * a zone.
4608a92f7126SChristoph Lameter  */
4609a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
4610a92f7126SChristoph Lameter 
46119eeff239SChristoph Lameter /*
4612a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
46139614634fSChristoph Lameter  * occur.
46149614634fSChristoph Lameter  */
46159614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
46169614634fSChristoph Lameter 
46179614634fSChristoph Lameter /*
46180ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
46190ff38490SChristoph Lameter  * slab reclaim needs to occur.
46200ff38490SChristoph Lameter  */
46210ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
46220ff38490SChristoph Lameter 
462311fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
462490afa5deSMel Gorman {
462511fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
462611fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
462711fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
462890afa5deSMel Gorman 
462990afa5deSMel Gorman 	/*
463090afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
463190afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
463290afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
463390afa5deSMel Gorman 	 */
463490afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
463590afa5deSMel Gorman }
463690afa5deSMel Gorman 
463790afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4638a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
463990afa5deSMel Gorman {
4640d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
4641d031a157SAlexandru Moise 	unsigned long delta = 0;
464290afa5deSMel Gorman 
464390afa5deSMel Gorman 	/*
464495bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
464590afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
464611fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
464790afa5deSMel Gorman 	 * a better estimate
464890afa5deSMel Gorman 	 */
4649a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
4650a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
465190afa5deSMel Gorman 	else
4652a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
465390afa5deSMel Gorman 
465490afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
4655a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
4656a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
465790afa5deSMel Gorman 
465890afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
465990afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
466090afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
466190afa5deSMel Gorman 
466290afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
466390afa5deSMel Gorman }
466490afa5deSMel Gorman 
46650ff38490SChristoph Lameter /*
4666a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
46679eeff239SChristoph Lameter  */
4668a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
46699eeff239SChristoph Lameter {
46707fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
467169e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
46729eeff239SChristoph Lameter 	struct task_struct *p = current;
4673499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
4674179e9639SAndrew Morton 	struct scan_control sc = {
467562b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4676f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
4677bd2f6199SJohannes Weiner 		.order = order,
4678a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
4679a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4680a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4681ee814fe2SJohannes Weiner 		.may_swap = 1,
4682f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
4683179e9639SAndrew Morton 	};
468457f29762SJohannes Weiner 	unsigned long pflags;
46859eeff239SChristoph Lameter 
4686132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4687132bb8cfSYafang Shao 					   sc.gfp_mask);
4688132bb8cfSYafang Shao 
46899eeff239SChristoph Lameter 	cond_resched();
469057f29762SJohannes Weiner 	psi_memstall_enter(&pflags);
469193781325SOmar Sandoval 	fs_reclaim_acquire(sc.gfp_mask);
4692d4f7796eSChristoph Lameter 	/*
469395bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4694d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
469595bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
4696d4f7796eSChristoph Lameter 	 */
4697499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
4698499118e9SVlastimil Babka 	p->flags |= PF_SWAPWRITE;
46991732d2b0SAndrew Morton 	set_task_reclaim_state(p, &sc.reclaim_state);
4700c84db23cSChristoph Lameter 
4701a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
4702a92f7126SChristoph Lameter 		/*
4703894befecSAndrey Ryabinin 		 * Free memory by calling shrink node with increasing
47040ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
4705a92f7126SChristoph Lameter 		 */
4706a92f7126SChristoph Lameter 		do {
4707970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
47089e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
47090ff38490SChristoph Lameter 	}
4710a92f7126SChristoph Lameter 
47111732d2b0SAndrew Morton 	set_task_reclaim_state(p, NULL);
4712499118e9SVlastimil Babka 	current->flags &= ~PF_SWAPWRITE;
4713499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
471493781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
471557f29762SJohannes Weiner 	psi_memstall_leave(&pflags);
4716132bb8cfSYafang Shao 
4717132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4718132bb8cfSYafang Shao 
4719a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
47209eeff239SChristoph Lameter }
4721179e9639SAndrew Morton 
4722a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4723179e9639SAndrew Morton {
4724d773ed6bSDavid Rientjes 	int ret;
4725179e9639SAndrew Morton 
4726179e9639SAndrew Morton 	/*
4727a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
47280ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
472934aa1330SChristoph Lameter 	 *
47309614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
47319614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
4732a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
4733a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
47349614634fSChristoph Lameter 	 * unmapped file backed pages.
4735179e9639SAndrew Morton 	 */
4736a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4737d42f3245SRoman Gushchin 	    node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
4738d42f3245SRoman Gushchin 	    pgdat->min_slab_pages)
4739a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
4740179e9639SAndrew Morton 
4741179e9639SAndrew Morton 	/*
4742d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
4743179e9639SAndrew Morton 	 */
4744d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4745a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4746179e9639SAndrew Morton 
4747179e9639SAndrew Morton 	/*
4748a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
4749179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
4750179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
4751179e9639SAndrew Morton 	 * as wide as possible.
4752179e9639SAndrew Morton 	 */
4753a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4754a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4755d773ed6bSDavid Rientjes 
4756a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4757a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4758fa5e084eSMel Gorman 
4759a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
4760a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4761d773ed6bSDavid Rientjes 
476224cf7251SMel Gorman 	if (!ret)
476324cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
476424cf7251SMel Gorman 
4765d773ed6bSDavid Rientjes 	return ret;
4766179e9639SAndrew Morton }
47679eeff239SChristoph Lameter #endif
4768894bc310SLee Schermerhorn 
476989e004eaSLee Schermerhorn /**
477064e3d12fSKuo-Hsin Yang  * check_move_unevictable_pages - check pages for evictability and move to
477164e3d12fSKuo-Hsin Yang  * appropriate zone lru list
477264e3d12fSKuo-Hsin Yang  * @pvec: pagevec with lru pages to check
477389e004eaSLee Schermerhorn  *
477464e3d12fSKuo-Hsin Yang  * Checks pages for evictability, if an evictable page is in the unevictable
477564e3d12fSKuo-Hsin Yang  * lru list, moves it to the appropriate evictable lru list. This function
477664e3d12fSKuo-Hsin Yang  * should be only used for lru pages.
477789e004eaSLee Schermerhorn  */
477864e3d12fSKuo-Hsin Yang void check_move_unevictable_pages(struct pagevec *pvec)
477989e004eaSLee Schermerhorn {
47806168d0daSAlex Shi 	struct lruvec *lruvec = NULL;
478124513264SHugh Dickins 	int pgscanned = 0;
478224513264SHugh Dickins 	int pgrescued = 0;
478389e004eaSLee Schermerhorn 	int i;
478489e004eaSLee Schermerhorn 
478564e3d12fSKuo-Hsin Yang 	for (i = 0; i < pvec->nr; i++) {
478664e3d12fSKuo-Hsin Yang 		struct page *page = pvec->pages[i];
47878d8869caSHugh Dickins 		int nr_pages;
478889e004eaSLee Schermerhorn 
47898d8869caSHugh Dickins 		if (PageTransTail(page))
47908d8869caSHugh Dickins 			continue;
47918d8869caSHugh Dickins 
47928d8869caSHugh Dickins 		nr_pages = thp_nr_pages(page);
47938d8869caSHugh Dickins 		pgscanned += nr_pages;
47948d8869caSHugh Dickins 
4795d25b5bd8SAlex Shi 		/* block memcg migration during page moving between lru */
4796d25b5bd8SAlex Shi 		if (!TestClearPageLRU(page))
4797d25b5bd8SAlex Shi 			continue;
4798d25b5bd8SAlex Shi 
47992a5e4e34SAlexander Duyck 		lruvec = relock_page_lruvec_irq(page, lruvec);
4800d25b5bd8SAlex Shi 		if (page_evictable(page) && PageUnevictable(page)) {
480146ae6b2cSYu Zhao 			del_page_from_lru_list(page, lruvec);
480224513264SHugh Dickins 			ClearPageUnevictable(page);
48033a9c9788SYu Zhao 			add_page_to_lru_list(page, lruvec);
48048d8869caSHugh Dickins 			pgrescued += nr_pages;
480589e004eaSLee Schermerhorn 		}
4806d25b5bd8SAlex Shi 		SetPageLRU(page);
480789e004eaSLee Schermerhorn 	}
480824513264SHugh Dickins 
48096168d0daSAlex Shi 	if (lruvec) {
481024513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
481124513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
48126168d0daSAlex Shi 		unlock_page_lruvec_irq(lruvec);
4813d25b5bd8SAlex Shi 	} else if (pgscanned) {
4814d25b5bd8SAlex Shi 		count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
481524513264SHugh Dickins 	}
481685046579SHugh Dickins }
481764e3d12fSKuo-Hsin Yang EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
4818