xref: /openbmc/linux/mm/vmscan.c (revision 166e3d32276f4c9ffd290f92b9df55b255f5fed7)
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>
59c574bbe9SHuang Ying #include <linux/sched/sysctl.h>
601da177e4SLinus Torvalds 
610f8053a5SNick Piggin #include "internal.h"
62014bb1deSNeilBrown #include "swap.h"
630f8053a5SNick Piggin 
6433906bc5SMel Gorman #define CREATE_TRACE_POINTS
6533906bc5SMel Gorman #include <trace/events/vmscan.h>
6633906bc5SMel Gorman 
671da177e4SLinus Torvalds struct scan_control {
6822fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6922fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
7022fba335SKOSAKI Motohiro 
71ee814fe2SJohannes Weiner 	/*
72ee814fe2SJohannes Weiner 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
73ee814fe2SJohannes Weiner 	 * are scanned.
74ee814fe2SJohannes Weiner 	 */
75ee814fe2SJohannes Weiner 	nodemask_t	*nodemask;
769e3b2f8cSKonstantin Khlebnikov 
775f53e762SKOSAKI Motohiro 	/*
78f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
79f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
80f16015fbSJohannes Weiner 	 */
81f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
8266e1707bSBalbir Singh 
837cf111bcSJohannes Weiner 	/*
847cf111bcSJohannes Weiner 	 * Scan pressure balancing between anon and file LRUs
857cf111bcSJohannes Weiner 	 */
867cf111bcSJohannes Weiner 	unsigned long	anon_cost;
877cf111bcSJohannes Weiner 	unsigned long	file_cost;
887cf111bcSJohannes Weiner 
89b91ac374SJohannes Weiner 	/* Can active pages be deactivated as part of reclaim? */
90b91ac374SJohannes Weiner #define DEACTIVATE_ANON 1
91b91ac374SJohannes Weiner #define DEACTIVATE_FILE 2
92b91ac374SJohannes Weiner 	unsigned int may_deactivate:2;
93b91ac374SJohannes Weiner 	unsigned int force_deactivate:1;
94b91ac374SJohannes Weiner 	unsigned int skipped_deactivate:1;
95b91ac374SJohannes Weiner 
961276ad68SJohannes Weiner 	/* Writepage batching in laptop mode; RECLAIM_WRITE */
97ee814fe2SJohannes Weiner 	unsigned int may_writepage:1;
98ee814fe2SJohannes Weiner 
99ee814fe2SJohannes Weiner 	/* Can mapped pages be reclaimed? */
100ee814fe2SJohannes Weiner 	unsigned int may_unmap:1;
101ee814fe2SJohannes Weiner 
102ee814fe2SJohannes Weiner 	/* Can pages be swapped as part of reclaim? */
103ee814fe2SJohannes Weiner 	unsigned int may_swap:1;
104ee814fe2SJohannes Weiner 
105d6622f63SYisheng Xie 	/*
106f56ce412SJohannes Weiner 	 * Cgroup memory below memory.low is protected as long as we
107f56ce412SJohannes Weiner 	 * don't threaten to OOM. If any cgroup is reclaimed at
108f56ce412SJohannes Weiner 	 * reduced force or passed over entirely due to its memory.low
109f56ce412SJohannes Weiner 	 * setting (memcg_low_skipped), and nothing is reclaimed as a
110f56ce412SJohannes Weiner 	 * result, then go back for one more cycle that reclaims the protected
111f56ce412SJohannes Weiner 	 * memory (memcg_low_reclaim) to avert OOM.
112d6622f63SYisheng Xie 	 */
113d6622f63SYisheng Xie 	unsigned int memcg_low_reclaim:1;
114d6622f63SYisheng Xie 	unsigned int memcg_low_skipped:1;
115241994edSJohannes Weiner 
116ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
117ee814fe2SJohannes Weiner 
118ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
119ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
120ee814fe2SJohannes Weiner 
121b91ac374SJohannes Weiner 	/* There is easily reclaimable cold cache in the current node */
122b91ac374SJohannes Weiner 	unsigned int cache_trim_mode:1;
123b91ac374SJohannes Weiner 
12453138ceaSJohannes Weiner 	/* The file pages on the current node are dangerously low */
12553138ceaSJohannes Weiner 	unsigned int file_is_tiny:1;
12653138ceaSJohannes Weiner 
12726aa2d19SDave Hansen 	/* Always discard instead of demoting to lower tier memory */
12826aa2d19SDave Hansen 	unsigned int no_demotion:1;
12926aa2d19SDave Hansen 
130bb451fdfSGreg Thelen 	/* Allocation order */
131bb451fdfSGreg Thelen 	s8 order;
132bb451fdfSGreg Thelen 
133bb451fdfSGreg Thelen 	/* Scan (total_size >> priority) pages at once */
134bb451fdfSGreg Thelen 	s8 priority;
135bb451fdfSGreg Thelen 
136bb451fdfSGreg Thelen 	/* The highest zone to isolate pages for reclaim from */
137bb451fdfSGreg Thelen 	s8 reclaim_idx;
138bb451fdfSGreg Thelen 
139bb451fdfSGreg Thelen 	/* This context's GFP mask */
140bb451fdfSGreg Thelen 	gfp_t gfp_mask;
141bb451fdfSGreg Thelen 
142ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
143ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
144ee814fe2SJohannes Weiner 
145ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
146ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
147d108c772SAndrey Ryabinin 
148d108c772SAndrey Ryabinin 	struct {
149d108c772SAndrey Ryabinin 		unsigned int dirty;
150d108c772SAndrey Ryabinin 		unsigned int unqueued_dirty;
151d108c772SAndrey Ryabinin 		unsigned int congested;
152d108c772SAndrey Ryabinin 		unsigned int writeback;
153d108c772SAndrey Ryabinin 		unsigned int immediate;
154d108c772SAndrey Ryabinin 		unsigned int file_taken;
155d108c772SAndrey Ryabinin 		unsigned int taken;
156d108c772SAndrey Ryabinin 	} nr;
157e5ca8071SYafang Shao 
158e5ca8071SYafang Shao 	/* for recording the reclaimed slab by now */
159e5ca8071SYafang Shao 	struct reclaim_state reclaim_state;
1601da177e4SLinus Torvalds };
1611da177e4SLinus Torvalds 
1621da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
163*166e3d32SMatthew Wilcox (Oracle) #define prefetchw_prev_lru_folio(_folio, _base, _field)			\
1641da177e4SLinus Torvalds 	do {								\
165*166e3d32SMatthew Wilcox (Oracle) 		if ((_folio)->lru.prev != _base) {			\
166*166e3d32SMatthew Wilcox (Oracle) 			struct folio *prev;				\
1671da177e4SLinus Torvalds 									\
168*166e3d32SMatthew Wilcox (Oracle) 			prev = lru_to_folio(&(_folio->lru));		\
1691da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1701da177e4SLinus Torvalds 		}							\
1711da177e4SLinus Torvalds 	} while (0)
1721da177e4SLinus Torvalds #else
173*166e3d32SMatthew Wilcox (Oracle) #define prefetchw_prev_lru_folio(_folio, _base, _field) do { } while (0)
1741da177e4SLinus Torvalds #endif
1751da177e4SLinus Torvalds 
1761da177e4SLinus Torvalds /*
177c843966cSJohannes Weiner  * From 0 .. 200.  Higher means more swappy.
1781da177e4SLinus Torvalds  */
1791da177e4SLinus Torvalds int vm_swappiness = 60;
1801da177e4SLinus Torvalds 
1810a432dcbSYang Shi static void set_task_reclaim_state(struct task_struct *task,
1820a432dcbSYang Shi 				   struct reclaim_state *rs)
1830a432dcbSYang Shi {
1840a432dcbSYang Shi 	/* Check for an overwrite */
1850a432dcbSYang Shi 	WARN_ON_ONCE(rs && task->reclaim_state);
1860a432dcbSYang Shi 
1870a432dcbSYang Shi 	/* Check for the nulling of an already-nulled member */
1880a432dcbSYang Shi 	WARN_ON_ONCE(!rs && !task->reclaim_state);
1890a432dcbSYang Shi 
1900a432dcbSYang Shi 	task->reclaim_state = rs;
1910a432dcbSYang Shi }
1920a432dcbSYang Shi 
1935035ebc6SRoman Gushchin LIST_HEAD(shrinker_list);
1945035ebc6SRoman Gushchin DECLARE_RWSEM(shrinker_rwsem);
1951da177e4SLinus Torvalds 
1960a432dcbSYang Shi #ifdef CONFIG_MEMCG
197a2fb1261SYang Shi static int shrinker_nr_max;
1982bfd3637SYang Shi 
1993c6f17e6SYang Shi /* The shrinker_info is expanded in a batch of BITS_PER_LONG */
200a2fb1261SYang Shi static inline int shrinker_map_size(int nr_items)
201a2fb1261SYang Shi {
202a2fb1261SYang Shi 	return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
203a2fb1261SYang Shi }
2042bfd3637SYang Shi 
2053c6f17e6SYang Shi static inline int shrinker_defer_size(int nr_items)
2063c6f17e6SYang Shi {
2073c6f17e6SYang Shi 	return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
2083c6f17e6SYang Shi }
2093c6f17e6SYang Shi 
210468ab843SYang Shi static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
211468ab843SYang Shi 						     int nid)
212468ab843SYang Shi {
213468ab843SYang Shi 	return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
214468ab843SYang Shi 					 lockdep_is_held(&shrinker_rwsem));
215468ab843SYang Shi }
216468ab843SYang Shi 
217e4262c4fSYang Shi static int expand_one_shrinker_info(struct mem_cgroup *memcg,
2183c6f17e6SYang Shi 				    int map_size, int defer_size,
2193c6f17e6SYang Shi 				    int old_map_size, int old_defer_size)
2202bfd3637SYang Shi {
221e4262c4fSYang Shi 	struct shrinker_info *new, *old;
2222bfd3637SYang Shi 	struct mem_cgroup_per_node *pn;
2232bfd3637SYang Shi 	int nid;
2243c6f17e6SYang Shi 	int size = map_size + defer_size;
2252bfd3637SYang Shi 
2262bfd3637SYang Shi 	for_each_node(nid) {
2272bfd3637SYang Shi 		pn = memcg->nodeinfo[nid];
228468ab843SYang Shi 		old = shrinker_info_protected(memcg, nid);
2292bfd3637SYang Shi 		/* Not yet online memcg */
2302bfd3637SYang Shi 		if (!old)
2312bfd3637SYang Shi 			return 0;
2322bfd3637SYang Shi 
2332bfd3637SYang Shi 		new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
2342bfd3637SYang Shi 		if (!new)
2352bfd3637SYang Shi 			return -ENOMEM;
2362bfd3637SYang Shi 
2373c6f17e6SYang Shi 		new->nr_deferred = (atomic_long_t *)(new + 1);
2383c6f17e6SYang Shi 		new->map = (void *)new->nr_deferred + defer_size;
2393c6f17e6SYang Shi 
2403c6f17e6SYang Shi 		/* map: set all old bits, clear all new bits */
2413c6f17e6SYang Shi 		memset(new->map, (int)0xff, old_map_size);
2423c6f17e6SYang Shi 		memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
2433c6f17e6SYang Shi 		/* nr_deferred: copy old values, clear all new values */
2443c6f17e6SYang Shi 		memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
2453c6f17e6SYang Shi 		memset((void *)new->nr_deferred + old_defer_size, 0,
2463c6f17e6SYang Shi 		       defer_size - old_defer_size);
2472bfd3637SYang Shi 
248e4262c4fSYang Shi 		rcu_assign_pointer(pn->shrinker_info, new);
24972673e86SYang Shi 		kvfree_rcu(old, rcu);
2502bfd3637SYang Shi 	}
2512bfd3637SYang Shi 
2522bfd3637SYang Shi 	return 0;
2532bfd3637SYang Shi }
2542bfd3637SYang Shi 
255e4262c4fSYang Shi void free_shrinker_info(struct mem_cgroup *memcg)
2562bfd3637SYang Shi {
2572bfd3637SYang Shi 	struct mem_cgroup_per_node *pn;
258e4262c4fSYang Shi 	struct shrinker_info *info;
2592bfd3637SYang Shi 	int nid;
2602bfd3637SYang Shi 
2612bfd3637SYang Shi 	for_each_node(nid) {
2622bfd3637SYang Shi 		pn = memcg->nodeinfo[nid];
263e4262c4fSYang Shi 		info = rcu_dereference_protected(pn->shrinker_info, true);
264e4262c4fSYang Shi 		kvfree(info);
265e4262c4fSYang Shi 		rcu_assign_pointer(pn->shrinker_info, NULL);
2662bfd3637SYang Shi 	}
2672bfd3637SYang Shi }
2682bfd3637SYang Shi 
269e4262c4fSYang Shi int alloc_shrinker_info(struct mem_cgroup *memcg)
2702bfd3637SYang Shi {
271e4262c4fSYang Shi 	struct shrinker_info *info;
2722bfd3637SYang Shi 	int nid, size, ret = 0;
2733c6f17e6SYang Shi 	int map_size, defer_size = 0;
2742bfd3637SYang Shi 
275d27cf2aaSYang Shi 	down_write(&shrinker_rwsem);
2763c6f17e6SYang Shi 	map_size = shrinker_map_size(shrinker_nr_max);
2773c6f17e6SYang Shi 	defer_size = shrinker_defer_size(shrinker_nr_max);
2783c6f17e6SYang Shi 	size = map_size + defer_size;
2792bfd3637SYang Shi 	for_each_node(nid) {
280e4262c4fSYang Shi 		info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
281e4262c4fSYang Shi 		if (!info) {
282e4262c4fSYang Shi 			free_shrinker_info(memcg);
2832bfd3637SYang Shi 			ret = -ENOMEM;
2842bfd3637SYang Shi 			break;
2852bfd3637SYang Shi 		}
2863c6f17e6SYang Shi 		info->nr_deferred = (atomic_long_t *)(info + 1);
2873c6f17e6SYang Shi 		info->map = (void *)info->nr_deferred + defer_size;
288e4262c4fSYang Shi 		rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
2892bfd3637SYang Shi 	}
290d27cf2aaSYang Shi 	up_write(&shrinker_rwsem);
2912bfd3637SYang Shi 
2922bfd3637SYang Shi 	return ret;
2932bfd3637SYang Shi }
2942bfd3637SYang Shi 
2953c6f17e6SYang Shi static inline bool need_expand(int nr_max)
2963c6f17e6SYang Shi {
2973c6f17e6SYang Shi 	return round_up(nr_max, BITS_PER_LONG) >
2983c6f17e6SYang Shi 	       round_up(shrinker_nr_max, BITS_PER_LONG);
2993c6f17e6SYang Shi }
3003c6f17e6SYang Shi 
301e4262c4fSYang Shi static int expand_shrinker_info(int new_id)
3022bfd3637SYang Shi {
3033c6f17e6SYang Shi 	int ret = 0;
304a2fb1261SYang Shi 	int new_nr_max = new_id + 1;
3053c6f17e6SYang Shi 	int map_size, defer_size = 0;
3063c6f17e6SYang Shi 	int old_map_size, old_defer_size = 0;
3072bfd3637SYang Shi 	struct mem_cgroup *memcg;
3082bfd3637SYang Shi 
3093c6f17e6SYang Shi 	if (!need_expand(new_nr_max))
310a2fb1261SYang Shi 		goto out;
3112bfd3637SYang Shi 
3122bfd3637SYang Shi 	if (!root_mem_cgroup)
313d27cf2aaSYang Shi 		goto out;
314d27cf2aaSYang Shi 
315d27cf2aaSYang Shi 	lockdep_assert_held(&shrinker_rwsem);
3162bfd3637SYang Shi 
3173c6f17e6SYang Shi 	map_size = shrinker_map_size(new_nr_max);
3183c6f17e6SYang Shi 	defer_size = shrinker_defer_size(new_nr_max);
3193c6f17e6SYang Shi 	old_map_size = shrinker_map_size(shrinker_nr_max);
3203c6f17e6SYang Shi 	old_defer_size = shrinker_defer_size(shrinker_nr_max);
3213c6f17e6SYang Shi 
3222bfd3637SYang Shi 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3232bfd3637SYang Shi 	do {
3243c6f17e6SYang Shi 		ret = expand_one_shrinker_info(memcg, map_size, defer_size,
3253c6f17e6SYang Shi 					       old_map_size, old_defer_size);
3262bfd3637SYang Shi 		if (ret) {
3272bfd3637SYang Shi 			mem_cgroup_iter_break(NULL, memcg);
328d27cf2aaSYang Shi 			goto out;
3292bfd3637SYang Shi 		}
3302bfd3637SYang Shi 	} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
331d27cf2aaSYang Shi out:
3322bfd3637SYang Shi 	if (!ret)
333a2fb1261SYang Shi 		shrinker_nr_max = new_nr_max;
334d27cf2aaSYang Shi 
3352bfd3637SYang Shi 	return ret;
3362bfd3637SYang Shi }
3372bfd3637SYang Shi 
3382bfd3637SYang Shi void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
3392bfd3637SYang Shi {
3402bfd3637SYang Shi 	if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
341e4262c4fSYang Shi 		struct shrinker_info *info;
3422bfd3637SYang Shi 
3432bfd3637SYang Shi 		rcu_read_lock();
344e4262c4fSYang Shi 		info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
3452bfd3637SYang Shi 		/* Pairs with smp mb in shrink_slab() */
3462bfd3637SYang Shi 		smp_mb__before_atomic();
347e4262c4fSYang Shi 		set_bit(shrinker_id, info->map);
3482bfd3637SYang Shi 		rcu_read_unlock();
3492bfd3637SYang Shi 	}
3502bfd3637SYang Shi }
3512bfd3637SYang Shi 
352b4c2b231SKirill Tkhai static DEFINE_IDR(shrinker_idr);
353b4c2b231SKirill Tkhai 
354b4c2b231SKirill Tkhai static int prealloc_memcg_shrinker(struct shrinker *shrinker)
355b4c2b231SKirill Tkhai {
356b4c2b231SKirill Tkhai 	int id, ret = -ENOMEM;
357b4c2b231SKirill Tkhai 
358476b30a0SYang Shi 	if (mem_cgroup_disabled())
359476b30a0SYang Shi 		return -ENOSYS;
360476b30a0SYang Shi 
361b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
362b4c2b231SKirill Tkhai 	/* This may call shrinker, so it must use down_read_trylock() */
36341ca668aSYang Shi 	id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
364b4c2b231SKirill Tkhai 	if (id < 0)
365b4c2b231SKirill Tkhai 		goto unlock;
366b4c2b231SKirill Tkhai 
3670a4465d3SKirill Tkhai 	if (id >= shrinker_nr_max) {
368e4262c4fSYang Shi 		if (expand_shrinker_info(id)) {
3690a4465d3SKirill Tkhai 			idr_remove(&shrinker_idr, id);
3700a4465d3SKirill Tkhai 			goto unlock;
3710a4465d3SKirill Tkhai 		}
3720a4465d3SKirill Tkhai 	}
373b4c2b231SKirill Tkhai 	shrinker->id = id;
374b4c2b231SKirill Tkhai 	ret = 0;
375b4c2b231SKirill Tkhai unlock:
376b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
377b4c2b231SKirill Tkhai 	return ret;
378b4c2b231SKirill Tkhai }
379b4c2b231SKirill Tkhai 
380b4c2b231SKirill Tkhai static void unregister_memcg_shrinker(struct shrinker *shrinker)
381b4c2b231SKirill Tkhai {
382b4c2b231SKirill Tkhai 	int id = shrinker->id;
383b4c2b231SKirill Tkhai 
384b4c2b231SKirill Tkhai 	BUG_ON(id < 0);
385b4c2b231SKirill Tkhai 
38641ca668aSYang Shi 	lockdep_assert_held(&shrinker_rwsem);
38741ca668aSYang Shi 
388b4c2b231SKirill Tkhai 	idr_remove(&shrinker_idr, id);
389b4c2b231SKirill Tkhai }
390b4c2b231SKirill Tkhai 
39186750830SYang Shi static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
39286750830SYang Shi 				   struct mem_cgroup *memcg)
39386750830SYang Shi {
39486750830SYang Shi 	struct shrinker_info *info;
39586750830SYang Shi 
39686750830SYang Shi 	info = shrinker_info_protected(memcg, nid);
39786750830SYang Shi 	return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
39886750830SYang Shi }
39986750830SYang Shi 
40086750830SYang Shi static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
40186750830SYang Shi 				  struct mem_cgroup *memcg)
40286750830SYang Shi {
40386750830SYang Shi 	struct shrinker_info *info;
40486750830SYang Shi 
40586750830SYang Shi 	info = shrinker_info_protected(memcg, nid);
40686750830SYang Shi 	return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
40786750830SYang Shi }
40886750830SYang Shi 
409a178015cSYang Shi void reparent_shrinker_deferred(struct mem_cgroup *memcg)
410a178015cSYang Shi {
411a178015cSYang Shi 	int i, nid;
412a178015cSYang Shi 	long nr;
413a178015cSYang Shi 	struct mem_cgroup *parent;
414a178015cSYang Shi 	struct shrinker_info *child_info, *parent_info;
415a178015cSYang Shi 
416a178015cSYang Shi 	parent = parent_mem_cgroup(memcg);
417a178015cSYang Shi 	if (!parent)
418a178015cSYang Shi 		parent = root_mem_cgroup;
419a178015cSYang Shi 
420a178015cSYang Shi 	/* Prevent from concurrent shrinker_info expand */
421a178015cSYang Shi 	down_read(&shrinker_rwsem);
422a178015cSYang Shi 	for_each_node(nid) {
423a178015cSYang Shi 		child_info = shrinker_info_protected(memcg, nid);
424a178015cSYang Shi 		parent_info = shrinker_info_protected(parent, nid);
425a178015cSYang Shi 		for (i = 0; i < shrinker_nr_max; i++) {
426a178015cSYang Shi 			nr = atomic_long_read(&child_info->nr_deferred[i]);
427a178015cSYang Shi 			atomic_long_add(nr, &parent_info->nr_deferred[i]);
428a178015cSYang Shi 		}
429a178015cSYang Shi 	}
430a178015cSYang Shi 	up_read(&shrinker_rwsem);
431a178015cSYang Shi }
432a178015cSYang Shi 
433b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
43489b5fae5SJohannes Weiner {
435b5ead35eSJohannes Weiner 	return sc->target_mem_cgroup;
43689b5fae5SJohannes Weiner }
43797c9341fSTejun Heo 
43897c9341fSTejun Heo /**
439b5ead35eSJohannes Weiner  * writeback_throttling_sane - is the usual dirty throttling mechanism available?
44097c9341fSTejun Heo  * @sc: scan_control in question
44197c9341fSTejun Heo  *
44297c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
44397c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
44497c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
44597c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
44697c9341fSTejun Heo  * allocation and configurability.
44797c9341fSTejun Heo  *
44897c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
44997c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
45097c9341fSTejun Heo  */
451b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
45297c9341fSTejun Heo {
453b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
45497c9341fSTejun Heo 		return true;
45597c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
45669234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
45797c9341fSTejun Heo 		return true;
45897c9341fSTejun Heo #endif
45997c9341fSTejun Heo 	return false;
46097c9341fSTejun Heo }
46191a45470SKAMEZAWA Hiroyuki #else
4620a432dcbSYang Shi static int prealloc_memcg_shrinker(struct shrinker *shrinker)
4630a432dcbSYang Shi {
464476b30a0SYang Shi 	return -ENOSYS;
4650a432dcbSYang Shi }
4660a432dcbSYang Shi 
4670a432dcbSYang Shi static void unregister_memcg_shrinker(struct shrinker *shrinker)
4680a432dcbSYang Shi {
4690a432dcbSYang Shi }
4700a432dcbSYang Shi 
47186750830SYang Shi static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
47286750830SYang Shi 				   struct mem_cgroup *memcg)
47386750830SYang Shi {
47486750830SYang Shi 	return 0;
47586750830SYang Shi }
47686750830SYang Shi 
47786750830SYang Shi static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
47886750830SYang Shi 				  struct mem_cgroup *memcg)
47986750830SYang Shi {
48086750830SYang Shi 	return 0;
48186750830SYang Shi }
48286750830SYang Shi 
483b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
48489b5fae5SJohannes Weiner {
485b5ead35eSJohannes Weiner 	return false;
48689b5fae5SJohannes Weiner }
48797c9341fSTejun Heo 
488b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
48997c9341fSTejun Heo {
49097c9341fSTejun Heo 	return true;
49197c9341fSTejun Heo }
49291a45470SKAMEZAWA Hiroyuki #endif
49391a45470SKAMEZAWA Hiroyuki 
49486750830SYang Shi static long xchg_nr_deferred(struct shrinker *shrinker,
49586750830SYang Shi 			     struct shrink_control *sc)
49686750830SYang Shi {
49786750830SYang Shi 	int nid = sc->nid;
49886750830SYang Shi 
49986750830SYang Shi 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
50086750830SYang Shi 		nid = 0;
50186750830SYang Shi 
50286750830SYang Shi 	if (sc->memcg &&
50386750830SYang Shi 	    (shrinker->flags & SHRINKER_MEMCG_AWARE))
50486750830SYang Shi 		return xchg_nr_deferred_memcg(nid, shrinker,
50586750830SYang Shi 					      sc->memcg);
50686750830SYang Shi 
50786750830SYang Shi 	return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
50886750830SYang Shi }
50986750830SYang Shi 
51086750830SYang Shi 
51186750830SYang Shi static long add_nr_deferred(long nr, struct shrinker *shrinker,
51286750830SYang Shi 			    struct shrink_control *sc)
51386750830SYang Shi {
51486750830SYang Shi 	int nid = sc->nid;
51586750830SYang Shi 
51686750830SYang Shi 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
51786750830SYang Shi 		nid = 0;
51886750830SYang Shi 
51986750830SYang Shi 	if (sc->memcg &&
52086750830SYang Shi 	    (shrinker->flags & SHRINKER_MEMCG_AWARE))
52186750830SYang Shi 		return add_nr_deferred_memcg(nr, nid, shrinker,
52286750830SYang Shi 					     sc->memcg);
52386750830SYang Shi 
52486750830SYang Shi 	return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
52586750830SYang Shi }
52686750830SYang Shi 
52726aa2d19SDave Hansen static bool can_demote(int nid, struct scan_control *sc)
52826aa2d19SDave Hansen {
52920b51af1SHuang Ying 	if (!numa_demotion_enabled)
53020b51af1SHuang Ying 		return false;
5313f1509c5SJohannes Weiner 	if (sc && sc->no_demotion)
53226aa2d19SDave Hansen 		return false;
53326aa2d19SDave Hansen 	if (next_demotion_node(nid) == NUMA_NO_NODE)
53426aa2d19SDave Hansen 		return false;
53526aa2d19SDave Hansen 
53620b51af1SHuang Ying 	return true;
53726aa2d19SDave Hansen }
53826aa2d19SDave Hansen 
539a2a36488SKeith Busch static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
540a2a36488SKeith Busch 					  int nid,
541a2a36488SKeith Busch 					  struct scan_control *sc)
542a2a36488SKeith Busch {
543a2a36488SKeith Busch 	if (memcg == NULL) {
544a2a36488SKeith Busch 		/*
545a2a36488SKeith Busch 		 * For non-memcg reclaim, is there
546a2a36488SKeith Busch 		 * space in any swap device?
547a2a36488SKeith Busch 		 */
548a2a36488SKeith Busch 		if (get_nr_swap_pages() > 0)
549a2a36488SKeith Busch 			return true;
550a2a36488SKeith Busch 	} else {
551a2a36488SKeith Busch 		/* Is the memcg below its swap limit? */
552a2a36488SKeith Busch 		if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
553a2a36488SKeith Busch 			return true;
554a2a36488SKeith Busch 	}
555a2a36488SKeith Busch 
556a2a36488SKeith Busch 	/*
557a2a36488SKeith Busch 	 * The page can not be swapped.
558a2a36488SKeith Busch 	 *
559a2a36488SKeith Busch 	 * Can it be reclaimed from this node via demotion?
560a2a36488SKeith Busch 	 */
561a2a36488SKeith Busch 	return can_demote(nid, sc);
562a2a36488SKeith Busch }
563a2a36488SKeith Busch 
5645a1c84b4SMel Gorman /*
5655a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
5665a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
5675a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
5685a1c84b4SMel Gorman  */
5695a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
5705a1c84b4SMel Gorman {
5715a1c84b4SMel Gorman 	unsigned long nr;
5725a1c84b4SMel Gorman 
5735a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
5745a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
575a2a36488SKeith Busch 	if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
5765a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
5775a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
5785a1c84b4SMel Gorman 
5795a1c84b4SMel Gorman 	return nr;
5805a1c84b4SMel Gorman }
5815a1c84b4SMel Gorman 
582fd538803SMichal Hocko /**
583fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
584fd538803SMichal Hocko  * @lruvec: lru vector
585fd538803SMichal Hocko  * @lru: lru to use
5868b3a899aSWei Yang  * @zone_idx: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list)
587fd538803SMichal Hocko  */
5882091339dSYu Zhao static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
5892091339dSYu Zhao 				     int zone_idx)
590c9f299d9SKOSAKI Motohiro {
591de3b0150SJohannes Weiner 	unsigned long size = 0;
592fd538803SMichal Hocko 	int zid;
593a3d8e054SKOSAKI Motohiro 
5948b3a899aSWei Yang 	for (zid = 0; zid <= zone_idx; zid++) {
595fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
596fd538803SMichal Hocko 
597fd538803SMichal Hocko 		if (!managed_zone(zone))
598fd538803SMichal Hocko 			continue;
599fd538803SMichal Hocko 
600fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
601de3b0150SJohannes Weiner 			size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
602fd538803SMichal Hocko 		else
603de3b0150SJohannes Weiner 			size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
604c9f299d9SKOSAKI Motohiro 	}
605de3b0150SJohannes Weiner 	return size;
606b4536f0cSMichal Hocko }
607b4536f0cSMichal Hocko 
6081da177e4SLinus Torvalds /*
6091d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
6101da177e4SLinus Torvalds  */
611e33c267aSRoman Gushchin static int __prealloc_shrinker(struct shrinker *shrinker)
6121da177e4SLinus Torvalds {
613476b30a0SYang Shi 	unsigned int size;
614476b30a0SYang Shi 	int err;
6151d3d4437SGlauber Costa 
616476b30a0SYang Shi 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
617476b30a0SYang Shi 		err = prealloc_memcg_shrinker(shrinker);
618476b30a0SYang Shi 		if (err != -ENOSYS)
619476b30a0SYang Shi 			return err;
620476b30a0SYang Shi 
621476b30a0SYang Shi 		shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
622476b30a0SYang Shi 	}
623476b30a0SYang Shi 
624476b30a0SYang Shi 	size = sizeof(*shrinker->nr_deferred);
6251d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
6261d3d4437SGlauber Costa 		size *= nr_node_ids;
6271d3d4437SGlauber Costa 
6281d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
6291d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
6301d3d4437SGlauber Costa 		return -ENOMEM;
631b4c2b231SKirill Tkhai 
6328e04944fSTetsuo Handa 	return 0;
6338e04944fSTetsuo Handa }
6341d3d4437SGlauber Costa 
635e33c267aSRoman Gushchin #ifdef CONFIG_SHRINKER_DEBUG
636e33c267aSRoman Gushchin int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...)
637e33c267aSRoman Gushchin {
638e33c267aSRoman Gushchin 	va_list ap;
639e33c267aSRoman Gushchin 	int err;
640e33c267aSRoman Gushchin 
641e33c267aSRoman Gushchin 	va_start(ap, fmt);
642e33c267aSRoman Gushchin 	shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
643e33c267aSRoman Gushchin 	va_end(ap);
644e33c267aSRoman Gushchin 	if (!shrinker->name)
645e33c267aSRoman Gushchin 		return -ENOMEM;
646e33c267aSRoman Gushchin 
647e33c267aSRoman Gushchin 	err = __prealloc_shrinker(shrinker);
648e33c267aSRoman Gushchin 	if (err)
649e33c267aSRoman Gushchin 		kfree_const(shrinker->name);
650e33c267aSRoman Gushchin 
651e33c267aSRoman Gushchin 	return err;
652e33c267aSRoman Gushchin }
653e33c267aSRoman Gushchin #else
654e33c267aSRoman Gushchin int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...)
655e33c267aSRoman Gushchin {
656e33c267aSRoman Gushchin 	return __prealloc_shrinker(shrinker);
657e33c267aSRoman Gushchin }
658e33c267aSRoman Gushchin #endif
659e33c267aSRoman Gushchin 
6608e04944fSTetsuo Handa void free_prealloced_shrinker(struct shrinker *shrinker)
6618e04944fSTetsuo Handa {
662e33c267aSRoman Gushchin #ifdef CONFIG_SHRINKER_DEBUG
663e33c267aSRoman Gushchin 	kfree_const(shrinker->name);
664e33c267aSRoman Gushchin #endif
66541ca668aSYang Shi 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
66641ca668aSYang Shi 		down_write(&shrinker_rwsem);
667b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
66841ca668aSYang Shi 		up_write(&shrinker_rwsem);
669476b30a0SYang Shi 		return;
67041ca668aSYang Shi 	}
671b4c2b231SKirill Tkhai 
6728e04944fSTetsuo Handa 	kfree(shrinker->nr_deferred);
6738e04944fSTetsuo Handa 	shrinker->nr_deferred = NULL;
6748e04944fSTetsuo Handa }
6758e04944fSTetsuo Handa 
6768e04944fSTetsuo Handa void register_shrinker_prepared(struct shrinker *shrinker)
6778e04944fSTetsuo Handa {
6781da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
6791da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
68041ca668aSYang Shi 	shrinker->flags |= SHRINKER_REGISTERED;
6815035ebc6SRoman Gushchin 	shrinker_debugfs_add(shrinker);
6821da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
6838e04944fSTetsuo Handa }
6848e04944fSTetsuo Handa 
685e33c267aSRoman Gushchin static int __register_shrinker(struct shrinker *shrinker)
6868e04944fSTetsuo Handa {
687e33c267aSRoman Gushchin 	int err = __prealloc_shrinker(shrinker);
6888e04944fSTetsuo Handa 
6898e04944fSTetsuo Handa 	if (err)
6908e04944fSTetsuo Handa 		return err;
6918e04944fSTetsuo Handa 	register_shrinker_prepared(shrinker);
6921d3d4437SGlauber Costa 	return 0;
6931da177e4SLinus Torvalds }
694e33c267aSRoman Gushchin 
695e33c267aSRoman Gushchin #ifdef CONFIG_SHRINKER_DEBUG
696e33c267aSRoman Gushchin int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
697e33c267aSRoman Gushchin {
698e33c267aSRoman Gushchin 	va_list ap;
699e33c267aSRoman Gushchin 	int err;
700e33c267aSRoman Gushchin 
701e33c267aSRoman Gushchin 	va_start(ap, fmt);
702e33c267aSRoman Gushchin 	shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
703e33c267aSRoman Gushchin 	va_end(ap);
704e33c267aSRoman Gushchin 	if (!shrinker->name)
705e33c267aSRoman Gushchin 		return -ENOMEM;
706e33c267aSRoman Gushchin 
707e33c267aSRoman Gushchin 	err = __register_shrinker(shrinker);
708e33c267aSRoman Gushchin 	if (err)
709e33c267aSRoman Gushchin 		kfree_const(shrinker->name);
710e33c267aSRoman Gushchin 	return err;
711e33c267aSRoman Gushchin }
712e33c267aSRoman Gushchin #else
713e33c267aSRoman Gushchin int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
714e33c267aSRoman Gushchin {
715e33c267aSRoman Gushchin 	return __register_shrinker(shrinker);
716e33c267aSRoman Gushchin }
717e33c267aSRoman Gushchin #endif
7188e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
7191da177e4SLinus Torvalds 
7201da177e4SLinus Torvalds /*
7211da177e4SLinus Torvalds  * Remove one
7221da177e4SLinus Torvalds  */
7238e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
7241da177e4SLinus Torvalds {
72541ca668aSYang Shi 	if (!(shrinker->flags & SHRINKER_REGISTERED))
726bb422a73STetsuo Handa 		return;
72741ca668aSYang Shi 
7281da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
7291da177e4SLinus Torvalds 	list_del(&shrinker->list);
73041ca668aSYang Shi 	shrinker->flags &= ~SHRINKER_REGISTERED;
73141ca668aSYang Shi 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
73241ca668aSYang Shi 		unregister_memcg_shrinker(shrinker);
7335035ebc6SRoman Gushchin 	shrinker_debugfs_remove(shrinker);
7341da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
73541ca668aSYang Shi 
736ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
737bb422a73STetsuo Handa 	shrinker->nr_deferred = NULL;
7381da177e4SLinus Torvalds }
7398e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
7401da177e4SLinus Torvalds 
741880121beSChristian König /**
742880121beSChristian König  * synchronize_shrinkers - Wait for all running shrinkers to complete.
743880121beSChristian König  *
744880121beSChristian König  * This is equivalent to calling unregister_shrink() and register_shrinker(),
745880121beSChristian König  * but atomically and with less overhead. This is useful to guarantee that all
746880121beSChristian König  * shrinker invocations have seen an update, before freeing memory, similar to
747880121beSChristian König  * rcu.
748880121beSChristian König  */
749880121beSChristian König void synchronize_shrinkers(void)
750880121beSChristian König {
751880121beSChristian König 	down_write(&shrinker_rwsem);
752880121beSChristian König 	up_write(&shrinker_rwsem);
753880121beSChristian König }
754880121beSChristian König EXPORT_SYMBOL(synchronize_shrinkers);
755880121beSChristian König 
7561da177e4SLinus Torvalds #define SHRINK_BATCH 128
7571d3d4437SGlauber Costa 
758cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
7599092c71bSJosef Bacik 				    struct shrinker *shrinker, int priority)
7601da177e4SLinus Torvalds {
76124f7c6b9SDave Chinner 	unsigned long freed = 0;
7621da177e4SLinus Torvalds 	unsigned long long delta;
763635697c6SKonstantin Khlebnikov 	long total_scan;
764d5bc5fd3SVladimir Davydov 	long freeable;
765acf92b48SDave Chinner 	long nr;
766acf92b48SDave Chinner 	long new_nr;
767e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
768e9299f50SDave Chinner 					  : SHRINK_BATCH;
7695f33a080SShaohua Li 	long scanned = 0, next_deferred;
7701da177e4SLinus Torvalds 
771d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
7729b996468SKirill Tkhai 	if (freeable == 0 || freeable == SHRINK_EMPTY)
7739b996468SKirill Tkhai 		return freeable;
774635697c6SKonstantin Khlebnikov 
775acf92b48SDave Chinner 	/*
776acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
777acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
778acf92b48SDave Chinner 	 * don't also do this scanning work.
779acf92b48SDave Chinner 	 */
78086750830SYang Shi 	nr = xchg_nr_deferred(shrinker, shrinkctl);
781acf92b48SDave Chinner 
7824b85afbdSJohannes Weiner 	if (shrinker->seeks) {
7839092c71bSJosef Bacik 		delta = freeable >> priority;
7849092c71bSJosef Bacik 		delta *= 4;
7859092c71bSJosef Bacik 		do_div(delta, shrinker->seeks);
7864b85afbdSJohannes Weiner 	} else {
7874b85afbdSJohannes Weiner 		/*
7884b85afbdSJohannes Weiner 		 * These objects don't require any IO to create. Trim
7894b85afbdSJohannes Weiner 		 * them aggressively under memory pressure to keep
7904b85afbdSJohannes Weiner 		 * them from causing refetches in the IO caches.
7914b85afbdSJohannes Weiner 		 */
7924b85afbdSJohannes Weiner 		delta = freeable / 2;
7934b85afbdSJohannes Weiner 	}
794172b06c3SRoman Gushchin 
79518bb473eSYang Shi 	total_scan = nr >> priority;
796acf92b48SDave Chinner 	total_scan += delta;
79718bb473eSYang Shi 	total_scan = min(total_scan, (2 * freeable));
7981da177e4SLinus Torvalds 
79924f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
8009092c71bSJosef Bacik 				   freeable, delta, total_scan, priority);
80109576073SDave Chinner 
8020b1fb40aSVladimir Davydov 	/*
8030b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
8040b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
8050b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
8060b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
8070b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
8080b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
8090b1fb40aSVladimir Davydov 	 * batch_size.
8100b1fb40aSVladimir Davydov 	 *
8110b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
8120b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
813d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
8140b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
8150b1fb40aSVladimir Davydov 	 * possible.
8160b1fb40aSVladimir Davydov 	 */
8170b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
818d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
81924f7c6b9SDave Chinner 		unsigned long ret;
8200b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
8211da177e4SLinus Torvalds 
8220b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
823d460acb5SChris Wilson 		shrinkctl->nr_scanned = nr_to_scan;
82424f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
82524f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
8261da177e4SLinus Torvalds 			break;
82724f7c6b9SDave Chinner 		freed += ret;
82824f7c6b9SDave Chinner 
829d460acb5SChris Wilson 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
830d460acb5SChris Wilson 		total_scan -= shrinkctl->nr_scanned;
831d460acb5SChris Wilson 		scanned += shrinkctl->nr_scanned;
8321da177e4SLinus Torvalds 
8331da177e4SLinus Torvalds 		cond_resched();
8341da177e4SLinus Torvalds 	}
8351da177e4SLinus Torvalds 
83618bb473eSYang Shi 	/*
83718bb473eSYang Shi 	 * The deferred work is increased by any new work (delta) that wasn't
83818bb473eSYang Shi 	 * done, decreased by old deferred work that was done now.
83918bb473eSYang Shi 	 *
84018bb473eSYang Shi 	 * And it is capped to two times of the freeable items.
84118bb473eSYang Shi 	 */
84218bb473eSYang Shi 	next_deferred = max_t(long, (nr + delta - scanned), 0);
84318bb473eSYang Shi 	next_deferred = min(next_deferred, (2 * freeable));
84418bb473eSYang Shi 
845acf92b48SDave Chinner 	/*
846acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
84786750830SYang Shi 	 * manner that handles concurrent updates.
848acf92b48SDave Chinner 	 */
84986750830SYang Shi 	new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
850acf92b48SDave Chinner 
8518efb4b59SYang Shi 	trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
8521d3d4437SGlauber Costa 	return freed;
8531d3d4437SGlauber Costa }
8541d3d4437SGlauber Costa 
8550a432dcbSYang Shi #ifdef CONFIG_MEMCG
856b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
857b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
858b0dedc49SKirill Tkhai {
859e4262c4fSYang Shi 	struct shrinker_info *info;
860b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
861b8e57efaSKirill Tkhai 	int i;
862b0dedc49SKirill Tkhai 
8630a432dcbSYang Shi 	if (!mem_cgroup_online(memcg))
864b0dedc49SKirill Tkhai 		return 0;
865b0dedc49SKirill Tkhai 
866b0dedc49SKirill Tkhai 	if (!down_read_trylock(&shrinker_rwsem))
867b0dedc49SKirill Tkhai 		return 0;
868b0dedc49SKirill Tkhai 
869468ab843SYang Shi 	info = shrinker_info_protected(memcg, nid);
870e4262c4fSYang Shi 	if (unlikely(!info))
871b0dedc49SKirill Tkhai 		goto unlock;
872b0dedc49SKirill Tkhai 
873e4262c4fSYang Shi 	for_each_set_bit(i, info->map, shrinker_nr_max) {
874b0dedc49SKirill Tkhai 		struct shrink_control sc = {
875b0dedc49SKirill Tkhai 			.gfp_mask = gfp_mask,
876b0dedc49SKirill Tkhai 			.nid = nid,
877b0dedc49SKirill Tkhai 			.memcg = memcg,
878b0dedc49SKirill Tkhai 		};
879b0dedc49SKirill Tkhai 		struct shrinker *shrinker;
880b0dedc49SKirill Tkhai 
881b0dedc49SKirill Tkhai 		shrinker = idr_find(&shrinker_idr, i);
88241ca668aSYang Shi 		if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
8837e010df5SKirill Tkhai 			if (!shrinker)
884e4262c4fSYang Shi 				clear_bit(i, info->map);
885b0dedc49SKirill Tkhai 			continue;
886b0dedc49SKirill Tkhai 		}
887b0dedc49SKirill Tkhai 
8880a432dcbSYang Shi 		/* Call non-slab shrinkers even though kmem is disabled */
8890a432dcbSYang Shi 		if (!memcg_kmem_enabled() &&
8900a432dcbSYang Shi 		    !(shrinker->flags & SHRINKER_NONSLAB))
8910a432dcbSYang Shi 			continue;
8920a432dcbSYang Shi 
893b0dedc49SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
894f90280d6SKirill Tkhai 		if (ret == SHRINK_EMPTY) {
895e4262c4fSYang Shi 			clear_bit(i, info->map);
896f90280d6SKirill Tkhai 			/*
897f90280d6SKirill Tkhai 			 * After the shrinker reported that it had no objects to
898f90280d6SKirill Tkhai 			 * free, but before we cleared the corresponding bit in
899f90280d6SKirill Tkhai 			 * the memcg shrinker map, a new object might have been
900f90280d6SKirill Tkhai 			 * added. To make sure, we have the bit set in this
901f90280d6SKirill Tkhai 			 * case, we invoke the shrinker one more time and reset
902f90280d6SKirill Tkhai 			 * the bit if it reports that it is not empty anymore.
903f90280d6SKirill Tkhai 			 * The memory barrier here pairs with the barrier in
9042bfd3637SYang Shi 			 * set_shrinker_bit():
905f90280d6SKirill Tkhai 			 *
906f90280d6SKirill Tkhai 			 * list_lru_add()     shrink_slab_memcg()
907f90280d6SKirill Tkhai 			 *   list_add_tail()    clear_bit()
908f90280d6SKirill Tkhai 			 *   <MB>               <MB>
909f90280d6SKirill Tkhai 			 *   set_bit()          do_shrink_slab()
910f90280d6SKirill Tkhai 			 */
911f90280d6SKirill Tkhai 			smp_mb__after_atomic();
912f90280d6SKirill Tkhai 			ret = do_shrink_slab(&sc, shrinker, priority);
9139b996468SKirill Tkhai 			if (ret == SHRINK_EMPTY)
9149b996468SKirill Tkhai 				ret = 0;
915f90280d6SKirill Tkhai 			else
9162bfd3637SYang Shi 				set_shrinker_bit(memcg, nid, i);
917f90280d6SKirill Tkhai 		}
918b0dedc49SKirill Tkhai 		freed += ret;
919b0dedc49SKirill Tkhai 
920b0dedc49SKirill Tkhai 		if (rwsem_is_contended(&shrinker_rwsem)) {
921b0dedc49SKirill Tkhai 			freed = freed ? : 1;
922b0dedc49SKirill Tkhai 			break;
923b0dedc49SKirill Tkhai 		}
924b0dedc49SKirill Tkhai 	}
925b0dedc49SKirill Tkhai unlock:
926b0dedc49SKirill Tkhai 	up_read(&shrinker_rwsem);
927b0dedc49SKirill Tkhai 	return freed;
928b0dedc49SKirill Tkhai }
9290a432dcbSYang Shi #else /* CONFIG_MEMCG */
930b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
931b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
932b0dedc49SKirill Tkhai {
933b0dedc49SKirill Tkhai 	return 0;
934b0dedc49SKirill Tkhai }
9350a432dcbSYang Shi #endif /* CONFIG_MEMCG */
936b0dedc49SKirill Tkhai 
9376b4f7799SJohannes Weiner /**
938cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
9396b4f7799SJohannes Weiner  * @gfp_mask: allocation context
9406b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
941cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
9429092c71bSJosef Bacik  * @priority: the reclaim priority
9431d3d4437SGlauber Costa  *
9446b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
9451d3d4437SGlauber Costa  *
9466b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
9476b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
9481d3d4437SGlauber Costa  *
949aeed1d32SVladimir Davydov  * @memcg specifies the memory cgroup to target. Unaware shrinkers
950aeed1d32SVladimir Davydov  * are called only if it is the root cgroup.
951cb731d6cSVladimir Davydov  *
9529092c71bSJosef Bacik  * @priority is sc->priority, we take the number of objects and >> by priority
9539092c71bSJosef Bacik  * in order to get the scan target.
9541d3d4437SGlauber Costa  *
9556b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
9561d3d4437SGlauber Costa  */
957cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
958cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
9599092c71bSJosef Bacik 				 int priority)
9601d3d4437SGlauber Costa {
961b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
9621d3d4437SGlauber Costa 	struct shrinker *shrinker;
9631d3d4437SGlauber Costa 
964fa1e512fSYang Shi 	/*
965fa1e512fSYang Shi 	 * The root memcg might be allocated even though memcg is disabled
966fa1e512fSYang Shi 	 * via "cgroup_disable=memory" boot parameter.  This could make
967fa1e512fSYang Shi 	 * mem_cgroup_is_root() return false, then just run memcg slab
968fa1e512fSYang Shi 	 * shrink, but skip global shrink.  This may result in premature
969fa1e512fSYang Shi 	 * oom.
970fa1e512fSYang Shi 	 */
971fa1e512fSYang Shi 	if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
972b0dedc49SKirill Tkhai 		return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
973cb731d6cSVladimir Davydov 
974e830c63aSTetsuo Handa 	if (!down_read_trylock(&shrinker_rwsem))
9751d3d4437SGlauber Costa 		goto out;
9761d3d4437SGlauber Costa 
9771d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
9786b4f7799SJohannes Weiner 		struct shrink_control sc = {
9796b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
9806b4f7799SJohannes Weiner 			.nid = nid,
981cb731d6cSVladimir Davydov 			.memcg = memcg,
9826b4f7799SJohannes Weiner 		};
9836b4f7799SJohannes Weiner 
9849b996468SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
9859b996468SKirill Tkhai 		if (ret == SHRINK_EMPTY)
9869b996468SKirill Tkhai 			ret = 0;
9879b996468SKirill Tkhai 		freed += ret;
988e496612cSMinchan Kim 		/*
989e496612cSMinchan Kim 		 * Bail out if someone want to register a new shrinker to
99055b65a57SEthon Paul 		 * prevent the registration from being stalled for long periods
991e496612cSMinchan Kim 		 * by parallel ongoing shrinking.
992e496612cSMinchan Kim 		 */
993e496612cSMinchan Kim 		if (rwsem_is_contended(&shrinker_rwsem)) {
994e496612cSMinchan Kim 			freed = freed ? : 1;
995e496612cSMinchan Kim 			break;
996e496612cSMinchan Kim 		}
997ec97097bSVladimir Davydov 	}
9981d3d4437SGlauber Costa 
9991da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
1000f06590bdSMinchan Kim out:
1001f06590bdSMinchan Kim 	cond_resched();
100224f7c6b9SDave Chinner 	return freed;
10031da177e4SLinus Torvalds }
10041da177e4SLinus Torvalds 
1005e4b424b7SGang Li static void drop_slab_node(int nid)
1006cb731d6cSVladimir Davydov {
1007cb731d6cSVladimir Davydov 	unsigned long freed;
10081399af7eSVlastimil Babka 	int shift = 0;
1009cb731d6cSVladimir Davydov 
1010cb731d6cSVladimir Davydov 	do {
1011cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
1012cb731d6cSVladimir Davydov 
1013069c411dSChunxin Zang 		if (fatal_signal_pending(current))
1014069c411dSChunxin Zang 			return;
1015069c411dSChunxin Zang 
1016cb731d6cSVladimir Davydov 		freed = 0;
1017aeed1d32SVladimir Davydov 		memcg = mem_cgroup_iter(NULL, NULL, NULL);
1018cb731d6cSVladimir Davydov 		do {
10199092c71bSJosef Bacik 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
1020cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
10211399af7eSVlastimil Babka 	} while ((freed >> shift++) > 1);
1022cb731d6cSVladimir Davydov }
1023cb731d6cSVladimir Davydov 
1024cb731d6cSVladimir Davydov void drop_slab(void)
1025cb731d6cSVladimir Davydov {
1026cb731d6cSVladimir Davydov 	int nid;
1027cb731d6cSVladimir Davydov 
1028cb731d6cSVladimir Davydov 	for_each_online_node(nid)
1029cb731d6cSVladimir Davydov 		drop_slab_node(nid);
1030cb731d6cSVladimir Davydov }
1031cb731d6cSVladimir Davydov 
1032e0cd5e7fSMatthew Wilcox (Oracle) static inline int is_page_cache_freeable(struct folio *folio)
10331da177e4SLinus Torvalds {
1034ceddc3a5SJohannes Weiner 	/*
1035ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
103667891fffSMatthew Wilcox 	 * that isolated the page, the page cache and optional buffer
103767891fffSMatthew Wilcox 	 * heads at page->private.
1038ceddc3a5SJohannes Weiner 	 */
1039e0cd5e7fSMatthew Wilcox (Oracle) 	return folio_ref_count(folio) - folio_test_private(folio) ==
1040e0cd5e7fSMatthew Wilcox (Oracle) 		1 + folio_nr_pages(folio);
10411da177e4SLinus Torvalds }
10421da177e4SLinus Torvalds 
10431da177e4SLinus Torvalds /*
1044e0cd5e7fSMatthew Wilcox (Oracle)  * We detected a synchronous write error writing a folio out.  Probably
10451da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
10461da177e4SLinus Torvalds  * fsync(), msync() or close().
10471da177e4SLinus Torvalds  *
10481da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
1049e0cd5e7fSMatthew Wilcox (Oracle)  * prevents it from being freed up.  But we have a ref on the folio and once
1050e0cd5e7fSMatthew Wilcox (Oracle)  * that folio is locked, the mapping is pinned.
10511da177e4SLinus Torvalds  *
1052e0cd5e7fSMatthew Wilcox (Oracle)  * We're allowed to run sleeping folio_lock() here because we know the caller has
10531da177e4SLinus Torvalds  * __GFP_FS.
10541da177e4SLinus Torvalds  */
10551da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
1056e0cd5e7fSMatthew Wilcox (Oracle) 				struct folio *folio, int error)
10571da177e4SLinus Torvalds {
1058e0cd5e7fSMatthew Wilcox (Oracle) 	folio_lock(folio);
1059e0cd5e7fSMatthew Wilcox (Oracle) 	if (folio_mapping(folio) == mapping)
10603e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
1061e0cd5e7fSMatthew Wilcox (Oracle) 	folio_unlock(folio);
10621da177e4SLinus Torvalds }
10631da177e4SLinus Torvalds 
10641b4e3f26SMel Gorman static bool skip_throttle_noprogress(pg_data_t *pgdat)
10651b4e3f26SMel Gorman {
10661b4e3f26SMel Gorman 	int reclaimable = 0, write_pending = 0;
10671b4e3f26SMel Gorman 	int i;
10681b4e3f26SMel Gorman 
10691b4e3f26SMel Gorman 	/*
10701b4e3f26SMel Gorman 	 * If kswapd is disabled, reschedule if necessary but do not
10711b4e3f26SMel Gorman 	 * throttle as the system is likely near OOM.
10721b4e3f26SMel Gorman 	 */
10731b4e3f26SMel Gorman 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
10741b4e3f26SMel Gorman 		return true;
10751b4e3f26SMel Gorman 
10761b4e3f26SMel Gorman 	/*
10771b4e3f26SMel Gorman 	 * If there are a lot of dirty/writeback pages then do not
10781b4e3f26SMel Gorman 	 * throttle as throttling will occur when the pages cycle
10791b4e3f26SMel Gorman 	 * towards the end of the LRU if still under writeback.
10801b4e3f26SMel Gorman 	 */
10811b4e3f26SMel Gorman 	for (i = 0; i < MAX_NR_ZONES; i++) {
10821b4e3f26SMel Gorman 		struct zone *zone = pgdat->node_zones + i;
10831b4e3f26SMel Gorman 
108436c26128SWei Yang 		if (!managed_zone(zone))
10851b4e3f26SMel Gorman 			continue;
10861b4e3f26SMel Gorman 
10871b4e3f26SMel Gorman 		reclaimable += zone_reclaimable_pages(zone);
10881b4e3f26SMel Gorman 		write_pending += zone_page_state_snapshot(zone,
10891b4e3f26SMel Gorman 						  NR_ZONE_WRITE_PENDING);
10901b4e3f26SMel Gorman 	}
10911b4e3f26SMel Gorman 	if (2 * write_pending <= reclaimable)
10921b4e3f26SMel Gorman 		return true;
10931b4e3f26SMel Gorman 
10941b4e3f26SMel Gorman 	return false;
10951b4e3f26SMel Gorman }
10961b4e3f26SMel Gorman 
1097c3f4a9a2SMel Gorman void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason)
10988cd7c588SMel Gorman {
10998cd7c588SMel Gorman 	wait_queue_head_t *wqh = &pgdat->reclaim_wait[reason];
1100c3f4a9a2SMel Gorman 	long timeout, ret;
11018cd7c588SMel Gorman 	DEFINE_WAIT(wait);
11028cd7c588SMel Gorman 
11038cd7c588SMel Gorman 	/*
11048cd7c588SMel Gorman 	 * Do not throttle IO workers, kthreads other than kswapd or
11058cd7c588SMel Gorman 	 * workqueues. They may be required for reclaim to make
11068cd7c588SMel Gorman 	 * forward progress (e.g. journalling workqueues or kthreads).
11078cd7c588SMel Gorman 	 */
11088cd7c588SMel Gorman 	if (!current_is_kswapd() &&
1109b485c6f1SMel Gorman 	    current->flags & (PF_IO_WORKER|PF_KTHREAD)) {
1110b485c6f1SMel Gorman 		cond_resched();
11118cd7c588SMel Gorman 		return;
1112b485c6f1SMel Gorman 	}
11138cd7c588SMel Gorman 
1114c3f4a9a2SMel Gorman 	/*
1115c3f4a9a2SMel Gorman 	 * These figures are pulled out of thin air.
1116c3f4a9a2SMel Gorman 	 * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many
1117c3f4a9a2SMel Gorman 	 * parallel reclaimers which is a short-lived event so the timeout is
1118c3f4a9a2SMel Gorman 	 * short. Failing to make progress or waiting on writeback are
1119c3f4a9a2SMel Gorman 	 * potentially long-lived events so use a longer timeout. This is shaky
1120c3f4a9a2SMel Gorman 	 * logic as a failure to make progress could be due to anything from
1121c3f4a9a2SMel Gorman 	 * writeback to a slow device to excessive references pages at the tail
1122c3f4a9a2SMel Gorman 	 * of the inactive LRU.
1123c3f4a9a2SMel Gorman 	 */
1124c3f4a9a2SMel Gorman 	switch(reason) {
1125c3f4a9a2SMel Gorman 	case VMSCAN_THROTTLE_WRITEBACK:
1126c3f4a9a2SMel Gorman 		timeout = HZ/10;
1127c3f4a9a2SMel Gorman 
1128c3f4a9a2SMel Gorman 		if (atomic_inc_return(&pgdat->nr_writeback_throttled) == 1) {
11298cd7c588SMel Gorman 			WRITE_ONCE(pgdat->nr_reclaim_start,
11308cd7c588SMel Gorman 				node_page_state(pgdat, NR_THROTTLED_WRITTEN));
11318cd7c588SMel Gorman 		}
11328cd7c588SMel Gorman 
1133c3f4a9a2SMel Gorman 		break;
11341b4e3f26SMel Gorman 	case VMSCAN_THROTTLE_CONGESTED:
11351b4e3f26SMel Gorman 		fallthrough;
1136c3f4a9a2SMel Gorman 	case VMSCAN_THROTTLE_NOPROGRESS:
11371b4e3f26SMel Gorman 		if (skip_throttle_noprogress(pgdat)) {
11381b4e3f26SMel Gorman 			cond_resched();
11391b4e3f26SMel Gorman 			return;
11401b4e3f26SMel Gorman 		}
11411b4e3f26SMel Gorman 
11421b4e3f26SMel Gorman 		timeout = 1;
11431b4e3f26SMel Gorman 
1144c3f4a9a2SMel Gorman 		break;
1145c3f4a9a2SMel Gorman 	case VMSCAN_THROTTLE_ISOLATED:
1146c3f4a9a2SMel Gorman 		timeout = HZ/50;
1147c3f4a9a2SMel Gorman 		break;
1148c3f4a9a2SMel Gorman 	default:
1149c3f4a9a2SMel Gorman 		WARN_ON_ONCE(1);
1150c3f4a9a2SMel Gorman 		timeout = HZ;
1151c3f4a9a2SMel Gorman 		break;
1152c3f4a9a2SMel Gorman 	}
1153c3f4a9a2SMel Gorman 
11548cd7c588SMel Gorman 	prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE);
11558cd7c588SMel Gorman 	ret = schedule_timeout(timeout);
11568cd7c588SMel Gorman 	finish_wait(wqh, &wait);
1157d818fca1SMel Gorman 
1158c3f4a9a2SMel Gorman 	if (reason == VMSCAN_THROTTLE_WRITEBACK)
11598cd7c588SMel Gorman 		atomic_dec(&pgdat->nr_writeback_throttled);
11608cd7c588SMel Gorman 
11618cd7c588SMel Gorman 	trace_mm_vmscan_throttled(pgdat->node_id, jiffies_to_usecs(timeout),
11628cd7c588SMel Gorman 				jiffies_to_usecs(timeout - ret),
11638cd7c588SMel Gorman 				reason);
11648cd7c588SMel Gorman }
11658cd7c588SMel Gorman 
11668cd7c588SMel Gorman /*
11678cd7c588SMel Gorman  * Account for pages written if tasks are throttled waiting on dirty
11688cd7c588SMel Gorman  * pages to clean. If enough pages have been cleaned since throttling
11698cd7c588SMel Gorman  * started then wakeup the throttled tasks.
11708cd7c588SMel Gorman  */
1171512b7931SLinus Torvalds void __acct_reclaim_writeback(pg_data_t *pgdat, struct folio *folio,
11728cd7c588SMel Gorman 							int nr_throttled)
11738cd7c588SMel Gorman {
11748cd7c588SMel Gorman 	unsigned long nr_written;
11758cd7c588SMel Gorman 
1176512b7931SLinus Torvalds 	node_stat_add_folio(folio, NR_THROTTLED_WRITTEN);
11778cd7c588SMel Gorman 
11788cd7c588SMel Gorman 	/*
11798cd7c588SMel Gorman 	 * This is an inaccurate read as the per-cpu deltas may not
11808cd7c588SMel Gorman 	 * be synchronised. However, given that the system is
11818cd7c588SMel Gorman 	 * writeback throttled, it is not worth taking the penalty
11828cd7c588SMel Gorman 	 * of getting an accurate count. At worst, the throttle
11838cd7c588SMel Gorman 	 * timeout guarantees forward progress.
11848cd7c588SMel Gorman 	 */
11858cd7c588SMel Gorman 	nr_written = node_page_state(pgdat, NR_THROTTLED_WRITTEN) -
11868cd7c588SMel Gorman 		READ_ONCE(pgdat->nr_reclaim_start);
11878cd7c588SMel Gorman 
11888cd7c588SMel Gorman 	if (nr_written > SWAP_CLUSTER_MAX * nr_throttled)
11898cd7c588SMel Gorman 		wake_up(&pgdat->reclaim_wait[VMSCAN_THROTTLE_WRITEBACK]);
11908cd7c588SMel Gorman }
11918cd7c588SMel Gorman 
119204e62a29SChristoph Lameter /* possible outcome of pageout() */
119304e62a29SChristoph Lameter typedef enum {
119404e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
119504e62a29SChristoph Lameter 	PAGE_KEEP,
119604e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
119704e62a29SChristoph Lameter 	PAGE_ACTIVATE,
119804e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
119904e62a29SChristoph Lameter 	PAGE_SUCCESS,
120004e62a29SChristoph Lameter 	/* page is clean and locked */
120104e62a29SChristoph Lameter 	PAGE_CLEAN,
120204e62a29SChristoph Lameter } pageout_t;
120304e62a29SChristoph Lameter 
12041da177e4SLinus Torvalds /*
12051742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
12061742f19fSAndrew Morton  * Calls ->writepage().
12071da177e4SLinus Torvalds  */
12082282679fSNeilBrown static pageout_t pageout(struct folio *folio, struct address_space *mapping,
12092282679fSNeilBrown 			 struct swap_iocb **plug)
12101da177e4SLinus Torvalds {
12111da177e4SLinus Torvalds 	/*
1212e0cd5e7fSMatthew Wilcox (Oracle) 	 * If the folio is dirty, only perform writeback if that write
12131da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
12141da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
12151da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
12161da177e4SLinus Torvalds 	 * PagePrivate for that.
12171da177e4SLinus Torvalds 	 *
12188174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
1219e0cd5e7fSMatthew Wilcox (Oracle) 	 * this folio's queue, we can perform writeback even if that
12201da177e4SLinus Torvalds 	 * will block.
12211da177e4SLinus Torvalds 	 *
1222e0cd5e7fSMatthew Wilcox (Oracle) 	 * If the folio is swapcache, write it back even if that would
12231da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
12241da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
12251da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
12261da177e4SLinus Torvalds 	 */
1227e0cd5e7fSMatthew Wilcox (Oracle) 	if (!is_page_cache_freeable(folio))
12281da177e4SLinus Torvalds 		return PAGE_KEEP;
12291da177e4SLinus Torvalds 	if (!mapping) {
12301da177e4SLinus Torvalds 		/*
1231e0cd5e7fSMatthew Wilcox (Oracle) 		 * Some data journaling orphaned folios can have
1232e0cd5e7fSMatthew Wilcox (Oracle) 		 * folio->mapping == NULL while being dirty with clean buffers.
12331da177e4SLinus Torvalds 		 */
1234e0cd5e7fSMatthew Wilcox (Oracle) 		if (folio_test_private(folio)) {
123568189fefSMatthew Wilcox (Oracle) 			if (try_to_free_buffers(folio)) {
1236e0cd5e7fSMatthew Wilcox (Oracle) 				folio_clear_dirty(folio);
1237e0cd5e7fSMatthew Wilcox (Oracle) 				pr_info("%s: orphaned folio\n", __func__);
12381da177e4SLinus Torvalds 				return PAGE_CLEAN;
12391da177e4SLinus Torvalds 			}
12401da177e4SLinus Torvalds 		}
12411da177e4SLinus Torvalds 		return PAGE_KEEP;
12421da177e4SLinus Torvalds 	}
12431da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
12441da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
12451da177e4SLinus Torvalds 
1246e0cd5e7fSMatthew Wilcox (Oracle) 	if (folio_clear_dirty_for_io(folio)) {
12471da177e4SLinus Torvalds 		int res;
12481da177e4SLinus Torvalds 		struct writeback_control wbc = {
12491da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
12501da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
1251111ebb6eSOGAWA Hirofumi 			.range_start = 0,
1252111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
12531da177e4SLinus Torvalds 			.for_reclaim = 1,
12542282679fSNeilBrown 			.swap_plug = plug,
12551da177e4SLinus Torvalds 		};
12561da177e4SLinus Torvalds 
1257e0cd5e7fSMatthew Wilcox (Oracle) 		folio_set_reclaim(folio);
1258e0cd5e7fSMatthew Wilcox (Oracle) 		res = mapping->a_ops->writepage(&folio->page, &wbc);
12591da177e4SLinus Torvalds 		if (res < 0)
1260e0cd5e7fSMatthew Wilcox (Oracle) 			handle_write_error(mapping, folio, res);
1261994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
1262e0cd5e7fSMatthew Wilcox (Oracle) 			folio_clear_reclaim(folio);
12631da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
12641da177e4SLinus Torvalds 		}
1265c661b078SAndy Whitcroft 
1266e0cd5e7fSMatthew Wilcox (Oracle) 		if (!folio_test_writeback(folio)) {
12671da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
1268e0cd5e7fSMatthew Wilcox (Oracle) 			folio_clear_reclaim(folio);
12691da177e4SLinus Torvalds 		}
1270e0cd5e7fSMatthew Wilcox (Oracle) 		trace_mm_vmscan_write_folio(folio);
1271e0cd5e7fSMatthew Wilcox (Oracle) 		node_stat_add_folio(folio, NR_VMSCAN_WRITE);
12721da177e4SLinus Torvalds 		return PAGE_SUCCESS;
12731da177e4SLinus Torvalds 	}
12741da177e4SLinus Torvalds 
12751da177e4SLinus Torvalds 	return PAGE_CLEAN;
12761da177e4SLinus Torvalds }
12771da177e4SLinus Torvalds 
1278a649fd92SAndrew Morton /*
1279e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
1280e286781dSNick Piggin  * gets returned with a refcount of 0.
1281a649fd92SAndrew Morton  */
1282be7c07d6SMatthew Wilcox (Oracle) static int __remove_mapping(struct address_space *mapping, struct folio *folio,
1283b910718aSJohannes Weiner 			    bool reclaimed, struct mem_cgroup *target_memcg)
128449d2e9ccSChristoph Lameter {
1285bd4c82c2SHuang Ying 	int refcount;
1286aae466b0SJoonsoo Kim 	void *shadow = NULL;
1287c4843a75SGreg Thelen 
1288be7c07d6SMatthew Wilcox (Oracle) 	BUG_ON(!folio_test_locked(folio));
1289be7c07d6SMatthew Wilcox (Oracle) 	BUG_ON(mapping != folio_mapping(folio));
129049d2e9ccSChristoph Lameter 
1291be7c07d6SMatthew Wilcox (Oracle) 	if (!folio_test_swapcache(folio))
129251b8c1feSJohannes Weiner 		spin_lock(&mapping->host->i_lock);
129330472509SJohannes Weiner 	xa_lock_irq(&mapping->i_pages);
129449d2e9ccSChristoph Lameter 	/*
12950fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
12960fd0e6b0SNick Piggin 	 *
12970fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
12980fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
12990fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
13000fd0e6b0SNick Piggin 	 * here, then the following race may occur:
13010fd0e6b0SNick Piggin 	 *
13020fd0e6b0SNick Piggin 	 * get_user_pages(&page);
13030fd0e6b0SNick Piggin 	 * [user mapping goes away]
13040fd0e6b0SNick Piggin 	 * write_to(page);
13050fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
13060fd0e6b0SNick Piggin 	 * SetPageDirty(page);
13070fd0e6b0SNick Piggin 	 * put_page(page);
13080fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
13090fd0e6b0SNick Piggin 	 *
13100fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
13110fd0e6b0SNick Piggin 	 *
13120fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
13130fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
13140139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
13150fd0e6b0SNick Piggin 	 *
13160fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
1317b93b0163SMatthew Wilcox 	 * and thus under the i_pages lock, then this ordering is not required.
131849d2e9ccSChristoph Lameter 	 */
1319be7c07d6SMatthew Wilcox (Oracle) 	refcount = 1 + folio_nr_pages(folio);
1320be7c07d6SMatthew Wilcox (Oracle) 	if (!folio_ref_freeze(folio, refcount))
132149d2e9ccSChristoph Lameter 		goto cannot_free;
13221c4c3b99SJiang Biao 	/* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
1323be7c07d6SMatthew Wilcox (Oracle) 	if (unlikely(folio_test_dirty(folio))) {
1324be7c07d6SMatthew Wilcox (Oracle) 		folio_ref_unfreeze(folio, refcount);
132549d2e9ccSChristoph Lameter 		goto cannot_free;
1326e286781dSNick Piggin 	}
132749d2e9ccSChristoph Lameter 
1328be7c07d6SMatthew Wilcox (Oracle) 	if (folio_test_swapcache(folio)) {
1329be7c07d6SMatthew Wilcox (Oracle) 		swp_entry_t swap = folio_swap_entry(folio);
13303ecb0087SMatthew Wilcox (Oracle) 		mem_cgroup_swapout(folio, swap);
1331aae466b0SJoonsoo Kim 		if (reclaimed && !mapping_exiting(mapping))
13328927f647SMatthew Wilcox (Oracle) 			shadow = workingset_eviction(folio, target_memcg);
1333be7c07d6SMatthew Wilcox (Oracle) 		__delete_from_swap_cache(&folio->page, swap, shadow);
133430472509SJohannes Weiner 		xa_unlock_irq(&mapping->i_pages);
1335be7c07d6SMatthew Wilcox (Oracle) 		put_swap_page(&folio->page, swap);
1336e286781dSNick Piggin 	} else {
1337d2329aa0SMatthew Wilcox (Oracle) 		void (*free_folio)(struct folio *);
13386072d13cSLinus Torvalds 
1339d2329aa0SMatthew Wilcox (Oracle) 		free_folio = mapping->a_ops->free_folio;
1340a528910eSJohannes Weiner 		/*
1341a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
1342a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
1343a528910eSJohannes Weiner 		 *
1344a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
1345238c3046Sdylan-meiners 		 * already exiting.  This is not just an optimization,
1346a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
1347a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
1348a528910eSJohannes Weiner 		 * back.
1349f9fe48beSRoss Zwisler 		 *
1350f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
1351f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
1352f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
1353f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
1354b93b0163SMatthew Wilcox 		 * same address_space.
1355a528910eSJohannes Weiner 		 */
1356be7c07d6SMatthew Wilcox (Oracle) 		if (reclaimed && folio_is_file_lru(folio) &&
1357f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
13588927f647SMatthew Wilcox (Oracle) 			shadow = workingset_eviction(folio, target_memcg);
13598927f647SMatthew Wilcox (Oracle) 		__filemap_remove_folio(folio, shadow);
136030472509SJohannes Weiner 		xa_unlock_irq(&mapping->i_pages);
136151b8c1feSJohannes Weiner 		if (mapping_shrinkable(mapping))
136251b8c1feSJohannes Weiner 			inode_add_lru(mapping->host);
136351b8c1feSJohannes Weiner 		spin_unlock(&mapping->host->i_lock);
13646072d13cSLinus Torvalds 
1365d2329aa0SMatthew Wilcox (Oracle) 		if (free_folio)
1366d2329aa0SMatthew Wilcox (Oracle) 			free_folio(folio);
1367e286781dSNick Piggin 	}
1368e286781dSNick Piggin 
136949d2e9ccSChristoph Lameter 	return 1;
137049d2e9ccSChristoph Lameter 
137149d2e9ccSChristoph Lameter cannot_free:
137230472509SJohannes Weiner 	xa_unlock_irq(&mapping->i_pages);
1373be7c07d6SMatthew Wilcox (Oracle) 	if (!folio_test_swapcache(folio))
137451b8c1feSJohannes Weiner 		spin_unlock(&mapping->host->i_lock);
137549d2e9ccSChristoph Lameter 	return 0;
137649d2e9ccSChristoph Lameter }
137749d2e9ccSChristoph Lameter 
13785100da38SMatthew Wilcox (Oracle) /**
13795100da38SMatthew Wilcox (Oracle)  * remove_mapping() - Attempt to remove a folio from its mapping.
13805100da38SMatthew Wilcox (Oracle)  * @mapping: The address space.
13815100da38SMatthew Wilcox (Oracle)  * @folio: The folio to remove.
13825100da38SMatthew Wilcox (Oracle)  *
13835100da38SMatthew Wilcox (Oracle)  * If the folio is dirty, under writeback or if someone else has a ref
13845100da38SMatthew Wilcox (Oracle)  * on it, removal will fail.
13855100da38SMatthew Wilcox (Oracle)  * Return: The number of pages removed from the mapping.  0 if the folio
13865100da38SMatthew Wilcox (Oracle)  * could not be removed.
13875100da38SMatthew Wilcox (Oracle)  * Context: The caller should have a single refcount on the folio and
13885100da38SMatthew Wilcox (Oracle)  * hold its lock.
1389e286781dSNick Piggin  */
13905100da38SMatthew Wilcox (Oracle) long remove_mapping(struct address_space *mapping, struct folio *folio)
1391e286781dSNick Piggin {
1392be7c07d6SMatthew Wilcox (Oracle) 	if (__remove_mapping(mapping, folio, false, NULL)) {
1393e286781dSNick Piggin 		/*
13945100da38SMatthew Wilcox (Oracle) 		 * Unfreezing the refcount with 1 effectively
1395e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
1396e286781dSNick Piggin 		 * atomic operation.
1397e286781dSNick Piggin 		 */
1398be7c07d6SMatthew Wilcox (Oracle) 		folio_ref_unfreeze(folio, 1);
13995100da38SMatthew Wilcox (Oracle) 		return folio_nr_pages(folio);
1400e286781dSNick Piggin 	}
1401e286781dSNick Piggin 	return 0;
1402e286781dSNick Piggin }
1403e286781dSNick Piggin 
1404894bc310SLee Schermerhorn /**
1405ca6d60f3SMatthew Wilcox (Oracle)  * folio_putback_lru - Put previously isolated folio onto appropriate LRU list.
1406ca6d60f3SMatthew Wilcox (Oracle)  * @folio: Folio to be returned to an LRU list.
1407894bc310SLee Schermerhorn  *
1408ca6d60f3SMatthew Wilcox (Oracle)  * Add previously isolated @folio to appropriate LRU list.
1409ca6d60f3SMatthew Wilcox (Oracle)  * The folio may still be unevictable for other reasons.
1410894bc310SLee Schermerhorn  *
1411ca6d60f3SMatthew Wilcox (Oracle)  * Context: lru_lock must not be held, interrupts must be enabled.
1412894bc310SLee Schermerhorn  */
1413ca6d60f3SMatthew Wilcox (Oracle) void folio_putback_lru(struct folio *folio)
1414894bc310SLee Schermerhorn {
1415ca6d60f3SMatthew Wilcox (Oracle) 	folio_add_lru(folio);
1416ca6d60f3SMatthew Wilcox (Oracle) 	folio_put(folio);		/* drop ref from isolate */
1417894bc310SLee Schermerhorn }
1418894bc310SLee Schermerhorn 
1419dfc8d636SJohannes Weiner enum page_references {
1420dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
1421dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
142264574746SJohannes Weiner 	PAGEREF_KEEP,
1423dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
1424dfc8d636SJohannes Weiner };
1425dfc8d636SJohannes Weiner 
1426d92013d1SMatthew Wilcox (Oracle) static enum page_references folio_check_references(struct folio *folio,
1427dfc8d636SJohannes Weiner 						  struct scan_control *sc)
1428dfc8d636SJohannes Weiner {
1429d92013d1SMatthew Wilcox (Oracle) 	int referenced_ptes, referenced_folio;
1430dfc8d636SJohannes Weiner 	unsigned long vm_flags;
1431dfc8d636SJohannes Weiner 
1432b3ac0413SMatthew Wilcox (Oracle) 	referenced_ptes = folio_referenced(folio, 1, sc->target_mem_cgroup,
1433c3ac9a8aSJohannes Weiner 					   &vm_flags);
1434d92013d1SMatthew Wilcox (Oracle) 	referenced_folio = folio_test_clear_referenced(folio);
1435dfc8d636SJohannes Weiner 
1436dfc8d636SJohannes Weiner 	/*
1437d92013d1SMatthew Wilcox (Oracle) 	 * The supposedly reclaimable folio was found to be in a VM_LOCKED vma.
1438d92013d1SMatthew Wilcox (Oracle) 	 * Let the folio, now marked Mlocked, be moved to the unevictable list.
1439dfc8d636SJohannes Weiner 	 */
1440dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
144147d4f3eeSHugh Dickins 		return PAGEREF_ACTIVATE;
1442dfc8d636SJohannes Weiner 
14436d4675e6SMinchan Kim 	/* rmap lock contention: rotate */
14446d4675e6SMinchan Kim 	if (referenced_ptes == -1)
14456d4675e6SMinchan Kim 		return PAGEREF_KEEP;
14466d4675e6SMinchan Kim 
144764574746SJohannes Weiner 	if (referenced_ptes) {
144864574746SJohannes Weiner 		/*
1449d92013d1SMatthew Wilcox (Oracle) 		 * All mapped folios start out with page table
145064574746SJohannes Weiner 		 * references from the instantiating fault, so we need
14519030fb0bSLinus Torvalds 		 * to look twice if a mapped file/anon folio is used more
145264574746SJohannes Weiner 		 * than once.
145364574746SJohannes Weiner 		 *
145464574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
145564574746SJohannes Weiner 		 * inactive list.  Another page table reference will
145664574746SJohannes Weiner 		 * lead to its activation.
145764574746SJohannes Weiner 		 *
1458d92013d1SMatthew Wilcox (Oracle) 		 * Note: the mark is set for activated folios as well
1459d92013d1SMatthew Wilcox (Oracle) 		 * so that recently deactivated but used folios are
146064574746SJohannes Weiner 		 * quickly recovered.
146164574746SJohannes Weiner 		 */
1462d92013d1SMatthew Wilcox (Oracle) 		folio_set_referenced(folio);
146364574746SJohannes Weiner 
1464d92013d1SMatthew Wilcox (Oracle) 		if (referenced_folio || referenced_ptes > 1)
1465dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
1466dfc8d636SJohannes Weiner 
1467c909e993SKonstantin Khlebnikov 		/*
1468d92013d1SMatthew Wilcox (Oracle) 		 * Activate file-backed executable folios after first usage.
1469c909e993SKonstantin Khlebnikov 		 */
1470f19a27e3SMiaohe Lin 		if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio))
1471c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
1472c909e993SKonstantin Khlebnikov 
147364574746SJohannes Weiner 		return PAGEREF_KEEP;
147464574746SJohannes Weiner 	}
147564574746SJohannes Weiner 
1476d92013d1SMatthew Wilcox (Oracle) 	/* Reclaim if clean, defer dirty folios to writeback */
1477f19a27e3SMiaohe Lin 	if (referenced_folio && folio_is_file_lru(folio))
1478dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
147964574746SJohannes Weiner 
148064574746SJohannes Weiner 	return PAGEREF_RECLAIM;
1481dfc8d636SJohannes Weiner }
1482dfc8d636SJohannes Weiner 
1483e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
1484e20c41b1SMatthew Wilcox (Oracle) static void folio_check_dirty_writeback(struct folio *folio,
1485e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
1486e2be15f6SMel Gorman {
1487b4597226SMel Gorman 	struct address_space *mapping;
1488b4597226SMel Gorman 
1489e2be15f6SMel Gorman 	/*
1490e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
149132a331a7SMiaohe Lin 	 * from reclaim context. Do not stall reclaim based on them.
149232a331a7SMiaohe Lin 	 * MADV_FREE anonymous pages are put into inactive file list too.
149332a331a7SMiaohe Lin 	 * They could be mistakenly treated as file lru. So further anon
149432a331a7SMiaohe Lin 	 * test is needed.
1495e2be15f6SMel Gorman 	 */
1496e20c41b1SMatthew Wilcox (Oracle) 	if (!folio_is_file_lru(folio) ||
1497e20c41b1SMatthew Wilcox (Oracle) 	    (folio_test_anon(folio) && !folio_test_swapbacked(folio))) {
1498e2be15f6SMel Gorman 		*dirty = false;
1499e2be15f6SMel Gorman 		*writeback = false;
1500e2be15f6SMel Gorman 		return;
1501e2be15f6SMel Gorman 	}
1502e2be15f6SMel Gorman 
1503e20c41b1SMatthew Wilcox (Oracle) 	/* By default assume that the folio flags are accurate */
1504e20c41b1SMatthew Wilcox (Oracle) 	*dirty = folio_test_dirty(folio);
1505e20c41b1SMatthew Wilcox (Oracle) 	*writeback = folio_test_writeback(folio);
1506b4597226SMel Gorman 
1507b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
1508e20c41b1SMatthew Wilcox (Oracle) 	if (!folio_test_private(folio))
1509b4597226SMel Gorman 		return;
1510b4597226SMel Gorman 
1511e20c41b1SMatthew Wilcox (Oracle) 	mapping = folio_mapping(folio);
1512b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
1513520f301cSMatthew Wilcox (Oracle) 		mapping->a_ops->is_dirty_writeback(folio, dirty, writeback);
1514e2be15f6SMel Gorman }
1515e2be15f6SMel Gorman 
151626aa2d19SDave Hansen static struct page *alloc_demote_page(struct page *page, unsigned long node)
151726aa2d19SDave Hansen {
151826aa2d19SDave Hansen 	struct migration_target_control mtc = {
151926aa2d19SDave Hansen 		/*
152026aa2d19SDave Hansen 		 * Allocate from 'node', or fail quickly and quietly.
152126aa2d19SDave Hansen 		 * When this happens, 'page' will likely just be discarded
152226aa2d19SDave Hansen 		 * instead of migrated.
152326aa2d19SDave Hansen 		 */
152426aa2d19SDave Hansen 		.gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
152526aa2d19SDave Hansen 			    __GFP_THISNODE  | __GFP_NOWARN |
152626aa2d19SDave Hansen 			    __GFP_NOMEMALLOC | GFP_NOWAIT,
152726aa2d19SDave Hansen 		.nid = node
152826aa2d19SDave Hansen 	};
152926aa2d19SDave Hansen 
153026aa2d19SDave Hansen 	return alloc_migration_target(page, (unsigned long)&mtc);
153126aa2d19SDave Hansen }
153226aa2d19SDave Hansen 
153326aa2d19SDave Hansen /*
153426aa2d19SDave Hansen  * Take pages on @demote_list and attempt to demote them to
153526aa2d19SDave Hansen  * another node.  Pages which are not demoted are left on
153626aa2d19SDave Hansen  * @demote_pages.
153726aa2d19SDave Hansen  */
153826aa2d19SDave Hansen static unsigned int demote_page_list(struct list_head *demote_pages,
153926aa2d19SDave Hansen 				     struct pglist_data *pgdat)
154026aa2d19SDave Hansen {
154126aa2d19SDave Hansen 	int target_nid = next_demotion_node(pgdat->node_id);
154226aa2d19SDave Hansen 	unsigned int nr_succeeded;
154326aa2d19SDave Hansen 
154426aa2d19SDave Hansen 	if (list_empty(demote_pages))
154526aa2d19SDave Hansen 		return 0;
154626aa2d19SDave Hansen 
154726aa2d19SDave Hansen 	if (target_nid == NUMA_NO_NODE)
154826aa2d19SDave Hansen 		return 0;
154926aa2d19SDave Hansen 
155026aa2d19SDave Hansen 	/* Demotion ignores all cpuset and mempolicy settings */
1551cb75463cSKai Song 	migrate_pages(demote_pages, alloc_demote_page, NULL,
155226aa2d19SDave Hansen 			    target_nid, MIGRATE_ASYNC, MR_DEMOTION,
155326aa2d19SDave Hansen 			    &nr_succeeded);
155426aa2d19SDave Hansen 
1555668e4147SYang Shi 	if (current_is_kswapd())
1556668e4147SYang Shi 		__count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1557668e4147SYang Shi 	else
1558668e4147SYang Shi 		__count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1559668e4147SYang Shi 
156026aa2d19SDave Hansen 	return nr_succeeded;
156126aa2d19SDave Hansen }
156226aa2d19SDave Hansen 
1563c28a0e96SMatthew Wilcox (Oracle) static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask)
1564d791ea67SNeilBrown {
1565d791ea67SNeilBrown 	if (gfp_mask & __GFP_FS)
1566d791ea67SNeilBrown 		return true;
1567c28a0e96SMatthew Wilcox (Oracle) 	if (!folio_test_swapcache(folio) || !(gfp_mask & __GFP_IO))
1568d791ea67SNeilBrown 		return false;
1569d791ea67SNeilBrown 	/*
1570d791ea67SNeilBrown 	 * We can "enter_fs" for swap-cache with only __GFP_IO
1571d791ea67SNeilBrown 	 * providing this isn't SWP_FS_OPS.
1572d791ea67SNeilBrown 	 * ->flags can be updated non-atomicially (scan_swap_map_slots),
1573d791ea67SNeilBrown 	 * but that will never affect SWP_FS_OPS, so the data_race
1574d791ea67SNeilBrown 	 * is safe.
1575d791ea67SNeilBrown 	 */
1576c28a0e96SMatthew Wilcox (Oracle) 	return !data_race(page_swap_flags(&folio->page) & SWP_FS_OPS);
1577d791ea67SNeilBrown }
1578d791ea67SNeilBrown 
1579e286781dSNick Piggin /*
15801742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
15811da177e4SLinus Torvalds  */
1582730ec8c0SManinder Singh static unsigned int shrink_page_list(struct list_head *page_list,
1583599d0c95SMel Gorman 				     struct pglist_data *pgdat,
1584f84f6e2bSMel Gorman 				     struct scan_control *sc,
15853c710c1aSMichal Hocko 				     struct reclaim_stat *stat,
15868940b34aSMinchan Kim 				     bool ignore_references)
15871da177e4SLinus Torvalds {
15881da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
1589abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
159026aa2d19SDave Hansen 	LIST_HEAD(demote_pages);
1591730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
1592730ec8c0SManinder Singh 	unsigned int pgactivate = 0;
159326aa2d19SDave Hansen 	bool do_demote_pass;
15942282679fSNeilBrown 	struct swap_iocb *plug = NULL;
15951da177e4SLinus Torvalds 
1596060f005fSKirill Tkhai 	memset(stat, 0, sizeof(*stat));
15971da177e4SLinus Torvalds 	cond_resched();
159826aa2d19SDave Hansen 	do_demote_pass = can_demote(pgdat->node_id, sc);
15991da177e4SLinus Torvalds 
160026aa2d19SDave Hansen retry:
16011da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
16021da177e4SLinus Torvalds 		struct address_space *mapping;
1603be7c07d6SMatthew Wilcox (Oracle) 		struct folio *folio;
16048940b34aSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM;
1605d791ea67SNeilBrown 		bool dirty, writeback;
160698879b3bSYang Shi 		unsigned int nr_pages;
16071da177e4SLinus Torvalds 
16081da177e4SLinus Torvalds 		cond_resched();
16091da177e4SLinus Torvalds 
1610be7c07d6SMatthew Wilcox (Oracle) 		folio = lru_to_folio(page_list);
1611be7c07d6SMatthew Wilcox (Oracle) 		list_del(&folio->lru);
16121da177e4SLinus Torvalds 
1613c28a0e96SMatthew Wilcox (Oracle) 		if (!folio_trylock(folio))
16141da177e4SLinus Torvalds 			goto keep;
16151da177e4SLinus Torvalds 
1616c28a0e96SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
16171da177e4SLinus Torvalds 
1618c28a0e96SMatthew Wilcox (Oracle) 		nr_pages = folio_nr_pages(folio);
161998879b3bSYang Shi 
1620c28a0e96SMatthew Wilcox (Oracle) 		/* Account the number of base pages */
162198879b3bSYang Shi 		sc->nr_scanned += nr_pages;
162280e43426SChristoph Lameter 
1623c28a0e96SMatthew Wilcox (Oracle) 		if (unlikely(!folio_evictable(folio)))
1624ad6b6704SMinchan Kim 			goto activate_locked;
1625894bc310SLee Schermerhorn 
16261bee2c16SMatthew Wilcox (Oracle) 		if (!sc->may_unmap && folio_mapped(folio))
162780e43426SChristoph Lameter 			goto keep_locked;
162880e43426SChristoph Lameter 
1629e62e384eSMichal Hocko 		/*
1630894befecSAndrey Ryabinin 		 * The number of dirty pages determines if a node is marked
16318cd7c588SMel Gorman 		 * reclaim_congested. kswapd will stall and start writing
1632c28a0e96SMatthew Wilcox (Oracle) 		 * folios if the tail of the LRU is all dirty unqueued folios.
1633e2be15f6SMel Gorman 		 */
1634e20c41b1SMatthew Wilcox (Oracle) 		folio_check_dirty_writeback(folio, &dirty, &writeback);
1635e2be15f6SMel Gorman 		if (dirty || writeback)
1636c79b7b96SMatthew Wilcox (Oracle) 			stat->nr_dirty += nr_pages;
1637e2be15f6SMel Gorman 
1638e2be15f6SMel Gorman 		if (dirty && !writeback)
1639c79b7b96SMatthew Wilcox (Oracle) 			stat->nr_unqueued_dirty += nr_pages;
1640e2be15f6SMel Gorman 
1641d04e8acdSMel Gorman 		/*
1642c28a0e96SMatthew Wilcox (Oracle) 		 * Treat this folio as congested if folios are cycling
1643c28a0e96SMatthew Wilcox (Oracle) 		 * through the LRU so quickly that the folios marked
1644c28a0e96SMatthew Wilcox (Oracle) 		 * for immediate reclaim are making it to the end of
1645c28a0e96SMatthew Wilcox (Oracle) 		 * the LRU a second time.
1646d04e8acdSMel Gorman 		 */
1647c28a0e96SMatthew Wilcox (Oracle) 		if (writeback && folio_test_reclaim(folio))
1648c79b7b96SMatthew Wilcox (Oracle) 			stat->nr_congested += nr_pages;
1649e2be15f6SMel Gorman 
1650e2be15f6SMel Gorman 		/*
1651d33e4e14SMatthew Wilcox (Oracle) 		 * If a folio at the tail of the LRU is under writeback, there
1652283aba9fSMel Gorman 		 * are three cases to consider.
1653e62e384eSMichal Hocko 		 *
1654c28a0e96SMatthew Wilcox (Oracle) 		 * 1) If reclaim is encountering an excessive number
1655c28a0e96SMatthew Wilcox (Oracle) 		 *    of folios under writeback and this folio has both
1656c28a0e96SMatthew Wilcox (Oracle) 		 *    the writeback and reclaim flags set, then it
1657d33e4e14SMatthew Wilcox (Oracle) 		 *    indicates that folios are being queued for I/O but
1658d33e4e14SMatthew Wilcox (Oracle) 		 *    are being recycled through the LRU before the I/O
1659d33e4e14SMatthew Wilcox (Oracle) 		 *    can complete. Waiting on the folio itself risks an
1660d33e4e14SMatthew Wilcox (Oracle) 		 *    indefinite stall if it is impossible to writeback
1661d33e4e14SMatthew Wilcox (Oracle) 		 *    the folio due to I/O error or disconnected storage
1662d33e4e14SMatthew Wilcox (Oracle) 		 *    so instead note that the LRU is being scanned too
1663d33e4e14SMatthew Wilcox (Oracle) 		 *    quickly and the caller can stall after the folio
1664d33e4e14SMatthew Wilcox (Oracle) 		 *    list has been processed.
1665c3b94f44SHugh Dickins 		 *
1666d33e4e14SMatthew Wilcox (Oracle) 		 * 2) Global or new memcg reclaim encounters a folio that is
1667ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1668ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1669d33e4e14SMatthew Wilcox (Oracle) 		 *    not to fs). In this case mark the folio for immediate
167097c9341fSTejun Heo 		 *    reclaim and continue scanning.
1671283aba9fSMel Gorman 		 *
1672d791ea67SNeilBrown 		 *    Require may_enter_fs() because we would wait on fs, which
1673d33e4e14SMatthew Wilcox (Oracle) 		 *    may not have submitted I/O yet. And the loop driver might
1674d33e4e14SMatthew Wilcox (Oracle) 		 *    enter reclaim, and deadlock if it waits on a folio for
1675283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1676283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1677283aba9fSMel Gorman 		 *    would probably show more reasons.
1678283aba9fSMel Gorman 		 *
1679d33e4e14SMatthew Wilcox (Oracle) 		 * 3) Legacy memcg encounters a folio that already has the
1680d33e4e14SMatthew Wilcox (Oracle) 		 *    reclaim flag set. memcg does not have any dirty folio
1681283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1682d33e4e14SMatthew Wilcox (Oracle) 		 *    folios are in writeback and there is nothing else to
1683283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1684c55e8d03SJohannes Weiner 		 *
1685d33e4e14SMatthew Wilcox (Oracle) 		 * In cases 1) and 2) we activate the folios to get them out of
1686d33e4e14SMatthew Wilcox (Oracle) 		 * the way while we continue scanning for clean folios on the
1687c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1688c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1689c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1690c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1691c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1692c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1693e62e384eSMichal Hocko 		 */
1694d33e4e14SMatthew Wilcox (Oracle) 		if (folio_test_writeback(folio)) {
1695283aba9fSMel Gorman 			/* Case 1 above */
1696283aba9fSMel Gorman 			if (current_is_kswapd() &&
1697d33e4e14SMatthew Wilcox (Oracle) 			    folio_test_reclaim(folio) &&
1698599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1699c79b7b96SMatthew Wilcox (Oracle) 				stat->nr_immediate += nr_pages;
1700c55e8d03SJohannes Weiner 				goto activate_locked;
1701283aba9fSMel Gorman 
1702283aba9fSMel Gorman 			/* Case 2 above */
1703b5ead35eSJohannes Weiner 			} else if (writeback_throttling_sane(sc) ||
1704d33e4e14SMatthew Wilcox (Oracle) 			    !folio_test_reclaim(folio) ||
1705c28a0e96SMatthew Wilcox (Oracle) 			    !may_enter_fs(folio, sc->gfp_mask)) {
1706c3b94f44SHugh Dickins 				/*
1707d33e4e14SMatthew Wilcox (Oracle) 				 * This is slightly racy -
1708c28a0e96SMatthew Wilcox (Oracle) 				 * folio_end_writeback() might have
1709c28a0e96SMatthew Wilcox (Oracle) 				 * just cleared the reclaim flag, then
1710c28a0e96SMatthew Wilcox (Oracle) 				 * setting the reclaim flag here ends up
1711c28a0e96SMatthew Wilcox (Oracle) 				 * interpreted as the readahead flag - but
1712c28a0e96SMatthew Wilcox (Oracle) 				 * that does not matter enough to care.
1713c28a0e96SMatthew Wilcox (Oracle) 				 * What we do want is for this folio to
1714c28a0e96SMatthew Wilcox (Oracle) 				 * have the reclaim flag set next time
1715c28a0e96SMatthew Wilcox (Oracle) 				 * memcg reclaim reaches the tests above,
1716c28a0e96SMatthew Wilcox (Oracle) 				 * so it will then wait for writeback to
1717c28a0e96SMatthew Wilcox (Oracle) 				 * avoid OOM; and it's also appropriate
1718d33e4e14SMatthew Wilcox (Oracle) 				 * in global reclaim.
1719c3b94f44SHugh Dickins 				 */
1720d33e4e14SMatthew Wilcox (Oracle) 				folio_set_reclaim(folio);
1721c79b7b96SMatthew Wilcox (Oracle) 				stat->nr_writeback += nr_pages;
1722c55e8d03SJohannes Weiner 				goto activate_locked;
1723283aba9fSMel Gorman 
1724283aba9fSMel Gorman 			/* Case 3 above */
1725283aba9fSMel Gorman 			} else {
1726d33e4e14SMatthew Wilcox (Oracle) 				folio_unlock(folio);
1727d33e4e14SMatthew Wilcox (Oracle) 				folio_wait_writeback(folio);
1728d33e4e14SMatthew Wilcox (Oracle) 				/* then go back and try same folio again */
1729d33e4e14SMatthew Wilcox (Oracle) 				list_add_tail(&folio->lru, page_list);
17307fadc820SHugh Dickins 				continue;
1731e62e384eSMichal Hocko 			}
1732283aba9fSMel Gorman 		}
17331da177e4SLinus Torvalds 
17348940b34aSMinchan Kim 		if (!ignore_references)
1735d92013d1SMatthew Wilcox (Oracle) 			references = folio_check_references(folio, sc);
173602c6de8dSMinchan Kim 
1737dfc8d636SJohannes Weiner 		switch (references) {
1738dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
17391da177e4SLinus Torvalds 			goto activate_locked;
174064574746SJohannes Weiner 		case PAGEREF_KEEP:
174198879b3bSYang Shi 			stat->nr_ref_keep += nr_pages;
174264574746SJohannes Weiner 			goto keep_locked;
1743dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1744dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1745c28a0e96SMatthew Wilcox (Oracle) 			; /* try to reclaim the folio below */
1746dfc8d636SJohannes Weiner 		}
17471da177e4SLinus Torvalds 
17481da177e4SLinus Torvalds 		/*
1749c28a0e96SMatthew Wilcox (Oracle) 		 * Before reclaiming the folio, try to relocate
175026aa2d19SDave Hansen 		 * its contents to another node.
175126aa2d19SDave Hansen 		 */
175226aa2d19SDave Hansen 		if (do_demote_pass &&
1753c28a0e96SMatthew Wilcox (Oracle) 		    (thp_migration_supported() || !folio_test_large(folio))) {
1754c28a0e96SMatthew Wilcox (Oracle) 			list_add(&folio->lru, &demote_pages);
1755c28a0e96SMatthew Wilcox (Oracle) 			folio_unlock(folio);
175626aa2d19SDave Hansen 			continue;
175726aa2d19SDave Hansen 		}
175826aa2d19SDave Hansen 
175926aa2d19SDave Hansen 		/*
17601da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
17611da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1762c28a0e96SMatthew Wilcox (Oracle) 		 * Lazyfree folio could be freed directly
17631da177e4SLinus Torvalds 		 */
1764c28a0e96SMatthew Wilcox (Oracle) 		if (folio_test_anon(folio) && folio_test_swapbacked(folio)) {
1765c28a0e96SMatthew Wilcox (Oracle) 			if (!folio_test_swapcache(folio)) {
176663eb6b93SHugh Dickins 				if (!(sc->gfp_mask & __GFP_IO))
176763eb6b93SHugh Dickins 					goto keep_locked;
1768d4b4084aSMatthew Wilcox (Oracle) 				if (folio_maybe_dma_pinned(folio))
1769feb889fbSLinus Torvalds 					goto keep_locked;
1770c28a0e96SMatthew Wilcox (Oracle) 				if (folio_test_large(folio)) {
1771c28a0e96SMatthew Wilcox (Oracle) 					/* cannot split folio, skip it */
1772d4b4084aSMatthew Wilcox (Oracle) 					if (!can_split_folio(folio, NULL))
1773b8f593cdSHuang Ying 						goto activate_locked;
1774747552b1SHuang Ying 					/*
1775c28a0e96SMatthew Wilcox (Oracle) 					 * Split folios without a PMD map right
1776747552b1SHuang Ying 					 * away. Chances are some or all of the
1777747552b1SHuang Ying 					 * tail pages can be freed without IO.
1778747552b1SHuang Ying 					 */
1779d4b4084aSMatthew Wilcox (Oracle) 					if (!folio_entire_mapcount(folio) &&
1780346cf613SMatthew Wilcox (Oracle) 					    split_folio_to_list(folio,
1781bd4c82c2SHuang Ying 								page_list))
1782747552b1SHuang Ying 						goto activate_locked;
1783747552b1SHuang Ying 				}
178409c02e56SMatthew Wilcox (Oracle) 				if (!add_to_swap(folio)) {
178509c02e56SMatthew Wilcox (Oracle) 					if (!folio_test_large(folio))
178698879b3bSYang Shi 						goto activate_locked_split;
1787bd4c82c2SHuang Ying 					/* Fallback to swap normal pages */
1788346cf613SMatthew Wilcox (Oracle) 					if (split_folio_to_list(folio,
1789bd4c82c2SHuang Ying 								page_list))
17900f074658SMinchan Kim 						goto activate_locked;
1791fe490cc0SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1792fe490cc0SHuang Ying 					count_vm_event(THP_SWPOUT_FALLBACK);
1793fe490cc0SHuang Ying #endif
179409c02e56SMatthew Wilcox (Oracle) 					if (!add_to_swap(folio))
179598879b3bSYang Shi 						goto activate_locked_split;
17960f074658SMinchan Kim 				}
1797bd4c82c2SHuang Ying 			}
1798c28a0e96SMatthew Wilcox (Oracle) 		} else if (folio_test_swapbacked(folio) &&
1799c28a0e96SMatthew Wilcox (Oracle) 			   folio_test_large(folio)) {
1800c28a0e96SMatthew Wilcox (Oracle) 			/* Split shmem folio */
1801346cf613SMatthew Wilcox (Oracle) 			if (split_folio_to_list(folio, page_list))
18027751b2daSKirill A. Shutemov 				goto keep_locked;
1803e2be15f6SMel Gorman 		}
18041da177e4SLinus Torvalds 
18051da177e4SLinus Torvalds 		/*
1806c28a0e96SMatthew Wilcox (Oracle) 		 * If the folio was split above, the tail pages will make
1807c28a0e96SMatthew Wilcox (Oracle) 		 * their own pass through this function and be accounted
1808c28a0e96SMatthew Wilcox (Oracle) 		 * then.
180998879b3bSYang Shi 		 */
1810c28a0e96SMatthew Wilcox (Oracle) 		if ((nr_pages > 1) && !folio_test_large(folio)) {
181198879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
181298879b3bSYang Shi 			nr_pages = 1;
181398879b3bSYang Shi 		}
181498879b3bSYang Shi 
181598879b3bSYang Shi 		/*
18161bee2c16SMatthew Wilcox (Oracle) 		 * The folio is mapped into the page tables of one or more
18171da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
18181da177e4SLinus Torvalds 		 */
18191bee2c16SMatthew Wilcox (Oracle) 		if (folio_mapped(folio)) {
1820013339dfSShakeel Butt 			enum ttu_flags flags = TTU_BATCH_FLUSH;
18211bee2c16SMatthew Wilcox (Oracle) 			bool was_swapbacked = folio_test_swapbacked(folio);
1822bd4c82c2SHuang Ying 
18231bee2c16SMatthew Wilcox (Oracle) 			if (folio_test_pmd_mappable(folio))
1824bd4c82c2SHuang Ying 				flags |= TTU_SPLIT_HUGE_PMD;
18251f318a9bSJaewon Kim 
1826869f7ee6SMatthew Wilcox (Oracle) 			try_to_unmap(folio, flags);
18271bee2c16SMatthew Wilcox (Oracle) 			if (folio_mapped(folio)) {
182898879b3bSYang Shi 				stat->nr_unmap_fail += nr_pages;
18291bee2c16SMatthew Wilcox (Oracle) 				if (!was_swapbacked &&
18301bee2c16SMatthew Wilcox (Oracle) 				    folio_test_swapbacked(folio))
18311f318a9bSJaewon Kim 					stat->nr_lazyfree_fail += nr_pages;
18321da177e4SLinus Torvalds 				goto activate_locked;
18331da177e4SLinus Torvalds 			}
18341da177e4SLinus Torvalds 		}
18351da177e4SLinus Torvalds 
18365441d490SMatthew Wilcox (Oracle) 		mapping = folio_mapping(folio);
183749bd2bf9SMatthew Wilcox (Oracle) 		if (folio_test_dirty(folio)) {
1838ee72886dSMel Gorman 			/*
183949bd2bf9SMatthew Wilcox (Oracle) 			 * Only kswapd can writeback filesystem folios
18404eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
184149bd2bf9SMatthew Wilcox (Oracle) 			 * injecting inefficient single-folio I/O into
18424eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
184349bd2bf9SMatthew Wilcox (Oracle) 			 * write folios when we've encountered many
184449bd2bf9SMatthew Wilcox (Oracle) 			 * dirty folios, and when we've already scanned
184549bd2bf9SMatthew Wilcox (Oracle) 			 * the rest of the LRU for clean folios and see
184649bd2bf9SMatthew Wilcox (Oracle) 			 * the same dirty folios again (with the reclaim
184749bd2bf9SMatthew Wilcox (Oracle) 			 * flag set).
1848ee72886dSMel Gorman 			 */
184949bd2bf9SMatthew Wilcox (Oracle) 			if (folio_is_file_lru(folio) &&
185049bd2bf9SMatthew Wilcox (Oracle) 			    (!current_is_kswapd() ||
185149bd2bf9SMatthew Wilcox (Oracle) 			     !folio_test_reclaim(folio) ||
1852599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
185349ea7eb6SMel Gorman 				/*
185449ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
185549bd2bf9SMatthew Wilcox (Oracle) 				 * Similar in principle to deactivate_page()
185649bd2bf9SMatthew Wilcox (Oracle) 				 * except we already have the folio isolated
185749ea7eb6SMel Gorman 				 * and know it's dirty
185849ea7eb6SMel Gorman 				 */
185949bd2bf9SMatthew Wilcox (Oracle) 				node_stat_mod_folio(folio, NR_VMSCAN_IMMEDIATE,
186049bd2bf9SMatthew Wilcox (Oracle) 						nr_pages);
186149bd2bf9SMatthew Wilcox (Oracle) 				folio_set_reclaim(folio);
186249ea7eb6SMel Gorman 
1863c55e8d03SJohannes Weiner 				goto activate_locked;
1864ee72886dSMel Gorman 			}
1865ee72886dSMel Gorman 
1866dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
18671da177e4SLinus Torvalds 				goto keep_locked;
1868c28a0e96SMatthew Wilcox (Oracle) 			if (!may_enter_fs(folio, sc->gfp_mask))
18691da177e4SLinus Torvalds 				goto keep_locked;
187052a8363eSChristoph Lameter 			if (!sc->may_writepage)
18711da177e4SLinus Torvalds 				goto keep_locked;
18721da177e4SLinus Torvalds 
1873d950c947SMel Gorman 			/*
187449bd2bf9SMatthew Wilcox (Oracle) 			 * Folio is dirty. Flush the TLB if a writable entry
187549bd2bf9SMatthew Wilcox (Oracle) 			 * potentially exists to avoid CPU writes after I/O
1876d950c947SMel Gorman 			 * starts and then write it out here.
1877d950c947SMel Gorman 			 */
1878d950c947SMel Gorman 			try_to_unmap_flush_dirty();
18792282679fSNeilBrown 			switch (pageout(folio, mapping, &plug)) {
18801da177e4SLinus Torvalds 			case PAGE_KEEP:
18811da177e4SLinus Torvalds 				goto keep_locked;
18821da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
18831da177e4SLinus Torvalds 				goto activate_locked;
18841da177e4SLinus Torvalds 			case PAGE_SUCCESS:
1885c79b7b96SMatthew Wilcox (Oracle) 				stat->nr_pageout += nr_pages;
188696f8bf4fSJohannes Weiner 
188749bd2bf9SMatthew Wilcox (Oracle) 				if (folio_test_writeback(folio))
188841ac1999SMel Gorman 					goto keep;
188949bd2bf9SMatthew Wilcox (Oracle) 				if (folio_test_dirty(folio))
18901da177e4SLinus Torvalds 					goto keep;
18917d3579e8SKOSAKI Motohiro 
18921da177e4SLinus Torvalds 				/*
18931da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
189449bd2bf9SMatthew Wilcox (Oracle) 				 * ahead and try to reclaim the folio.
18951da177e4SLinus Torvalds 				 */
189649bd2bf9SMatthew Wilcox (Oracle) 				if (!folio_trylock(folio))
18971da177e4SLinus Torvalds 					goto keep;
189849bd2bf9SMatthew Wilcox (Oracle) 				if (folio_test_dirty(folio) ||
189949bd2bf9SMatthew Wilcox (Oracle) 				    folio_test_writeback(folio))
19001da177e4SLinus Torvalds 					goto keep_locked;
190149bd2bf9SMatthew Wilcox (Oracle) 				mapping = folio_mapping(folio);
190201359eb2SGustavo A. R. Silva 				fallthrough;
19031da177e4SLinus Torvalds 			case PAGE_CLEAN:
190449bd2bf9SMatthew Wilcox (Oracle) 				; /* try to free the folio below */
19051da177e4SLinus Torvalds 			}
19061da177e4SLinus Torvalds 		}
19071da177e4SLinus Torvalds 
19081da177e4SLinus Torvalds 		/*
19090a36111cSMatthew Wilcox (Oracle) 		 * If the folio has buffers, try to free the buffer
19100a36111cSMatthew Wilcox (Oracle) 		 * mappings associated with this folio. If we succeed
19110a36111cSMatthew Wilcox (Oracle) 		 * we try to free the folio as well.
19121da177e4SLinus Torvalds 		 *
19130a36111cSMatthew Wilcox (Oracle) 		 * We do this even if the folio is dirty.
19140a36111cSMatthew Wilcox (Oracle) 		 * filemap_release_folio() does not perform I/O, but it
19150a36111cSMatthew Wilcox (Oracle) 		 * is possible for a folio to have the dirty flag set,
19160a36111cSMatthew Wilcox (Oracle) 		 * but it is actually clean (all its buffers are clean).
19170a36111cSMatthew Wilcox (Oracle) 		 * This happens if the buffers were written out directly,
19180a36111cSMatthew Wilcox (Oracle) 		 * with submit_bh(). ext3 will do this, as well as
19190a36111cSMatthew Wilcox (Oracle) 		 * the blockdev mapping.  filemap_release_folio() will
19200a36111cSMatthew Wilcox (Oracle) 		 * discover that cleanness and will drop the buffers
19210a36111cSMatthew Wilcox (Oracle) 		 * and mark the folio clean - it can be freed.
19221da177e4SLinus Torvalds 		 *
19230a36111cSMatthew Wilcox (Oracle) 		 * Rarely, folios can have buffers and no ->mapping.
19240a36111cSMatthew Wilcox (Oracle) 		 * These are the folios which were not successfully
19250a36111cSMatthew Wilcox (Oracle) 		 * invalidated in truncate_cleanup_folio().  We try to
19260a36111cSMatthew Wilcox (Oracle) 		 * drop those buffers here and if that worked, and the
19270a36111cSMatthew Wilcox (Oracle) 		 * folio is no longer mapped into process address space
19280a36111cSMatthew Wilcox (Oracle) 		 * (refcount == 1) it can be freed.  Otherwise, leave
19290a36111cSMatthew Wilcox (Oracle) 		 * the folio on the LRU so it is swappable.
19301da177e4SLinus Torvalds 		 */
19310a36111cSMatthew Wilcox (Oracle) 		if (folio_has_private(folio)) {
19320a36111cSMatthew Wilcox (Oracle) 			if (!filemap_release_folio(folio, sc->gfp_mask))
19331da177e4SLinus Torvalds 				goto activate_locked;
19340a36111cSMatthew Wilcox (Oracle) 			if (!mapping && folio_ref_count(folio) == 1) {
19350a36111cSMatthew Wilcox (Oracle) 				folio_unlock(folio);
19360a36111cSMatthew Wilcox (Oracle) 				if (folio_put_testzero(folio))
19371da177e4SLinus Torvalds 					goto free_it;
1938e286781dSNick Piggin 				else {
1939e286781dSNick Piggin 					/*
1940e286781dSNick Piggin 					 * rare race with speculative reference.
1941e286781dSNick Piggin 					 * the speculative reference will free
19420a36111cSMatthew Wilcox (Oracle) 					 * this folio shortly, so we may
1943e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1944e286781dSNick Piggin 					 * leave it off the LRU).
1945e286781dSNick Piggin 					 */
19469aafcffcSMiaohe Lin 					nr_reclaimed += nr_pages;
1947e286781dSNick Piggin 					continue;
1948e286781dSNick Piggin 				}
1949e286781dSNick Piggin 			}
19501da177e4SLinus Torvalds 		}
19511da177e4SLinus Torvalds 
195264daa5d8SMatthew Wilcox (Oracle) 		if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) {
1953802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
195464daa5d8SMatthew Wilcox (Oracle) 			if (!folio_ref_freeze(folio, 1))
195549d2e9ccSChristoph Lameter 				goto keep_locked;
1956d17be2d9SMiaohe Lin 			/*
195764daa5d8SMatthew Wilcox (Oracle) 			 * The folio has only one reference left, which is
1958d17be2d9SMiaohe Lin 			 * from the isolation. After the caller puts the
195964daa5d8SMatthew Wilcox (Oracle) 			 * folio back on the lru and drops the reference, the
196064daa5d8SMatthew Wilcox (Oracle) 			 * folio will be freed anyway. It doesn't matter
196164daa5d8SMatthew Wilcox (Oracle) 			 * which lru it goes on. So we don't bother checking
196264daa5d8SMatthew Wilcox (Oracle) 			 * the dirty flag here.
1963d17be2d9SMiaohe Lin 			 */
196464daa5d8SMatthew Wilcox (Oracle) 			count_vm_events(PGLAZYFREED, nr_pages);
196564daa5d8SMatthew Wilcox (Oracle) 			count_memcg_folio_events(folio, PGLAZYFREED, nr_pages);
1966be7c07d6SMatthew Wilcox (Oracle) 		} else if (!mapping || !__remove_mapping(mapping, folio, true,
1967b910718aSJohannes Weiner 							 sc->target_mem_cgroup))
1968802a3a92SShaohua Li 			goto keep_locked;
19699a1ea439SHugh Dickins 
1970c28a0e96SMatthew Wilcox (Oracle) 		folio_unlock(folio);
1971e286781dSNick Piggin free_it:
197298879b3bSYang Shi 		/*
1973c28a0e96SMatthew Wilcox (Oracle) 		 * Folio may get swapped out as a whole, need to account
1974c28a0e96SMatthew Wilcox (Oracle) 		 * all pages in it.
197598879b3bSYang Shi 		 */
197698879b3bSYang Shi 		nr_reclaimed += nr_pages;
1977abe4c3b5SMel Gorman 
1978abe4c3b5SMel Gorman 		/*
1979abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1980abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1981abe4c3b5SMel Gorman 		 */
1982c28a0e96SMatthew Wilcox (Oracle) 		if (unlikely(folio_test_large(folio)))
1983c28a0e96SMatthew Wilcox (Oracle) 			destroy_compound_page(&folio->page);
19847ae88534SYang Shi 		else
1985c28a0e96SMatthew Wilcox (Oracle) 			list_add(&folio->lru, &free_pages);
19861da177e4SLinus Torvalds 		continue;
19871da177e4SLinus Torvalds 
198898879b3bSYang Shi activate_locked_split:
198998879b3bSYang Shi 		/*
199098879b3bSYang Shi 		 * The tail pages that are failed to add into swap cache
199198879b3bSYang Shi 		 * reach here.  Fixup nr_scanned and nr_pages.
199298879b3bSYang Shi 		 */
199398879b3bSYang Shi 		if (nr_pages > 1) {
199498879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
199598879b3bSYang Shi 			nr_pages = 1;
199698879b3bSYang Shi 		}
19971da177e4SLinus Torvalds activate_locked:
199868a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
1999246b6480SMatthew Wilcox (Oracle) 		if (folio_test_swapcache(folio) &&
2000246b6480SMatthew Wilcox (Oracle) 		    (mem_cgroup_swap_full(&folio->page) ||
2001246b6480SMatthew Wilcox (Oracle) 		     folio_test_mlocked(folio)))
2002246b6480SMatthew Wilcox (Oracle) 			try_to_free_swap(&folio->page);
2003246b6480SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
2004246b6480SMatthew Wilcox (Oracle) 		if (!folio_test_mlocked(folio)) {
2005246b6480SMatthew Wilcox (Oracle) 			int type = folio_is_file_lru(folio);
2006246b6480SMatthew Wilcox (Oracle) 			folio_set_active(folio);
200798879b3bSYang Shi 			stat->nr_activate[type] += nr_pages;
2008246b6480SMatthew Wilcox (Oracle) 			count_memcg_folio_events(folio, PGACTIVATE, nr_pages);
2009ad6b6704SMinchan Kim 		}
20101da177e4SLinus Torvalds keep_locked:
2011c28a0e96SMatthew Wilcox (Oracle) 		folio_unlock(folio);
20121da177e4SLinus Torvalds keep:
2013c28a0e96SMatthew Wilcox (Oracle) 		list_add(&folio->lru, &ret_pages);
2014c28a0e96SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(folio_test_lru(folio) ||
2015c28a0e96SMatthew Wilcox (Oracle) 				folio_test_unevictable(folio), folio);
20161da177e4SLinus Torvalds 	}
201726aa2d19SDave Hansen 	/* 'page_list' is always empty here */
201826aa2d19SDave Hansen 
2019c28a0e96SMatthew Wilcox (Oracle) 	/* Migrate folios selected for demotion */
202026aa2d19SDave Hansen 	nr_reclaimed += demote_page_list(&demote_pages, pgdat);
2021c28a0e96SMatthew Wilcox (Oracle) 	/* Folios that could not be demoted are still in @demote_pages */
202226aa2d19SDave Hansen 	if (!list_empty(&demote_pages)) {
2023c28a0e96SMatthew Wilcox (Oracle) 		/* Folios which weren't demoted go back on @page_list for retry: */
202426aa2d19SDave Hansen 		list_splice_init(&demote_pages, page_list);
202526aa2d19SDave Hansen 		do_demote_pass = false;
202626aa2d19SDave Hansen 		goto retry;
202726aa2d19SDave Hansen 	}
2028abe4c3b5SMel Gorman 
202998879b3bSYang Shi 	pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
203098879b3bSYang Shi 
2031747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
203272b252aeSMel Gorman 	try_to_unmap_flush();
20332d4894b5SMel Gorman 	free_unref_page_list(&free_pages);
2034abe4c3b5SMel Gorman 
20351da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
2036886cf190SKirill Tkhai 	count_vm_events(PGACTIVATE, pgactivate);
20370a31bc97SJohannes Weiner 
20382282679fSNeilBrown 	if (plug)
20392282679fSNeilBrown 		swap_write_unplug(plug);
204005ff5137SAndrew Morton 	return nr_reclaimed;
20411da177e4SLinus Torvalds }
20421da177e4SLinus Torvalds 
2043730ec8c0SManinder Singh unsigned int reclaim_clean_pages_from_list(struct zone *zone,
2044b8cecb93SMatthew Wilcox (Oracle) 					    struct list_head *folio_list)
204502c6de8dSMinchan Kim {
204602c6de8dSMinchan Kim 	struct scan_control sc = {
204702c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
204802c6de8dSMinchan Kim 		.may_unmap = 1,
204902c6de8dSMinchan Kim 	};
20501f318a9bSJaewon Kim 	struct reclaim_stat stat;
2051730ec8c0SManinder Singh 	unsigned int nr_reclaimed;
2052b8cecb93SMatthew Wilcox (Oracle) 	struct folio *folio, *next;
2053b8cecb93SMatthew Wilcox (Oracle) 	LIST_HEAD(clean_folios);
20542d2b8d2bSYu Zhao 	unsigned int noreclaim_flag;
205502c6de8dSMinchan Kim 
2056b8cecb93SMatthew Wilcox (Oracle) 	list_for_each_entry_safe(folio, next, folio_list, lru) {
2057b8cecb93SMatthew Wilcox (Oracle) 		if (!folio_test_hugetlb(folio) && folio_is_file_lru(folio) &&
2058b8cecb93SMatthew Wilcox (Oracle) 		    !folio_test_dirty(folio) && !__folio_test_movable(folio) &&
2059b8cecb93SMatthew Wilcox (Oracle) 		    !folio_test_unevictable(folio)) {
2060b8cecb93SMatthew Wilcox (Oracle) 			folio_clear_active(folio);
2061b8cecb93SMatthew Wilcox (Oracle) 			list_move(&folio->lru, &clean_folios);
206202c6de8dSMinchan Kim 		}
206302c6de8dSMinchan Kim 	}
206402c6de8dSMinchan Kim 
20652d2b8d2bSYu Zhao 	/*
20662d2b8d2bSYu Zhao 	 * We should be safe here since we are only dealing with file pages and
20672d2b8d2bSYu Zhao 	 * we are not kswapd and therefore cannot write dirty file pages. But
20682d2b8d2bSYu Zhao 	 * call memalloc_noreclaim_save() anyway, just in case these conditions
20692d2b8d2bSYu Zhao 	 * change in the future.
20702d2b8d2bSYu Zhao 	 */
20712d2b8d2bSYu Zhao 	noreclaim_flag = memalloc_noreclaim_save();
2072b8cecb93SMatthew Wilcox (Oracle) 	nr_reclaimed = shrink_page_list(&clean_folios, zone->zone_pgdat, &sc,
2073013339dfSShakeel Butt 					&stat, true);
20742d2b8d2bSYu Zhao 	memalloc_noreclaim_restore(noreclaim_flag);
20752d2b8d2bSYu Zhao 
2076b8cecb93SMatthew Wilcox (Oracle) 	list_splice(&clean_folios, folio_list);
20772da9f630SNicholas Piggin 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
20782da9f630SNicholas Piggin 			    -(long)nr_reclaimed);
20791f318a9bSJaewon Kim 	/*
20801f318a9bSJaewon Kim 	 * Since lazyfree pages are isolated from file LRU from the beginning,
20811f318a9bSJaewon Kim 	 * they will rotate back to anonymous LRU in the end if it failed to
20821f318a9bSJaewon Kim 	 * discard so isolated count will be mismatched.
20831f318a9bSJaewon Kim 	 * Compensate the isolated count for both LRU lists.
20841f318a9bSJaewon Kim 	 */
20851f318a9bSJaewon Kim 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
20861f318a9bSJaewon Kim 			    stat.nr_lazyfree_fail);
20871f318a9bSJaewon Kim 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
20882da9f630SNicholas Piggin 			    -(long)stat.nr_lazyfree_fail);
20891f318a9bSJaewon Kim 	return nr_reclaimed;
209002c6de8dSMinchan Kim }
209102c6de8dSMinchan Kim 
20925ad333ebSAndy Whitcroft /*
20937ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
209455b65a57SEthon Paul  * be complete before mem_cgroup_update_lru_size due to a sanity check.
20957ee36a14SMel Gorman  */
20967ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
2097b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
20987ee36a14SMel Gorman {
20997ee36a14SMel Gorman 	int zid;
21007ee36a14SMel Gorman 
21017ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
21027ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
21037ee36a14SMel Gorman 			continue;
21047ee36a14SMel Gorman 
2105a892cb6bSWei Yang 		update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
21067ee36a14SMel Gorman 	}
21077ee36a14SMel Gorman 
21087ee36a14SMel Gorman }
21097ee36a14SMel Gorman 
2110f611fab7SMel Gorman /*
211115b44736SHugh Dickins  * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
211215b44736SHugh Dickins  *
211315b44736SHugh Dickins  * lruvec->lru_lock is heavily contended.  Some of the functions that
21141da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
21151da177e4SLinus Torvalds  * and working on them outside the LRU lock.
21161da177e4SLinus Torvalds  *
21171da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
21181da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
21191da177e4SLinus Torvalds  *
212015b44736SHugh Dickins  * Lru_lock must be held before calling this function.
21211da177e4SLinus Torvalds  *
2122791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
21235dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
21241da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
2125f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
2126fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
21273cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
21281da177e4SLinus Torvalds  *
21291da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
21301da177e4SLinus Torvalds  */
213169e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
21325dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
2133fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
2134a9e7c39fSKirill Tkhai 		enum lru_list lru)
21351da177e4SLinus Torvalds {
213675b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
213769e05944SAndrew Morton 	unsigned long nr_taken = 0;
2138599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
21397cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
21403db65812SJohannes Weiner 	unsigned long skipped = 0;
2141791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
2142*166e3d32SMatthew Wilcox (Oracle) 	LIST_HEAD(folios_skipped);
21431da177e4SLinus Torvalds 
214498879b3bSYang Shi 	total_scan = 0;
2145791b48b6SMinchan Kim 	scan = 0;
214698879b3bSYang Shi 	while (scan < nr_to_scan && !list_empty(src)) {
214789f6c88aSHugh Dickins 		struct list_head *move_to = src;
2148*166e3d32SMatthew Wilcox (Oracle) 		struct folio *folio;
21495ad333ebSAndy Whitcroft 
2150*166e3d32SMatthew Wilcox (Oracle) 		folio = lru_to_folio(src);
2151*166e3d32SMatthew Wilcox (Oracle) 		prefetchw_prev_lru_folio(folio, src, flags);
21521da177e4SLinus Torvalds 
2153*166e3d32SMatthew Wilcox (Oracle) 		nr_pages = folio_nr_pages(folio);
215498879b3bSYang Shi 		total_scan += nr_pages;
215598879b3bSYang Shi 
2156*166e3d32SMatthew Wilcox (Oracle) 		if (folio_zonenum(folio) > sc->reclaim_idx) {
2157*166e3d32SMatthew Wilcox (Oracle) 			nr_skipped[folio_zonenum(folio)] += nr_pages;
2158*166e3d32SMatthew Wilcox (Oracle) 			move_to = &folios_skipped;
215989f6c88aSHugh Dickins 			goto move;
2160b2e18757SMel Gorman 		}
2161b2e18757SMel Gorman 
2162791b48b6SMinchan Kim 		/*
2163*166e3d32SMatthew Wilcox (Oracle) 		 * Do not count skipped folios because that makes the function
2164*166e3d32SMatthew Wilcox (Oracle) 		 * return with no isolated folios if the LRU mostly contains
2165*166e3d32SMatthew Wilcox (Oracle) 		 * ineligible folios.  This causes the VM to not reclaim any
2166*166e3d32SMatthew Wilcox (Oracle) 		 * folios, triggering a premature OOM.
2167*166e3d32SMatthew Wilcox (Oracle) 		 * Account all pages in a folio.
2168791b48b6SMinchan Kim 		 */
216998879b3bSYang Shi 		scan += nr_pages;
217089f6c88aSHugh Dickins 
2171*166e3d32SMatthew Wilcox (Oracle) 		if (!folio_test_lru(folio))
217289f6c88aSHugh Dickins 			goto move;
2173*166e3d32SMatthew Wilcox (Oracle) 		if (!sc->may_unmap && folio_mapped(folio))
217489f6c88aSHugh Dickins 			goto move;
217589f6c88aSHugh Dickins 
21769df41314SAlex Shi 		/*
2177*166e3d32SMatthew Wilcox (Oracle) 		 * Be careful not to clear the lru flag until after we're
2178*166e3d32SMatthew Wilcox (Oracle) 		 * sure the folio is not being freed elsewhere -- the
2179*166e3d32SMatthew Wilcox (Oracle) 		 * folio release code relies on it.
21809df41314SAlex Shi 		 */
2181*166e3d32SMatthew Wilcox (Oracle) 		if (unlikely(!folio_try_get(folio)))
218289f6c88aSHugh Dickins 			goto move;
21839df41314SAlex Shi 
2184*166e3d32SMatthew Wilcox (Oracle) 		if (!folio_test_clear_lru(folio)) {
2185*166e3d32SMatthew Wilcox (Oracle) 			/* Another thread is already isolating this folio */
2186*166e3d32SMatthew Wilcox (Oracle) 			folio_put(folio);
218789f6c88aSHugh Dickins 			goto move;
21889df41314SAlex Shi 		}
21899df41314SAlex Shi 
2190599d0c95SMel Gorman 		nr_taken += nr_pages;
2191*166e3d32SMatthew Wilcox (Oracle) 		nr_zone_taken[folio_zonenum(folio)] += nr_pages;
219289f6c88aSHugh Dickins 		move_to = dst;
219389f6c88aSHugh Dickins move:
2194*166e3d32SMatthew Wilcox (Oracle) 		list_move(&folio->lru, move_to);
21955ad333ebSAndy Whitcroft 	}
21961da177e4SLinus Torvalds 
2197b2e18757SMel Gorman 	/*
2198*166e3d32SMatthew Wilcox (Oracle) 	 * Splice any skipped folios to the start of the LRU list. Note that
2199b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
2200b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2201*166e3d32SMatthew Wilcox (Oracle) 	 * scanning would soon rescan the same folios to skip and waste lots
2202b2cb6826SMiaohe Lin 	 * of cpu cycles.
2203b2e18757SMel Gorman 	 */
2204*166e3d32SMatthew Wilcox (Oracle) 	if (!list_empty(&folios_skipped)) {
22057cc30fcfSMel Gorman 		int zid;
22067cc30fcfSMel Gorman 
2207*166e3d32SMatthew Wilcox (Oracle) 		list_splice(&folios_skipped, src);
22087cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
22097cc30fcfSMel Gorman 			if (!nr_skipped[zid])
22107cc30fcfSMel Gorman 				continue;
22117cc30fcfSMel Gorman 
22127cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
22131265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
22147cc30fcfSMel Gorman 		}
22157cc30fcfSMel Gorman 	}
2216791b48b6SMinchan Kim 	*nr_scanned = total_scan;
22171265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
221889f6c88aSHugh Dickins 				    total_scan, skipped, nr_taken,
221989f6c88aSHugh Dickins 				    sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
2220b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
22211da177e4SLinus Torvalds 	return nr_taken;
22221da177e4SLinus Torvalds }
22231da177e4SLinus Torvalds 
222462695a84SNick Piggin /**
2225d1d8a3b4SMatthew Wilcox (Oracle)  * folio_isolate_lru() - Try to isolate a folio from its LRU list.
2226d1d8a3b4SMatthew Wilcox (Oracle)  * @folio: Folio to isolate from its LRU list.
222762695a84SNick Piggin  *
2228d1d8a3b4SMatthew Wilcox (Oracle)  * Isolate a @folio from an LRU list and adjust the vmstat statistic
2229d1d8a3b4SMatthew Wilcox (Oracle)  * corresponding to whatever LRU list the folio was on.
223062695a84SNick Piggin  *
2231d1d8a3b4SMatthew Wilcox (Oracle)  * The folio will have its LRU flag cleared.  If it was found on the
2232d1d8a3b4SMatthew Wilcox (Oracle)  * active list, it will have the Active flag set.  If it was found on the
2233d1d8a3b4SMatthew Wilcox (Oracle)  * unevictable list, it will have the Unevictable flag set.  These flags
2234894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
223562695a84SNick Piggin  *
2236d1d8a3b4SMatthew Wilcox (Oracle)  * Context:
2237a5d09bedSMike Rapoport  *
223862695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
2239d1d8a3b4SMatthew Wilcox (Oracle)  *     fundamental difference from isolate_lru_pages() (which is called
224062695a84SNick Piggin  *     without a stable reference).
2241d1d8a3b4SMatthew Wilcox (Oracle)  * (2) The lru_lock must not be held.
2242d1d8a3b4SMatthew Wilcox (Oracle)  * (3) Interrupts must be enabled.
2243d1d8a3b4SMatthew Wilcox (Oracle)  *
2244d1d8a3b4SMatthew Wilcox (Oracle)  * Return: 0 if the folio was removed from an LRU list.
2245d1d8a3b4SMatthew Wilcox (Oracle)  * -EBUSY if the folio was not on an LRU list.
224662695a84SNick Piggin  */
2247d1d8a3b4SMatthew Wilcox (Oracle) int folio_isolate_lru(struct folio *folio)
224862695a84SNick Piggin {
224962695a84SNick Piggin 	int ret = -EBUSY;
225062695a84SNick Piggin 
2251d1d8a3b4SMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(!folio_ref_count(folio), folio);
22520c917313SKonstantin Khlebnikov 
2253d1d8a3b4SMatthew Wilcox (Oracle) 	if (folio_test_clear_lru(folio)) {
2254fa9add64SHugh Dickins 		struct lruvec *lruvec;
225562695a84SNick Piggin 
2256d1d8a3b4SMatthew Wilcox (Oracle) 		folio_get(folio);
2257e809c3feSMatthew Wilcox (Oracle) 		lruvec = folio_lruvec_lock_irq(folio);
2258d1d8a3b4SMatthew Wilcox (Oracle) 		lruvec_del_folio(lruvec, folio);
22596168d0daSAlex Shi 		unlock_page_lruvec_irq(lruvec);
2260fa9add64SHugh Dickins 		ret = 0;
226162695a84SNick Piggin 	}
2262d25b5bd8SAlex Shi 
226362695a84SNick Piggin 	return ret;
226462695a84SNick Piggin }
226562695a84SNick Piggin 
22665ad333ebSAndy Whitcroft /*
2267d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
2268178821b8SXianting Tian  * then get rescheduled. When there are massive number of tasks doing page
2269d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2270d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
2271d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
227235cd7815SRik van Riel  */
2273599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
227435cd7815SRik van Riel 		struct scan_control *sc)
227535cd7815SRik van Riel {
227635cd7815SRik van Riel 	unsigned long inactive, isolated;
2277d818fca1SMel Gorman 	bool too_many;
227835cd7815SRik van Riel 
227935cd7815SRik van Riel 	if (current_is_kswapd())
228035cd7815SRik van Riel 		return 0;
228135cd7815SRik van Riel 
2282b5ead35eSJohannes Weiner 	if (!writeback_throttling_sane(sc))
228335cd7815SRik van Riel 		return 0;
228435cd7815SRik van Riel 
228535cd7815SRik van Riel 	if (file) {
2286599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2287599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
228835cd7815SRik van Riel 	} else {
2289599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2290599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
229135cd7815SRik van Riel 	}
229235cd7815SRik van Riel 
22933cf23841SFengguang Wu 	/*
22943cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
22953cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
22963cf23841SFengguang Wu 	 * deadlock.
22973cf23841SFengguang Wu 	 */
2298d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
22993cf23841SFengguang Wu 		inactive >>= 3;
23003cf23841SFengguang Wu 
2301d818fca1SMel Gorman 	too_many = isolated > inactive;
2302d818fca1SMel Gorman 
2303d818fca1SMel Gorman 	/* Wake up tasks throttled due to too_many_isolated. */
2304d818fca1SMel Gorman 	if (!too_many)
2305d818fca1SMel Gorman 		wake_throttle_isolated(pgdat);
2306d818fca1SMel Gorman 
2307d818fca1SMel Gorman 	return too_many;
230835cd7815SRik van Riel }
230935cd7815SRik van Riel 
2310a222f341SKirill Tkhai /*
231115b44736SHugh Dickins  * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
231215b44736SHugh Dickins  * On return, @list is reused as a list of pages to be freed by the caller.
2313a222f341SKirill Tkhai  *
2314a222f341SKirill Tkhai  * Returns the number of pages moved to the given lruvec.
2315a222f341SKirill Tkhai  */
23169ef56b78SMuchun Song static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2317a222f341SKirill Tkhai 				      struct list_head *list)
231866635629SMel Gorman {
2319a222f341SKirill Tkhai 	int nr_pages, nr_moved = 0;
23203f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
2321a222f341SKirill Tkhai 	struct page *page;
232266635629SMel Gorman 
2323a222f341SKirill Tkhai 	while (!list_empty(list)) {
2324a222f341SKirill Tkhai 		page = lru_to_page(list);
2325309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
2326a222f341SKirill Tkhai 		list_del(&page->lru);
23273d06afabSAlex Shi 		if (unlikely(!page_evictable(page))) {
23286168d0daSAlex Shi 			spin_unlock_irq(&lruvec->lru_lock);
232966635629SMel Gorman 			putback_lru_page(page);
23306168d0daSAlex Shi 			spin_lock_irq(&lruvec->lru_lock);
233166635629SMel Gorman 			continue;
233266635629SMel Gorman 		}
2333fa9add64SHugh Dickins 
23343d06afabSAlex Shi 		/*
23353d06afabSAlex Shi 		 * The SetPageLRU needs to be kept here for list integrity.
23363d06afabSAlex Shi 		 * Otherwise:
23373d06afabSAlex Shi 		 *   #0 move_pages_to_lru             #1 release_pages
23383d06afabSAlex Shi 		 *   if !put_page_testzero
23393d06afabSAlex Shi 		 *				      if (put_page_testzero())
23403d06afabSAlex Shi 		 *				        !PageLRU //skip lru_lock
23413d06afabSAlex Shi 		 *     SetPageLRU()
23423d06afabSAlex Shi 		 *     list_add(&page->lru,)
23433d06afabSAlex Shi 		 *                                        list_add(&page->lru,)
23443d06afabSAlex Shi 		 */
23457a608572SLinus Torvalds 		SetPageLRU(page);
2346a222f341SKirill Tkhai 
23473d06afabSAlex Shi 		if (unlikely(put_page_testzero(page))) {
234887560179SYu Zhao 			__clear_page_lru_flags(page);
23492bcf8879SHugh Dickins 
23502bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
23516168d0daSAlex Shi 				spin_unlock_irq(&lruvec->lru_lock);
2352ff45fc3cSMatthew Wilcox (Oracle) 				destroy_compound_page(page);
23536168d0daSAlex Shi 				spin_lock_irq(&lruvec->lru_lock);
23542bcf8879SHugh Dickins 			} else
23552bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
23563d06afabSAlex Shi 
23573d06afabSAlex Shi 			continue;
23583d06afabSAlex Shi 		}
23593d06afabSAlex Shi 
2360afca9157SAlex Shi 		/*
2361afca9157SAlex Shi 		 * All pages were isolated from the same lruvec (and isolation
2362afca9157SAlex Shi 		 * inhibits memcg migration).
2363afca9157SAlex Shi 		 */
23640de340cbSMatthew Wilcox (Oracle) 		VM_BUG_ON_PAGE(!folio_matches_lruvec(page_folio(page), lruvec), page);
23653a9c9788SYu Zhao 		add_page_to_lru_list(page, lruvec);
23663d06afabSAlex Shi 		nr_pages = thp_nr_pages(page);
2367a222f341SKirill Tkhai 		nr_moved += nr_pages;
236831d8fcacSJohannes Weiner 		if (PageActive(page))
236931d8fcacSJohannes Weiner 			workingset_age_nonresident(lruvec, nr_pages);
237066635629SMel Gorman 	}
237166635629SMel Gorman 
23723f79768fSHugh Dickins 	/*
23733f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
23743f79768fSHugh Dickins 	 */
2375a222f341SKirill Tkhai 	list_splice(&pages_to_free, list);
2376a222f341SKirill Tkhai 
2377a222f341SKirill Tkhai 	return nr_moved;
237866635629SMel Gorman }
237966635629SMel Gorman 
238066635629SMel Gorman /*
23815829f7dbSMiaohe Lin  * If a kernel thread (such as nfsd for loop-back mounts) services a backing
23825829f7dbSMiaohe Lin  * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case
23835829f7dbSMiaohe Lin  * we should not throttle.  Otherwise it is safe to do so.
2384399ba0b9SNeilBrown  */
2385399ba0b9SNeilBrown static int current_may_throttle(void)
2386399ba0b9SNeilBrown {
2387b9b1335eSNeilBrown 	return !(current->flags & PF_LOCAL_THROTTLE);
2388399ba0b9SNeilBrown }
2389399ba0b9SNeilBrown 
2390399ba0b9SNeilBrown /*
2391b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
23921742f19fSAndrew Morton  * of reclaimed pages
23931da177e4SLinus Torvalds  */
23949ef56b78SMuchun Song static unsigned long
23951a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
23969e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
23971da177e4SLinus Torvalds {
23981da177e4SLinus Torvalds 	LIST_HEAD(page_list);
2399e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
2400730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
2401e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
2402060f005fSKirill Tkhai 	struct reclaim_stat stat;
2403497a6c1bSJohannes Weiner 	bool file = is_file_lru(lru);
2404f46b7912SKirill Tkhai 	enum vm_event_item item;
2405599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2406db73ee0dSMichal Hocko 	bool stalled = false;
240778dc583dSKOSAKI Motohiro 
2408599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
2409db73ee0dSMichal Hocko 		if (stalled)
2410db73ee0dSMichal Hocko 			return 0;
2411db73ee0dSMichal Hocko 
2412db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
2413db73ee0dSMichal Hocko 		stalled = true;
2414c3f4a9a2SMel Gorman 		reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
241535cd7815SRik van Riel 
241635cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
241735cd7815SRik van Riel 		if (fatal_signal_pending(current))
241835cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
241935cd7815SRik van Riel 	}
242035cd7815SRik van Riel 
24211da177e4SLinus Torvalds 	lru_add_drain();
2422f80c0673SMinchan Kim 
24236168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
24241da177e4SLinus Torvalds 
24255dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
2426a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
242795d918fcSKonstantin Khlebnikov 
2428599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2429f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
2430b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
2431f46b7912SKirill Tkhai 		__count_vm_events(item, nr_scanned);
2432f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
2433497a6c1bSJohannes Weiner 	__count_vm_events(PGSCAN_ANON + file, nr_scanned);
2434497a6c1bSJohannes Weiner 
24356168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
2436d563c050SHillf Danton 
2437d563c050SHillf Danton 	if (nr_taken == 0)
243866635629SMel Gorman 		return 0;
2439b35ea17bSKOSAKI Motohiro 
2440013339dfSShakeel Butt 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
2441c661b078SAndy Whitcroft 
24426168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2443497a6c1bSJohannes Weiner 	move_pages_to_lru(lruvec, &page_list);
2444497a6c1bSJohannes Weiner 
2445497a6c1bSJohannes Weiner 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2446f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
2447b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
2448f46b7912SKirill Tkhai 		__count_vm_events(item, nr_reclaimed);
2449f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
2450497a6c1bSJohannes Weiner 	__count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
24516168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
24523f79768fSHugh Dickins 
245375cc3c91SAlex Shi 	lru_note_cost(lruvec, file, stat.nr_pageout);
2454747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
24552d4894b5SMel Gorman 	free_unref_page_list(&page_list);
2456e11da5b4SMel Gorman 
245792df3a72SMel Gorman 	/*
24581c610d5fSAndrey Ryabinin 	 * If dirty pages are scanned that are not queued for IO, it
24591c610d5fSAndrey Ryabinin 	 * implies that flushers are not doing their job. This can
24601c610d5fSAndrey Ryabinin 	 * happen when memory pressure pushes dirty pages to the end of
24611c610d5fSAndrey Ryabinin 	 * the LRU before the dirty limits are breached and the dirty
24621c610d5fSAndrey Ryabinin 	 * data has expired. It can also happen when the proportion of
24631c610d5fSAndrey Ryabinin 	 * dirty pages grows not through writes but through memory
24641c610d5fSAndrey Ryabinin 	 * pressure reclaiming all the clean cache. And in some cases,
24651c610d5fSAndrey Ryabinin 	 * the flushers simply cannot keep up with the allocation
24661c610d5fSAndrey Ryabinin 	 * rate. Nudge the flusher threads in case they are asleep.
24671c610d5fSAndrey Ryabinin 	 */
24681c610d5fSAndrey Ryabinin 	if (stat.nr_unqueued_dirty == nr_taken)
24691c610d5fSAndrey Ryabinin 		wakeup_flusher_threads(WB_REASON_VMSCAN);
24701c610d5fSAndrey Ryabinin 
2471d108c772SAndrey Ryabinin 	sc->nr.dirty += stat.nr_dirty;
2472d108c772SAndrey Ryabinin 	sc->nr.congested += stat.nr_congested;
2473d108c772SAndrey Ryabinin 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2474d108c772SAndrey Ryabinin 	sc->nr.writeback += stat.nr_writeback;
2475d108c772SAndrey Ryabinin 	sc->nr.immediate += stat.nr_immediate;
2476d108c772SAndrey Ryabinin 	sc->nr.taken += nr_taken;
2477d108c772SAndrey Ryabinin 	if (file)
2478d108c772SAndrey Ryabinin 		sc->nr.file_taken += nr_taken;
24798e950282SMel Gorman 
2480599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2481d51d1e64SSteven Rostedt 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
248205ff5137SAndrew Morton 	return nr_reclaimed;
24831da177e4SLinus Torvalds }
24841da177e4SLinus Torvalds 
248515b44736SHugh Dickins /*
248615b44736SHugh Dickins  * shrink_active_list() moves pages from the active LRU to the inactive LRU.
248715b44736SHugh Dickins  *
248815b44736SHugh Dickins  * We move them the other way if the page is referenced by one or more
248915b44736SHugh Dickins  * processes.
249015b44736SHugh Dickins  *
249115b44736SHugh Dickins  * If the pages are mostly unmapped, the processing is fast and it is
249215b44736SHugh Dickins  * appropriate to hold lru_lock across the whole operation.  But if
2493b3ac0413SMatthew Wilcox (Oracle)  * the pages are mapped, the processing is slow (folio_referenced()), so
249415b44736SHugh Dickins  * we should drop lru_lock around each page.  It's impossible to balance
249515b44736SHugh Dickins  * this, so instead we remove the pages from the LRU while processing them.
249615b44736SHugh Dickins  * It is safe to rely on PG_active against the non-LRU pages in here because
249715b44736SHugh Dickins  * nobody will play with that bit on a non-LRU page.
249815b44736SHugh Dickins  *
249915b44736SHugh Dickins  * The downside is that we have to touch page->_refcount against each page.
250015b44736SHugh Dickins  * But we had to alter page->flags anyway.
250115b44736SHugh Dickins  */
2502f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
25031a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
2504f16015fbSJohannes Weiner 			       struct scan_control *sc,
25059e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
25061cfb419bSKAMEZAWA Hiroyuki {
250744c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
2508f626012dSHugh Dickins 	unsigned long nr_scanned;
25096fe6b7e3SWu Fengguang 	unsigned long vm_flags;
25101cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
25118cab4754SWu Fengguang 	LIST_HEAD(l_active);
2512b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
25139d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
25149d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
25153cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
2516599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
25171cfb419bSKAMEZAWA Hiroyuki 
25181da177e4SLinus Torvalds 	lru_add_drain();
2519f80c0673SMinchan Kim 
25206168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2521925b7673SJohannes Weiner 
25225dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2523a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
252489b5fae5SJohannes Weiner 
2525599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
25261cfb419bSKAMEZAWA Hiroyuki 
2527912c0572SShakeel Butt 	if (!cgroup_reclaim(sc))
2528599d0c95SMel Gorman 		__count_vm_events(PGREFILL, nr_scanned);
25292fa2690cSYafang Shao 	__count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
25309d5e6a9fSHugh Dickins 
25316168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
25321da177e4SLinus Torvalds 
25331da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
2534b3ac0413SMatthew Wilcox (Oracle) 		struct folio *folio;
2535b3ac0413SMatthew Wilcox (Oracle) 		struct page *page;
2536b3ac0413SMatthew Wilcox (Oracle) 
25371da177e4SLinus Torvalds 		cond_resched();
2538b3ac0413SMatthew Wilcox (Oracle) 		folio = lru_to_folio(&l_hold);
2539b3ac0413SMatthew Wilcox (Oracle) 		list_del(&folio->lru);
2540b3ac0413SMatthew Wilcox (Oracle) 		page = &folio->page;
25417e9cd484SRik van Riel 
254239b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
2543894bc310SLee Schermerhorn 			putback_lru_page(page);
2544894bc310SLee Schermerhorn 			continue;
2545894bc310SLee Schermerhorn 		}
2546894bc310SLee Schermerhorn 
2547cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
2548cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
2549cc715d99SMel Gorman 				if (page_has_private(page))
2550cc715d99SMel Gorman 					try_to_release_page(page, 0);
2551cc715d99SMel Gorman 				unlock_page(page);
2552cc715d99SMel Gorman 			}
2553cc715d99SMel Gorman 		}
2554cc715d99SMel Gorman 
25556d4675e6SMinchan Kim 		/* Referenced or rmap lock contention: rotate */
2556b3ac0413SMatthew Wilcox (Oracle) 		if (folio_referenced(folio, 0, sc->target_mem_cgroup,
25576d4675e6SMinchan Kim 				     &vm_flags) != 0) {
25588cab4754SWu Fengguang 			/*
25598cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
25608cab4754SWu Fengguang 			 * give them one more trip around the active list. So
25618cab4754SWu Fengguang 			 * that executable code get better chances to stay in
25628cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
25638cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
25648cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
25658cab4754SWu Fengguang 			 * so we ignore them here.
25668cab4754SWu Fengguang 			 */
25679de4f22aSHuang Ying 			if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
25686c357848SMatthew Wilcox (Oracle) 				nr_rotated += thp_nr_pages(page);
25698cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
25708cab4754SWu Fengguang 				continue;
25718cab4754SWu Fengguang 			}
25728cab4754SWu Fengguang 		}
25737e9cd484SRik van Riel 
25745205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
25751899ad18SJohannes Weiner 		SetPageWorkingset(page);
25761da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
25771da177e4SLinus Torvalds 	}
25781da177e4SLinus Torvalds 
2579b555749aSAndrew Morton 	/*
25808cab4754SWu Fengguang 	 * Move pages back to the lru list.
2581b555749aSAndrew Morton 	 */
25826168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2583556adecbSRik van Riel 
2584a222f341SKirill Tkhai 	nr_activate = move_pages_to_lru(lruvec, &l_active);
2585a222f341SKirill Tkhai 	nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2586f372d89eSKirill Tkhai 	/* Keep all free pages in l_active list */
2587f372d89eSKirill Tkhai 	list_splice(&l_inactive, &l_active);
25889851ac13SKirill Tkhai 
25899851ac13SKirill Tkhai 	__count_vm_events(PGDEACTIVATE, nr_deactivate);
25909851ac13SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
25919851ac13SKirill Tkhai 
2592599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
25936168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
25942bcf8879SHugh Dickins 
2595f372d89eSKirill Tkhai 	mem_cgroup_uncharge_list(&l_active);
2596f372d89eSKirill Tkhai 	free_unref_page_list(&l_active);
25979d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
25989d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
25991da177e4SLinus Torvalds }
26001da177e4SLinus Torvalds 
26011fe47c0bSMiaohe Lin static unsigned int reclaim_page_list(struct list_head *page_list,
26021fe47c0bSMiaohe Lin 				      struct pglist_data *pgdat)
26031a4e58ccSMinchan Kim {
26041a4e58ccSMinchan Kim 	struct reclaim_stat dummy_stat;
26051fe47c0bSMiaohe Lin 	unsigned int nr_reclaimed;
26061fe47c0bSMiaohe Lin 	struct folio *folio;
26071a4e58ccSMinchan Kim 	struct scan_control sc = {
26081a4e58ccSMinchan Kim 		.gfp_mask = GFP_KERNEL,
26091a4e58ccSMinchan Kim 		.may_writepage = 1,
26101a4e58ccSMinchan Kim 		.may_unmap = 1,
26111a4e58ccSMinchan Kim 		.may_swap = 1,
261226aa2d19SDave Hansen 		.no_demotion = 1,
26131a4e58ccSMinchan Kim 	};
26141a4e58ccSMinchan Kim 
26151fe47c0bSMiaohe Lin 	nr_reclaimed = shrink_page_list(page_list, pgdat, &sc, &dummy_stat, false);
26161fe47c0bSMiaohe Lin 	while (!list_empty(page_list)) {
26171fe47c0bSMiaohe Lin 		folio = lru_to_folio(page_list);
26181fe47c0bSMiaohe Lin 		list_del(&folio->lru);
26191fe47c0bSMiaohe Lin 		folio_putback_lru(folio);
26201fe47c0bSMiaohe Lin 	}
26211fe47c0bSMiaohe Lin 
26221fe47c0bSMiaohe Lin 	return nr_reclaimed;
26231fe47c0bSMiaohe Lin }
26241fe47c0bSMiaohe Lin 
26251fe47c0bSMiaohe Lin unsigned long reclaim_pages(struct list_head *page_list)
26261fe47c0bSMiaohe Lin {
2627ed657e55SWei Yang 	int nid;
26281fe47c0bSMiaohe Lin 	unsigned int nr_reclaimed = 0;
26291fe47c0bSMiaohe Lin 	LIST_HEAD(node_page_list);
26301fe47c0bSMiaohe Lin 	struct page *page;
26311fe47c0bSMiaohe Lin 	unsigned int noreclaim_flag;
26321fe47c0bSMiaohe Lin 
26331ae65e27SWei Yang 	if (list_empty(page_list))
26341ae65e27SWei Yang 		return nr_reclaimed;
26351ae65e27SWei Yang 
26362d2b8d2bSYu Zhao 	noreclaim_flag = memalloc_noreclaim_save();
26372d2b8d2bSYu Zhao 
2638ed657e55SWei Yang 	nid = page_to_nid(lru_to_page(page_list));
26391ae65e27SWei Yang 	do {
26401a4e58ccSMinchan Kim 		page = lru_to_page(page_list);
26411a4e58ccSMinchan Kim 
26421a4e58ccSMinchan Kim 		if (nid == page_to_nid(page)) {
26431a4e58ccSMinchan Kim 			ClearPageActive(page);
26441a4e58ccSMinchan Kim 			list_move(&page->lru, &node_page_list);
26451a4e58ccSMinchan Kim 			continue;
26461a4e58ccSMinchan Kim 		}
26471a4e58ccSMinchan Kim 
26481fe47c0bSMiaohe Lin 		nr_reclaimed += reclaim_page_list(&node_page_list, NODE_DATA(nid));
2649ed657e55SWei Yang 		nid = page_to_nid(lru_to_page(page_list));
26501ae65e27SWei Yang 	} while (!list_empty(page_list));
26511a4e58ccSMinchan Kim 
26521fe47c0bSMiaohe Lin 	nr_reclaimed += reclaim_page_list(&node_page_list, NODE_DATA(nid));
26531a4e58ccSMinchan Kim 
26542d2b8d2bSYu Zhao 	memalloc_noreclaim_restore(noreclaim_flag);
26552d2b8d2bSYu Zhao 
26561a4e58ccSMinchan Kim 	return nr_reclaimed;
26571a4e58ccSMinchan Kim }
26581a4e58ccSMinchan Kim 
2659b91ac374SJohannes Weiner static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2660b91ac374SJohannes Weiner 				 struct lruvec *lruvec, struct scan_control *sc)
2661b91ac374SJohannes Weiner {
2662b91ac374SJohannes Weiner 	if (is_active_lru(lru)) {
2663b91ac374SJohannes Weiner 		if (sc->may_deactivate & (1 << is_file_lru(lru)))
2664b91ac374SJohannes Weiner 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2665b91ac374SJohannes Weiner 		else
2666b91ac374SJohannes Weiner 			sc->skipped_deactivate = 1;
2667b91ac374SJohannes Weiner 		return 0;
2668b91ac374SJohannes Weiner 	}
2669b91ac374SJohannes Weiner 
2670b91ac374SJohannes Weiner 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2671b91ac374SJohannes Weiner }
2672b91ac374SJohannes Weiner 
267359dc76b0SRik van Riel /*
267459dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
267559dc76b0SRik van Riel  * to do too much work.
267614797e23SKOSAKI Motohiro  *
267759dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
267859dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
267959dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
268059dc76b0SRik van Riel  *
268159dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
268259dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
268359dc76b0SRik van Riel  *
26842a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
26852a2e4885SJohannes Weiner  *
268659dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
26873a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
268859dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
268959dc76b0SRik van Riel  *
269059dc76b0SRik van Riel  * total     target    max
269159dc76b0SRik van Riel  * memory    ratio     inactive
269259dc76b0SRik van Riel  * -------------------------------------
269359dc76b0SRik van Riel  *   10MB       1         5MB
269459dc76b0SRik van Riel  *  100MB       1        50MB
269559dc76b0SRik van Riel  *    1GB       3       250MB
269659dc76b0SRik van Riel  *   10GB      10       0.9GB
269759dc76b0SRik van Riel  *  100GB      31         3GB
269859dc76b0SRik van Riel  *    1TB     101        10GB
269959dc76b0SRik van Riel  *   10TB     320        32GB
270014797e23SKOSAKI Motohiro  */
2701b91ac374SJohannes Weiner static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
270214797e23SKOSAKI Motohiro {
2703b91ac374SJohannes Weiner 	enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
27042a2e4885SJohannes Weiner 	unsigned long inactive, active;
27052a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
270659dc76b0SRik van Riel 	unsigned long gb;
270759dc76b0SRik van Riel 
2708b91ac374SJohannes Weiner 	inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2709b91ac374SJohannes Weiner 	active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2710f8d1a311SMel Gorman 
271159dc76b0SRik van Riel 	gb = (inactive + active) >> (30 - PAGE_SHIFT);
27124002570cSJoonsoo Kim 	if (gb)
271359dc76b0SRik van Riel 		inactive_ratio = int_sqrt(10 * gb);
2714b39415b2SRik van Riel 	else
271559dc76b0SRik van Riel 		inactive_ratio = 1;
2716fd538803SMichal Hocko 
271759dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2718b39415b2SRik van Riel }
2719b39415b2SRik van Riel 
27209a265114SJohannes Weiner enum scan_balance {
27219a265114SJohannes Weiner 	SCAN_EQUAL,
27229a265114SJohannes Weiner 	SCAN_FRACT,
27239a265114SJohannes Weiner 	SCAN_ANON,
27249a265114SJohannes Weiner 	SCAN_FILE,
27259a265114SJohannes Weiner };
27269a265114SJohannes Weiner 
27271da177e4SLinus Torvalds /*
27284f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
272902e458d8SMiaohe Lin  * scanned.
27304f98a2feSRik van Riel  *
2731be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2732be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
27334f98a2feSRik van Riel  */
2734afaf07a6SJohannes Weiner static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2735afaf07a6SJohannes Weiner 			   unsigned long *nr)
27364f98a2feSRik van Riel {
2737a2a36488SKeith Busch 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2738afaf07a6SJohannes Weiner 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2739d483a5ddSJohannes Weiner 	unsigned long anon_cost, file_cost, total_cost;
274033377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
2741ed017373SYu Zhao 	u64 fraction[ANON_AND_FILE];
27429a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
27439a265114SJohannes Weiner 	enum scan_balance scan_balance;
27449a265114SJohannes Weiner 	unsigned long ap, fp;
27459a265114SJohannes Weiner 	enum lru_list lru;
274676a33fc3SShaohua Li 
274776a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2748a2a36488SKeith Busch 	if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
27499a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
275076a33fc3SShaohua Li 		goto out;
275176a33fc3SShaohua Li 	}
27524f98a2feSRik van Riel 
275310316b31SJohannes Weiner 	/*
275410316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
275510316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
275610316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
275710316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
275810316b31SJohannes Weiner 	 * too expensive.
275910316b31SJohannes Weiner 	 */
2760b5ead35eSJohannes Weiner 	if (cgroup_reclaim(sc) && !swappiness) {
27619a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
276210316b31SJohannes Weiner 		goto out;
276310316b31SJohannes Weiner 	}
276410316b31SJohannes Weiner 
276510316b31SJohannes Weiner 	/*
276610316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
276710316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
276810316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
276910316b31SJohannes Weiner 	 */
277002695175SJohannes Weiner 	if (!sc->priority && swappiness) {
27719a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
277210316b31SJohannes Weiner 		goto out;
277310316b31SJohannes Weiner 	}
277410316b31SJohannes Weiner 
277511d16c25SJohannes Weiner 	/*
277653138ceaSJohannes Weiner 	 * If the system is almost out of file pages, force-scan anon.
277762376251SJohannes Weiner 	 */
2778b91ac374SJohannes Weiner 	if (sc->file_is_tiny) {
277962376251SJohannes Weiner 		scan_balance = SCAN_ANON;
278062376251SJohannes Weiner 		goto out;
278162376251SJohannes Weiner 	}
278262376251SJohannes Weiner 
278362376251SJohannes Weiner 	/*
2784b91ac374SJohannes Weiner 	 * If there is enough inactive page cache, we do not reclaim
2785b91ac374SJohannes Weiner 	 * anything from the anonymous working right now.
2786e9868505SRik van Riel 	 */
2787b91ac374SJohannes Weiner 	if (sc->cache_trim_mode) {
27889a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2789e9868505SRik van Riel 		goto out;
27904f98a2feSRik van Riel 	}
27914f98a2feSRik van Riel 
27929a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
27934f98a2feSRik van Riel 	/*
2794314b57fbSJohannes Weiner 	 * Calculate the pressure balance between anon and file pages.
2795314b57fbSJohannes Weiner 	 *
2796314b57fbSJohannes Weiner 	 * The amount of pressure we put on each LRU is inversely
2797314b57fbSJohannes Weiner 	 * proportional to the cost of reclaiming each list, as
2798314b57fbSJohannes Weiner 	 * determined by the share of pages that are refaulting, times
2799314b57fbSJohannes Weiner 	 * the relative IO cost of bringing back a swapped out
2800314b57fbSJohannes Weiner 	 * anonymous page vs reloading a filesystem page (swappiness).
2801314b57fbSJohannes Weiner 	 *
2802d483a5ddSJohannes Weiner 	 * Although we limit that influence to ensure no list gets
2803d483a5ddSJohannes Weiner 	 * left behind completely: at least a third of the pressure is
2804d483a5ddSJohannes Weiner 	 * applied, before swappiness.
2805d483a5ddSJohannes Weiner 	 *
2806314b57fbSJohannes Weiner 	 * With swappiness at 100, anon and file have equal IO cost.
280758c37f6eSKOSAKI Motohiro 	 */
2808d483a5ddSJohannes Weiner 	total_cost = sc->anon_cost + sc->file_cost;
2809d483a5ddSJohannes Weiner 	anon_cost = total_cost + sc->anon_cost;
2810d483a5ddSJohannes Weiner 	file_cost = total_cost + sc->file_cost;
2811d483a5ddSJohannes Weiner 	total_cost = anon_cost + file_cost;
281258c37f6eSKOSAKI Motohiro 
2813d483a5ddSJohannes Weiner 	ap = swappiness * (total_cost + 1);
2814d483a5ddSJohannes Weiner 	ap /= anon_cost + 1;
28154f98a2feSRik van Riel 
2816d483a5ddSJohannes Weiner 	fp = (200 - swappiness) * (total_cost + 1);
2817d483a5ddSJohannes Weiner 	fp /= file_cost + 1;
28184f98a2feSRik van Riel 
281976a33fc3SShaohua Li 	fraction[0] = ap;
282076a33fc3SShaohua Li 	fraction[1] = fp;
2821a4fe1631SJohannes Weiner 	denominator = ap + fp;
282276a33fc3SShaohua Li out:
28234111304dSHugh Dickins 	for_each_evictable_lru(lru) {
28244111304dSHugh Dickins 		int file = is_file_lru(lru);
28259783aa99SChris Down 		unsigned long lruvec_size;
2826f56ce412SJohannes Weiner 		unsigned long low, min;
282776a33fc3SShaohua Li 		unsigned long scan;
282876a33fc3SShaohua Li 
28299783aa99SChris Down 		lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2830f56ce412SJohannes Weiner 		mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2831f56ce412SJohannes Weiner 				      &min, &low);
28329783aa99SChris Down 
2833f56ce412SJohannes Weiner 		if (min || low) {
28349783aa99SChris Down 			/*
28359783aa99SChris Down 			 * Scale a cgroup's reclaim pressure by proportioning
28369783aa99SChris Down 			 * its current usage to its memory.low or memory.min
28379783aa99SChris Down 			 * setting.
28389783aa99SChris Down 			 *
28399783aa99SChris Down 			 * This is important, as otherwise scanning aggression
28409783aa99SChris Down 			 * becomes extremely binary -- from nothing as we
28419783aa99SChris Down 			 * approach the memory protection threshold, to totally
28429783aa99SChris Down 			 * nominal as we exceed it.  This results in requiring
28439783aa99SChris Down 			 * setting extremely liberal protection thresholds. It
28449783aa99SChris Down 			 * also means we simply get no protection at all if we
28459783aa99SChris Down 			 * set it too low, which is not ideal.
28461bc63fb1SChris Down 			 *
28471bc63fb1SChris Down 			 * If there is any protection in place, we reduce scan
28481bc63fb1SChris Down 			 * pressure by how much of the total memory used is
28491bc63fb1SChris Down 			 * within protection thresholds.
28509783aa99SChris Down 			 *
28519de7ca46SChris Down 			 * There is one special case: in the first reclaim pass,
28529de7ca46SChris Down 			 * we skip over all groups that are within their low
28539de7ca46SChris Down 			 * protection. If that fails to reclaim enough pages to
28549de7ca46SChris Down 			 * satisfy the reclaim goal, we come back and override
28559de7ca46SChris Down 			 * the best-effort low protection. However, we still
28569de7ca46SChris Down 			 * ideally want to honor how well-behaved groups are in
28579de7ca46SChris Down 			 * that case instead of simply punishing them all
28589de7ca46SChris Down 			 * equally. As such, we reclaim them based on how much
28591bc63fb1SChris Down 			 * memory they are using, reducing the scan pressure
28601bc63fb1SChris Down 			 * again by how much of the total memory used is under
28611bc63fb1SChris Down 			 * hard protection.
28629783aa99SChris Down 			 */
28631bc63fb1SChris Down 			unsigned long cgroup_size = mem_cgroup_size(memcg);
2864f56ce412SJohannes Weiner 			unsigned long protection;
2865f56ce412SJohannes Weiner 
2866f56ce412SJohannes Weiner 			/* memory.low scaling, make sure we retry before OOM */
2867f56ce412SJohannes Weiner 			if (!sc->memcg_low_reclaim && low > min) {
2868f56ce412SJohannes Weiner 				protection = low;
2869f56ce412SJohannes Weiner 				sc->memcg_low_skipped = 1;
2870f56ce412SJohannes Weiner 			} else {
2871f56ce412SJohannes Weiner 				protection = min;
2872f56ce412SJohannes Weiner 			}
28731bc63fb1SChris Down 
28741bc63fb1SChris Down 			/* Avoid TOCTOU with earlier protection check */
28751bc63fb1SChris Down 			cgroup_size = max(cgroup_size, protection);
28761bc63fb1SChris Down 
28771bc63fb1SChris Down 			scan = lruvec_size - lruvec_size * protection /
287832d4f4b7SRik van Riel 				(cgroup_size + 1);
28799783aa99SChris Down 
28809783aa99SChris Down 			/*
28811bc63fb1SChris Down 			 * Minimally target SWAP_CLUSTER_MAX pages to keep
288255b65a57SEthon Paul 			 * reclaim moving forwards, avoiding decrementing
28839de7ca46SChris Down 			 * sc->priority further than desirable.
28849783aa99SChris Down 			 */
28851bc63fb1SChris Down 			scan = max(scan, SWAP_CLUSTER_MAX);
28869783aa99SChris Down 		} else {
28879783aa99SChris Down 			scan = lruvec_size;
28889783aa99SChris Down 		}
28899783aa99SChris Down 
28909783aa99SChris Down 		scan >>= sc->priority;
28919783aa99SChris Down 
2892688035f7SJohannes Weiner 		/*
2893688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2894688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2895688035f7SJohannes Weiner 		 */
2896688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
28979783aa99SChris Down 			scan = min(lruvec_size, SWAP_CLUSTER_MAX);
28989a265114SJohannes Weiner 
28999a265114SJohannes Weiner 		switch (scan_balance) {
29009a265114SJohannes Weiner 		case SCAN_EQUAL:
29019a265114SJohannes Weiner 			/* Scan lists relative to size */
29029a265114SJohannes Weiner 			break;
29039a265114SJohannes Weiner 		case SCAN_FRACT:
29049a265114SJohannes Weiner 			/*
29059a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
29069a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
290776073c64SGavin Shan 			 * Make sure we don't miss the last page on
290876073c64SGavin Shan 			 * the offlined memory cgroups because of a
290976073c64SGavin Shan 			 * round-off error.
29109a265114SJohannes Weiner 			 */
291176073c64SGavin Shan 			scan = mem_cgroup_online(memcg) ?
291276073c64SGavin Shan 			       div64_u64(scan * fraction[file], denominator) :
291376073c64SGavin Shan 			       DIV64_U64_ROUND_UP(scan * fraction[file],
29146f04f48dSSuleiman Souhlal 						  denominator);
29159a265114SJohannes Weiner 			break;
29169a265114SJohannes Weiner 		case SCAN_FILE:
29179a265114SJohannes Weiner 		case SCAN_ANON:
29189a265114SJohannes Weiner 			/* Scan one type exclusively */
2919e072bff6SMateusz Nosek 			if ((scan_balance == SCAN_FILE) != file)
29209a265114SJohannes Weiner 				scan = 0;
29219a265114SJohannes Weiner 			break;
29229a265114SJohannes Weiner 		default:
29239a265114SJohannes Weiner 			/* Look ma, no brain */
29249a265114SJohannes Weiner 			BUG();
29259a265114SJohannes Weiner 		}
29266b4f7799SJohannes Weiner 
29274111304dSHugh Dickins 		nr[lru] = scan;
292876a33fc3SShaohua Li 	}
29296e08a369SWu Fengguang }
29304f98a2feSRik van Riel 
29312f368a9fSDave Hansen /*
29322f368a9fSDave Hansen  * Anonymous LRU management is a waste if there is
29332f368a9fSDave Hansen  * ultimately no way to reclaim the memory.
29342f368a9fSDave Hansen  */
29352f368a9fSDave Hansen static bool can_age_anon_pages(struct pglist_data *pgdat,
29362f368a9fSDave Hansen 			       struct scan_control *sc)
29372f368a9fSDave Hansen {
29382f368a9fSDave Hansen 	/* Aging the anon LRU is valuable if swap is present: */
29392f368a9fSDave Hansen 	if (total_swap_pages > 0)
29402f368a9fSDave Hansen 		return true;
29412f368a9fSDave Hansen 
29422f368a9fSDave Hansen 	/* Also valuable if anon pages can be demoted: */
29432f368a9fSDave Hansen 	return can_demote(pgdat->node_id, sc);
29442f368a9fSDave Hansen }
29452f368a9fSDave Hansen 
2946afaf07a6SJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
29479b4f98cdSJohannes Weiner {
29489b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2949e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
29509b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
29519b4f98cdSJohannes Weiner 	enum lru_list lru;
29529b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
29539b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
29549b4f98cdSJohannes Weiner 	struct blk_plug plug;
29551a501907SMel Gorman 	bool scan_adjusted;
29569b4f98cdSJohannes Weiner 
2957afaf07a6SJohannes Weiner 	get_scan_count(lruvec, sc, nr);
29589b4f98cdSJohannes Weiner 
2959e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2960e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2961e82e0561SMel Gorman 
29621a501907SMel Gorman 	/*
29631a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
29641a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
29651a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
29661a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
29671a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
29681a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
29691a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
29701a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
29711a501907SMel Gorman 	 * dropped to zero at the first pass.
29721a501907SMel Gorman 	 */
2973b5ead35eSJohannes Weiner 	scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
29741a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
29751a501907SMel Gorman 
29769b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
29779b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
29789b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2979e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2980e82e0561SMel Gorman 		unsigned long nr_scanned;
2981e82e0561SMel Gorman 
29829b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
29839b4f98cdSJohannes Weiner 			if (nr[lru]) {
29849b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
29859b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
29869b4f98cdSJohannes Weiner 
29879b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
29883b991208SJohannes Weiner 							    lruvec, sc);
29899b4f98cdSJohannes Weiner 			}
29909b4f98cdSJohannes Weiner 		}
2991e82e0561SMel Gorman 
2992bd041733SMichal Hocko 		cond_resched();
2993bd041733SMichal Hocko 
2994e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2995e82e0561SMel Gorman 			continue;
2996e82e0561SMel Gorman 
29979b4f98cdSJohannes Weiner 		/*
2998e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
29991a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
3000e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
3001e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
3002e82e0561SMel Gorman 		 * proportional to the original scan target.
3003e82e0561SMel Gorman 		 */
3004e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
3005e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
3006e82e0561SMel Gorman 
30071a501907SMel Gorman 		/*
30081a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
30091a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
30101a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
30111a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
30121a501907SMel Gorman 		 */
30131a501907SMel Gorman 		if (!nr_file || !nr_anon)
30141a501907SMel Gorman 			break;
30151a501907SMel Gorman 
3016e82e0561SMel Gorman 		if (nr_file > nr_anon) {
3017e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
3018e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
3019e82e0561SMel Gorman 			lru = LRU_BASE;
3020e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
3021e82e0561SMel Gorman 		} else {
3022e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
3023e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
3024e82e0561SMel Gorman 			lru = LRU_FILE;
3025e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
3026e82e0561SMel Gorman 		}
3027e82e0561SMel Gorman 
3028e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
3029e82e0561SMel Gorman 		nr[lru] = 0;
3030e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
3031e82e0561SMel Gorman 
3032e82e0561SMel Gorman 		/*
3033e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
3034e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
3035e82e0561SMel Gorman 		 */
3036e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
3037e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
3038e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
3039e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
3040e82e0561SMel Gorman 
3041e82e0561SMel Gorman 		lru += LRU_ACTIVE;
3042e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
3043e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
3044e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
3045e82e0561SMel Gorman 
3046e82e0561SMel Gorman 		scan_adjusted = true;
30479b4f98cdSJohannes Weiner 	}
30489b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
30499b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
30509b4f98cdSJohannes Weiner 
30519b4f98cdSJohannes Weiner 	/*
30529b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
30539b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
30549b4f98cdSJohannes Weiner 	 */
30552f368a9fSDave Hansen 	if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
30562f368a9fSDave Hansen 	    inactive_is_low(lruvec, LRU_INACTIVE_ANON))
30579b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
30589b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
30599b4f98cdSJohannes Weiner }
30609b4f98cdSJohannes Weiner 
306123b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
30629e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
306323b9da55SMel Gorman {
3064d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
306523b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
30669e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
306723b9da55SMel Gorman 		return true;
306823b9da55SMel Gorman 
306923b9da55SMel Gorman 	return false;
307023b9da55SMel Gorman }
307123b9da55SMel Gorman 
30724f98a2feSRik van Riel /*
307323b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
307423b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
307523b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
3076df3a45f9SQiwu Chen  * calls try_to_compact_pages() that it will have enough free pages to succeed.
307723b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
30783e7d3449SMel Gorman  */
3079a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
30803e7d3449SMel Gorman 					unsigned long nr_reclaimed,
30813e7d3449SMel Gorman 					struct scan_control *sc)
30823e7d3449SMel Gorman {
30833e7d3449SMel Gorman 	unsigned long pages_for_compaction;
30843e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
3085a9dd0a83SMel Gorman 	int z;
30863e7d3449SMel Gorman 
30873e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
30889e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
30893e7d3449SMel Gorman 		return false;
30903e7d3449SMel Gorman 
30913e7d3449SMel Gorman 	/*
30925ee04716SVlastimil Babka 	 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
30935ee04716SVlastimil Babka 	 * number of pages that were scanned. This will return to the caller
30945ee04716SVlastimil Babka 	 * with the risk reclaim/compaction and the resulting allocation attempt
30955ee04716SVlastimil Babka 	 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
30965ee04716SVlastimil Babka 	 * allocations through requiring that the full LRU list has been scanned
30975ee04716SVlastimil Babka 	 * first, by assuming that zero delta of sc->nr_scanned means full LRU
30985ee04716SVlastimil Babka 	 * scan, but that approximation was wrong, and there were corner cases
30995ee04716SVlastimil Babka 	 * where always a non-zero amount of pages were scanned.
31002876592fSMel Gorman 	 */
31012876592fSMel Gorman 	if (!nr_reclaimed)
31022876592fSMel Gorman 		return false;
31033e7d3449SMel Gorman 
31043e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
3105a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
3106a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
31076aa303deSMel Gorman 		if (!managed_zone(zone))
3108a9dd0a83SMel Gorman 			continue;
3109a9dd0a83SMel Gorman 
3110a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
3111cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
31123e7d3449SMel Gorman 		case COMPACT_CONTINUE:
31133e7d3449SMel Gorman 			return false;
31143e7d3449SMel Gorman 		default:
3115a9dd0a83SMel Gorman 			/* check next zone */
3116a9dd0a83SMel Gorman 			;
31173e7d3449SMel Gorman 		}
31183e7d3449SMel Gorman 	}
31191c6c1597SHillf Danton 
31201c6c1597SHillf Danton 	/*
31211c6c1597SHillf Danton 	 * If we have not reclaimed enough pages for compaction and the
31221c6c1597SHillf Danton 	 * inactive lists are large enough, continue reclaiming
31231c6c1597SHillf Danton 	 */
31241c6c1597SHillf Danton 	pages_for_compaction = compact_gap(sc->order);
31251c6c1597SHillf Danton 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
3126a2a36488SKeith Busch 	if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
31271c6c1597SHillf Danton 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
31281c6c1597SHillf Danton 
31295ee04716SVlastimil Babka 	return inactive_lru_pages > pages_for_compaction;
3130a9dd0a83SMel Gorman }
31313e7d3449SMel Gorman 
31320f6a5cffSJohannes Weiner static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
3133f16015fbSJohannes Weiner {
31340f6a5cffSJohannes Weiner 	struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
3135694fbc0fSAndrew Morton 	struct mem_cgroup *memcg;
3136d108c772SAndrey Ryabinin 
31370f6a5cffSJohannes Weiner 	memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
3138694fbc0fSAndrew Morton 	do {
3139afaf07a6SJohannes Weiner 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
31408e8ae645SJohannes Weiner 		unsigned long reclaimed;
3141cb731d6cSVladimir Davydov 		unsigned long scanned;
31429b4f98cdSJohannes Weiner 
3143e3336cabSXunlei Pang 		/*
3144e3336cabSXunlei Pang 		 * This loop can become CPU-bound when target memcgs
3145e3336cabSXunlei Pang 		 * aren't eligible for reclaim - either because they
3146e3336cabSXunlei Pang 		 * don't have any reclaimable pages, or because their
3147e3336cabSXunlei Pang 		 * memory is explicitly protected. Avoid soft lockups.
3148e3336cabSXunlei Pang 		 */
3149e3336cabSXunlei Pang 		cond_resched();
3150e3336cabSXunlei Pang 
315145c7f7e1SChris Down 		mem_cgroup_calculate_protection(target_memcg, memcg);
315245c7f7e1SChris Down 
315345c7f7e1SChris Down 		if (mem_cgroup_below_min(memcg)) {
3154bf8d5d52SRoman Gushchin 			/*
3155bf8d5d52SRoman Gushchin 			 * Hard protection.
3156bf8d5d52SRoman Gushchin 			 * If there is no reclaimable memory, OOM.
3157bf8d5d52SRoman Gushchin 			 */
3158bf8d5d52SRoman Gushchin 			continue;
315945c7f7e1SChris Down 		} else if (mem_cgroup_below_low(memcg)) {
3160bf8d5d52SRoman Gushchin 			/*
3161bf8d5d52SRoman Gushchin 			 * Soft protection.
3162bf8d5d52SRoman Gushchin 			 * Respect the protection only as long as
3163bf8d5d52SRoman Gushchin 			 * there is an unprotected supply
3164bf8d5d52SRoman Gushchin 			 * of reclaimable memory from other cgroups.
3165bf8d5d52SRoman Gushchin 			 */
3166d6622f63SYisheng Xie 			if (!sc->memcg_low_reclaim) {
3167d6622f63SYisheng Xie 				sc->memcg_low_skipped = 1;
3168241994edSJohannes Weiner 				continue;
3169d6622f63SYisheng Xie 			}
3170e27be240SJohannes Weiner 			memcg_memory_event(memcg, MEMCG_LOW);
3171241994edSJohannes Weiner 		}
3172241994edSJohannes Weiner 
31738e8ae645SJohannes Weiner 		reclaimed = sc->nr_reclaimed;
3174cb731d6cSVladimir Davydov 		scanned = sc->nr_scanned;
3175afaf07a6SJohannes Weiner 
3176afaf07a6SJohannes Weiner 		shrink_lruvec(lruvec, sc);
3177f9be23d6SKonstantin Khlebnikov 
317828360f39SMel Gorman 		shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
317928360f39SMel Gorman 			    sc->priority);
3180cb731d6cSVladimir Davydov 
31818e8ae645SJohannes Weiner 		/* Record the group's reclaim efficiency */
31828e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, memcg, false,
31838e8ae645SJohannes Weiner 			   sc->nr_scanned - scanned,
31848e8ae645SJohannes Weiner 			   sc->nr_reclaimed - reclaimed);
31858e8ae645SJohannes Weiner 
31860f6a5cffSJohannes Weiner 	} while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
31870f6a5cffSJohannes Weiner }
31880f6a5cffSJohannes Weiner 
31896c9e0907SLiu Song static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
31900f6a5cffSJohannes Weiner {
31910f6a5cffSJohannes Weiner 	struct reclaim_state *reclaim_state = current->reclaim_state;
31920f6a5cffSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
31931b05117dSJohannes Weiner 	struct lruvec *target_lruvec;
31940f6a5cffSJohannes Weiner 	bool reclaimable = false;
3195b91ac374SJohannes Weiner 	unsigned long file;
31960f6a5cffSJohannes Weiner 
31971b05117dSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
31981b05117dSJohannes Weiner 
31990f6a5cffSJohannes Weiner again:
3200aa48e47eSShakeel Butt 	/*
3201aa48e47eSShakeel Butt 	 * Flush the memory cgroup stats, so that we read accurate per-memcg
3202aa48e47eSShakeel Butt 	 * lruvec stats for heuristics.
3203aa48e47eSShakeel Butt 	 */
3204aa48e47eSShakeel Butt 	mem_cgroup_flush_stats();
3205aa48e47eSShakeel Butt 
32060f6a5cffSJohannes Weiner 	memset(&sc->nr, 0, sizeof(sc->nr));
32070f6a5cffSJohannes Weiner 
32080f6a5cffSJohannes Weiner 	nr_reclaimed = sc->nr_reclaimed;
32090f6a5cffSJohannes Weiner 	nr_scanned = sc->nr_scanned;
32100f6a5cffSJohannes Weiner 
321153138ceaSJohannes Weiner 	/*
32127cf111bcSJohannes Weiner 	 * Determine the scan balance between anon and file LRUs.
32137cf111bcSJohannes Weiner 	 */
32146168d0daSAlex Shi 	spin_lock_irq(&target_lruvec->lru_lock);
32157cf111bcSJohannes Weiner 	sc->anon_cost = target_lruvec->anon_cost;
32167cf111bcSJohannes Weiner 	sc->file_cost = target_lruvec->file_cost;
32176168d0daSAlex Shi 	spin_unlock_irq(&target_lruvec->lru_lock);
32187cf111bcSJohannes Weiner 
32197cf111bcSJohannes Weiner 	/*
3220b91ac374SJohannes Weiner 	 * Target desirable inactive:active list ratios for the anon
3221b91ac374SJohannes Weiner 	 * and file LRU lists.
3222b91ac374SJohannes Weiner 	 */
3223b91ac374SJohannes Weiner 	if (!sc->force_deactivate) {
3224b91ac374SJohannes Weiner 		unsigned long refaults;
3225b91ac374SJohannes Weiner 
3226170b04b7SJoonsoo Kim 		refaults = lruvec_page_state(target_lruvec,
3227170b04b7SJoonsoo Kim 				WORKINGSET_ACTIVATE_ANON);
3228170b04b7SJoonsoo Kim 		if (refaults != target_lruvec->refaults[0] ||
3229170b04b7SJoonsoo Kim 			inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
3230b91ac374SJohannes Weiner 			sc->may_deactivate |= DEACTIVATE_ANON;
3231b91ac374SJohannes Weiner 		else
3232b91ac374SJohannes Weiner 			sc->may_deactivate &= ~DEACTIVATE_ANON;
3233b91ac374SJohannes Weiner 
3234b91ac374SJohannes Weiner 		/*
3235b91ac374SJohannes Weiner 		 * When refaults are being observed, it means a new
3236b91ac374SJohannes Weiner 		 * workingset is being established. Deactivate to get
3237b91ac374SJohannes Weiner 		 * rid of any stale active pages quickly.
3238b91ac374SJohannes Weiner 		 */
3239b91ac374SJohannes Weiner 		refaults = lruvec_page_state(target_lruvec,
3240170b04b7SJoonsoo Kim 				WORKINGSET_ACTIVATE_FILE);
3241170b04b7SJoonsoo Kim 		if (refaults != target_lruvec->refaults[1] ||
3242b91ac374SJohannes Weiner 		    inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
3243b91ac374SJohannes Weiner 			sc->may_deactivate |= DEACTIVATE_FILE;
3244b91ac374SJohannes Weiner 		else
3245b91ac374SJohannes Weiner 			sc->may_deactivate &= ~DEACTIVATE_FILE;
3246b91ac374SJohannes Weiner 	} else
3247b91ac374SJohannes Weiner 		sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
3248b91ac374SJohannes Weiner 
3249b91ac374SJohannes Weiner 	/*
3250b91ac374SJohannes Weiner 	 * If we have plenty of inactive file pages that aren't
3251b91ac374SJohannes Weiner 	 * thrashing, try to reclaim those first before touching
3252b91ac374SJohannes Weiner 	 * anonymous pages.
3253b91ac374SJohannes Weiner 	 */
3254b91ac374SJohannes Weiner 	file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
3255b91ac374SJohannes Weiner 	if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
3256b91ac374SJohannes Weiner 		sc->cache_trim_mode = 1;
3257b91ac374SJohannes Weiner 	else
3258b91ac374SJohannes Weiner 		sc->cache_trim_mode = 0;
3259b91ac374SJohannes Weiner 
3260b91ac374SJohannes Weiner 	/*
326153138ceaSJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
326253138ceaSJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
326353138ceaSJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
326453138ceaSJohannes Weiner 	 * shrinks, so does the window for rotation from references.
326553138ceaSJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
326653138ceaSJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
326753138ceaSJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
326853138ceaSJohannes Weiner 	 */
326953138ceaSJohannes Weiner 	if (!cgroup_reclaim(sc)) {
327053138ceaSJohannes Weiner 		unsigned long total_high_wmark = 0;
3271b91ac374SJohannes Weiner 		unsigned long free, anon;
3272b91ac374SJohannes Weiner 		int z;
327353138ceaSJohannes Weiner 
327453138ceaSJohannes Weiner 		free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
327553138ceaSJohannes Weiner 		file = node_page_state(pgdat, NR_ACTIVE_FILE) +
327653138ceaSJohannes Weiner 			   node_page_state(pgdat, NR_INACTIVE_FILE);
327753138ceaSJohannes Weiner 
327853138ceaSJohannes Weiner 		for (z = 0; z < MAX_NR_ZONES; z++) {
327953138ceaSJohannes Weiner 			struct zone *zone = &pgdat->node_zones[z];
328053138ceaSJohannes Weiner 			if (!managed_zone(zone))
328153138ceaSJohannes Weiner 				continue;
328253138ceaSJohannes Weiner 
328353138ceaSJohannes Weiner 			total_high_wmark += high_wmark_pages(zone);
328453138ceaSJohannes Weiner 		}
328553138ceaSJohannes Weiner 
3286b91ac374SJohannes Weiner 		/*
3287b91ac374SJohannes Weiner 		 * Consider anon: if that's low too, this isn't a
3288b91ac374SJohannes Weiner 		 * runaway file reclaim problem, but rather just
3289b91ac374SJohannes Weiner 		 * extreme pressure. Reclaim as per usual then.
3290b91ac374SJohannes Weiner 		 */
3291b91ac374SJohannes Weiner 		anon = node_page_state(pgdat, NR_INACTIVE_ANON);
3292b91ac374SJohannes Weiner 
3293b91ac374SJohannes Weiner 		sc->file_is_tiny =
3294b91ac374SJohannes Weiner 			file + free <= total_high_wmark &&
3295b91ac374SJohannes Weiner 			!(sc->may_deactivate & DEACTIVATE_ANON) &&
3296b91ac374SJohannes Weiner 			anon >> sc->priority;
329753138ceaSJohannes Weiner 	}
329853138ceaSJohannes Weiner 
32990f6a5cffSJohannes Weiner 	shrink_node_memcgs(pgdat, sc);
330070ddf637SAnton Vorontsov 
33016b4f7799SJohannes Weiner 	if (reclaim_state) {
3302cb731d6cSVladimir Davydov 		sc->nr_reclaimed += reclaim_state->reclaimed_slab;
33036b4f7799SJohannes Weiner 		reclaim_state->reclaimed_slab = 0;
33046b4f7799SJohannes Weiner 	}
33056b4f7799SJohannes Weiner 
33068e8ae645SJohannes Weiner 	/* Record the subtree's reclaim efficiency */
33071b05117dSJohannes Weiner 	vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
330870ddf637SAnton Vorontsov 		   sc->nr_scanned - nr_scanned,
330970ddf637SAnton Vorontsov 		   sc->nr_reclaimed - nr_reclaimed);
331070ddf637SAnton Vorontsov 
33112344d7e4SJohannes Weiner 	if (sc->nr_reclaimed - nr_reclaimed)
33122344d7e4SJohannes Weiner 		reclaimable = true;
33132344d7e4SJohannes Weiner 
3314e3c1ac58SAndrey Ryabinin 	if (current_is_kswapd()) {
3315d108c772SAndrey Ryabinin 		/*
3316e3c1ac58SAndrey Ryabinin 		 * If reclaim is isolating dirty pages under writeback,
3317e3c1ac58SAndrey Ryabinin 		 * it implies that the long-lived page allocation rate
3318e3c1ac58SAndrey Ryabinin 		 * is exceeding the page laundering rate. Either the
3319e3c1ac58SAndrey Ryabinin 		 * global limits are not being effective at throttling
3320e3c1ac58SAndrey Ryabinin 		 * processes due to the page distribution throughout
3321e3c1ac58SAndrey Ryabinin 		 * zones or there is heavy usage of a slow backing
3322e3c1ac58SAndrey Ryabinin 		 * device. The only option is to throttle from reclaim
3323e3c1ac58SAndrey Ryabinin 		 * context which is not ideal as there is no guarantee
3324d108c772SAndrey Ryabinin 		 * the dirtying process is throttled in the same way
3325d108c772SAndrey Ryabinin 		 * balance_dirty_pages() manages.
3326d108c772SAndrey Ryabinin 		 *
3327e3c1ac58SAndrey Ryabinin 		 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
3328e3c1ac58SAndrey Ryabinin 		 * count the number of pages under pages flagged for
3329e3c1ac58SAndrey Ryabinin 		 * immediate reclaim and stall if any are encountered
3330e3c1ac58SAndrey Ryabinin 		 * in the nr_immediate check below.
3331d108c772SAndrey Ryabinin 		 */
3332d108c772SAndrey Ryabinin 		if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
3333d108c772SAndrey Ryabinin 			set_bit(PGDAT_WRITEBACK, &pgdat->flags);
3334d108c772SAndrey Ryabinin 
3335d108c772SAndrey Ryabinin 		/* Allow kswapd to start writing pages during reclaim.*/
3336d108c772SAndrey Ryabinin 		if (sc->nr.unqueued_dirty == sc->nr.file_taken)
3337d108c772SAndrey Ryabinin 			set_bit(PGDAT_DIRTY, &pgdat->flags);
3338d108c772SAndrey Ryabinin 
3339d108c772SAndrey Ryabinin 		/*
33401eba09c1SRandy Dunlap 		 * If kswapd scans pages marked for immediate
3341d108c772SAndrey Ryabinin 		 * reclaim and under writeback (nr_immediate), it
3342d108c772SAndrey Ryabinin 		 * implies that pages are cycling through the LRU
33438cd7c588SMel Gorman 		 * faster than they are written so forcibly stall
33448cd7c588SMel Gorman 		 * until some pages complete writeback.
3345d108c772SAndrey Ryabinin 		 */
3346d108c772SAndrey Ryabinin 		if (sc->nr.immediate)
3347c3f4a9a2SMel Gorman 			reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
3348d108c772SAndrey Ryabinin 	}
3349d108c772SAndrey Ryabinin 
3350d108c772SAndrey Ryabinin 	/*
33518cd7c588SMel Gorman 	 * Tag a node/memcg as congested if all the dirty pages were marked
33528cd7c588SMel Gorman 	 * for writeback and immediate reclaim (counted in nr.congested).
33531b05117dSJohannes Weiner 	 *
3354e3c1ac58SAndrey Ryabinin 	 * Legacy memcg will stall in page writeback so avoid forcibly
33558cd7c588SMel Gorman 	 * stalling in reclaim_throttle().
3356e3c1ac58SAndrey Ryabinin 	 */
33571b05117dSJohannes Weiner 	if ((current_is_kswapd() ||
33581b05117dSJohannes Weiner 	     (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
3359e3c1ac58SAndrey Ryabinin 	    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
33601b05117dSJohannes Weiner 		set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
3361e3c1ac58SAndrey Ryabinin 
3362e3c1ac58SAndrey Ryabinin 	/*
33638cd7c588SMel Gorman 	 * Stall direct reclaim for IO completions if the lruvec is
33648cd7c588SMel Gorman 	 * node is congested. Allow kswapd to continue until it
3365d108c772SAndrey Ryabinin 	 * starts encountering unqueued dirty pages or cycling through
3366d108c772SAndrey Ryabinin 	 * the LRU too quickly.
3367d108c772SAndrey Ryabinin 	 */
33681b05117dSJohannes Weiner 	if (!current_is_kswapd() && current_may_throttle() &&
33691b05117dSJohannes Weiner 	    !sc->hibernation_mode &&
33701b05117dSJohannes Weiner 	    test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
33711b4e3f26SMel Gorman 		reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED);
3372d108c772SAndrey Ryabinin 
3373d2af3397SJohannes Weiner 	if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
3374d2af3397SJohannes Weiner 				    sc))
3375d2af3397SJohannes Weiner 		goto again;
33762344d7e4SJohannes Weiner 
3377c73322d0SJohannes Weiner 	/*
3378c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
3379c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
3380c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
3381c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
3382c73322d0SJohannes Weiner 	 */
3383c73322d0SJohannes Weiner 	if (reclaimable)
3384c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
3385f16015fbSJohannes Weiner }
3386f16015fbSJohannes Weiner 
338753853e2dSVlastimil Babka /*
3388fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
3389fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
3390fdd4c614SVlastimil Babka  * should reclaim first.
339153853e2dSVlastimil Babka  */
33924f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
3393fe4b1b24SMel Gorman {
339431483b6aSMel Gorman 	unsigned long watermark;
3395fdd4c614SVlastimil Babka 	enum compact_result suitable;
3396fe4b1b24SMel Gorman 
3397fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
3398fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
3399fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
3400fdd4c614SVlastimil Babka 		return true;
3401fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
3402fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
3403fe4b1b24SMel Gorman 		return false;
3404fe4b1b24SMel Gorman 
3405fdd4c614SVlastimil Babka 	/*
3406fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
3407fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
3408fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
3409fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
3410fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
3411fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
3412fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
3413fdd4c614SVlastimil Babka 	 */
3414fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
3415fdd4c614SVlastimil Babka 
3416fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
3417fe4b1b24SMel Gorman }
3418fe4b1b24SMel Gorman 
341969392a40SMel Gorman static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc)
342069392a40SMel Gorman {
342166ce520bSMel Gorman 	/*
342266ce520bSMel Gorman 	 * If reclaim is making progress greater than 12% efficiency then
342366ce520bSMel Gorman 	 * wake all the NOPROGRESS throttled tasks.
342466ce520bSMel Gorman 	 */
342566ce520bSMel Gorman 	if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) {
342669392a40SMel Gorman 		wait_queue_head_t *wqh;
342769392a40SMel Gorman 
342869392a40SMel Gorman 		wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS];
342969392a40SMel Gorman 		if (waitqueue_active(wqh))
343069392a40SMel Gorman 			wake_up(wqh);
343169392a40SMel Gorman 
343269392a40SMel Gorman 		return;
343369392a40SMel Gorman 	}
343469392a40SMel Gorman 
343569392a40SMel Gorman 	/*
34361b4e3f26SMel Gorman 	 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will
34371b4e3f26SMel Gorman 	 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages
34381b4e3f26SMel Gorman 	 * under writeback and marked for immediate reclaim at the tail of the
34391b4e3f26SMel Gorman 	 * LRU.
344069392a40SMel Gorman 	 */
34411b4e3f26SMel Gorman 	if (current_is_kswapd() || cgroup_reclaim(sc))
344269392a40SMel Gorman 		return;
344369392a40SMel Gorman 
344469392a40SMel Gorman 	/* Throttle if making no progress at high prioities. */
34451b4e3f26SMel Gorman 	if (sc->priority == 1 && !sc->nr_reclaimed)
3446c3f4a9a2SMel Gorman 		reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS);
344769392a40SMel Gorman }
344869392a40SMel Gorman 
34491da177e4SLinus Torvalds /*
34501da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
34511da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
34521da177e4SLinus Torvalds  * request.
34531da177e4SLinus Torvalds  *
34541da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
34551da177e4SLinus Torvalds  * scan then give up on it.
34561da177e4SLinus Torvalds  */
34570a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
34581da177e4SLinus Torvalds {
3459dd1a239fSMel Gorman 	struct zoneref *z;
346054a6eb5cSMel Gorman 	struct zone *zone;
34610608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
34620608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3463619d0d76SWeijie Yang 	gfp_t orig_mask;
346479dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
34651b4e3f26SMel Gorman 	pg_data_t *first_pgdat = NULL;
34661cfb419bSKAMEZAWA Hiroyuki 
3467cc715d99SMel Gorman 	/*
3468cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
3469cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
3470cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
3471cc715d99SMel Gorman 	 */
3472619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
3473b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
3474cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
34754f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
3476b2e18757SMel Gorman 	}
3477cc715d99SMel Gorman 
3478d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
3479b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
3480b2e18757SMel Gorman 		/*
34811cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
34821cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
34831cfb419bSKAMEZAWA Hiroyuki 		 */
3484b5ead35eSJohannes Weiner 		if (!cgroup_reclaim(sc)) {
3485344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
3486344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
34871da177e4SLinus Torvalds 				continue;
348865ec02cbSVladimir Davydov 
3489e0887c19SRik van Riel 			/*
3490e0c23279SMel Gorman 			 * If we already have plenty of memory free for
3491e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
3492e0c23279SMel Gorman 			 * Even though compaction is invoked for any
3493e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
3494e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
3495c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
3496c7cfa37bSCopot Alexandru 			 * page allocations.
3497e0887c19SRik van Riel 			 */
34980b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
34990b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
35004f588331SMel Gorman 			    compaction_ready(zone, sc)) {
35010b06496aSJohannes Weiner 				sc->compaction_ready = true;
3502e0887c19SRik van Riel 				continue;
3503e0887c19SRik van Riel 			}
35040b06496aSJohannes Weiner 
35050608f43dSAndrew Morton 			/*
350679dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
350779dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
350879dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
350979dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
351079dafcdcSMel Gorman 			 */
351179dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
351279dafcdcSMel Gorman 				continue;
351379dafcdcSMel Gorman 
351479dafcdcSMel Gorman 			/*
35150608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
35160608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
35170608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
35180608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
35190608f43dSAndrew Morton 			 */
35200608f43dSAndrew Morton 			nr_soft_scanned = 0;
3521ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
35220608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
35230608f43dSAndrew Morton 						&nr_soft_scanned);
35240608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
35250608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
3526ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
3527ac34a1a3SKAMEZAWA Hiroyuki 		}
3528d149e3b2SYing Han 
35291b4e3f26SMel Gorman 		if (!first_pgdat)
35301b4e3f26SMel Gorman 			first_pgdat = zone->zone_pgdat;
35311b4e3f26SMel Gorman 
353279dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
353379dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
353479dafcdcSMel Gorman 			continue;
353579dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
3536970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
35371da177e4SLinus Torvalds 	}
3538e0c23279SMel Gorman 
353980082938SMel Gorman 	if (first_pgdat)
35401b4e3f26SMel Gorman 		consider_reclaim_throttle(first_pgdat, sc);
35411b4e3f26SMel Gorman 
354265ec02cbSVladimir Davydov 	/*
3543619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
3544619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
3545619d0d76SWeijie Yang 	 */
3546619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
35471da177e4SLinus Torvalds }
35481da177e4SLinus Torvalds 
3549b910718aSJohannes Weiner static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
35502a2e4885SJohannes Weiner {
3551b910718aSJohannes Weiner 	struct lruvec *target_lruvec;
35522a2e4885SJohannes Weiner 	unsigned long refaults;
35532a2e4885SJohannes Weiner 
3554b910718aSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
3555170b04b7SJoonsoo Kim 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
3556170b04b7SJoonsoo Kim 	target_lruvec->refaults[0] = refaults;
3557170b04b7SJoonsoo Kim 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
3558170b04b7SJoonsoo Kim 	target_lruvec->refaults[1] = refaults;
35592a2e4885SJohannes Weiner }
35602a2e4885SJohannes Weiner 
35611da177e4SLinus Torvalds /*
35621da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
35631da177e4SLinus Torvalds  *
35641da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
35651da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
35661da177e4SLinus Torvalds  *
35671da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
35681da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
35695b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
35705b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
35715b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
35725b0830cbSJens Axboe  * work, and the allocation attempt will fail.
3573a41f24eaSNishanth Aravamudan  *
3574a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
3575a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
35761da177e4SLinus Torvalds  */
3577dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
35783115cd91SVladimir Davydov 					  struct scan_control *sc)
35791da177e4SLinus Torvalds {
3580241994edSJohannes Weiner 	int initial_priority = sc->priority;
35812a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
35822a2e4885SJohannes Weiner 	struct zoneref *z;
35832a2e4885SJohannes Weiner 	struct zone *zone;
3584241994edSJohannes Weiner retry:
3585873b4771SKeika Kobayashi 	delayacct_freepages_start();
3586873b4771SKeika Kobayashi 
3587b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
35887cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
35891da177e4SLinus Torvalds 
35909e3b2f8cSKonstantin Khlebnikov 	do {
359170ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
359270ddf637SAnton Vorontsov 				sc->priority);
359366e1707bSBalbir Singh 		sc->nr_scanned = 0;
35940a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
3595e0c23279SMel Gorman 
3596bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
35970b06496aSJohannes Weiner 			break;
35980b06496aSJohannes Weiner 
35990b06496aSJohannes Weiner 		if (sc->compaction_ready)
36000b06496aSJohannes Weiner 			break;
36011da177e4SLinus Torvalds 
36021da177e4SLinus Torvalds 		/*
36030e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
36040e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
36050e50ce3bSMinchan Kim 		 */
36060e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
36070e50ce3bSMinchan Kim 			sc->may_writepage = 1;
36080b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
3609bb21c7ceSKOSAKI Motohiro 
36102a2e4885SJohannes Weiner 	last_pgdat = NULL;
36112a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
36122a2e4885SJohannes Weiner 					sc->nodemask) {
36132a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
36142a2e4885SJohannes Weiner 			continue;
36152a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
36161b05117dSJohannes Weiner 
36172a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
36181b05117dSJohannes Weiner 
36191b05117dSJohannes Weiner 		if (cgroup_reclaim(sc)) {
36201b05117dSJohannes Weiner 			struct lruvec *lruvec;
36211b05117dSJohannes Weiner 
36221b05117dSJohannes Weiner 			lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
36231b05117dSJohannes Weiner 						   zone->zone_pgdat);
36241b05117dSJohannes Weiner 			clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
36251b05117dSJohannes Weiner 		}
36262a2e4885SJohannes Weiner 	}
36272a2e4885SJohannes Weiner 
3628873b4771SKeika Kobayashi 	delayacct_freepages_end();
3629873b4771SKeika Kobayashi 
3630bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
3631bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
3632bb21c7ceSKOSAKI Motohiro 
36330cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
36340b06496aSJohannes Weiner 	if (sc->compaction_ready)
36357335084dSMel Gorman 		return 1;
36367335084dSMel Gorman 
3637b91ac374SJohannes Weiner 	/*
3638b91ac374SJohannes Weiner 	 * We make inactive:active ratio decisions based on the node's
3639b91ac374SJohannes Weiner 	 * composition of memory, but a restrictive reclaim_idx or a
3640b91ac374SJohannes Weiner 	 * memory.low cgroup setting can exempt large amounts of
3641b91ac374SJohannes Weiner 	 * memory from reclaim. Neither of which are very common, so
3642b91ac374SJohannes Weiner 	 * instead of doing costly eligibility calculations of the
3643b91ac374SJohannes Weiner 	 * entire cgroup subtree up front, we assume the estimates are
3644b91ac374SJohannes Weiner 	 * good, and retry with forcible deactivation if that fails.
3645b91ac374SJohannes Weiner 	 */
3646b91ac374SJohannes Weiner 	if (sc->skipped_deactivate) {
3647b91ac374SJohannes Weiner 		sc->priority = initial_priority;
3648b91ac374SJohannes Weiner 		sc->force_deactivate = 1;
3649b91ac374SJohannes Weiner 		sc->skipped_deactivate = 0;
3650b91ac374SJohannes Weiner 		goto retry;
3651b91ac374SJohannes Weiner 	}
3652b91ac374SJohannes Weiner 
3653241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
3654d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
3655241994edSJohannes Weiner 		sc->priority = initial_priority;
3656b91ac374SJohannes Weiner 		sc->force_deactivate = 0;
3657d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
3658d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
3659241994edSJohannes Weiner 		goto retry;
3660241994edSJohannes Weiner 	}
3661241994edSJohannes Weiner 
3662bb21c7ceSKOSAKI Motohiro 	return 0;
36631da177e4SLinus Torvalds }
36641da177e4SLinus Torvalds 
3665c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
36665515061dSMel Gorman {
36675515061dSMel Gorman 	struct zone *zone;
36685515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
36695515061dSMel Gorman 	unsigned long free_pages = 0;
36705515061dSMel Gorman 	int i;
36715515061dSMel Gorman 	bool wmark_ok;
36725515061dSMel Gorman 
3673c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3674c73322d0SJohannes Weiner 		return true;
3675c73322d0SJohannes Weiner 
36765515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
36775515061dSMel Gorman 		zone = &pgdat->node_zones[i];
3678d450abd8SJohannes Weiner 		if (!managed_zone(zone))
3679d450abd8SJohannes Weiner 			continue;
3680d450abd8SJohannes Weiner 
3681d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
3682675becceSMel Gorman 			continue;
3683675becceSMel Gorman 
36845515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
36855515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
36865515061dSMel Gorman 	}
36875515061dSMel Gorman 
3688675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
3689675becceSMel Gorman 	if (!pfmemalloc_reserve)
3690675becceSMel Gorman 		return true;
3691675becceSMel Gorman 
36925515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
36935515061dSMel Gorman 
36945515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
36955515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
369697a225e6SJoonsoo Kim 		if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
369797a225e6SJoonsoo Kim 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
36985644e1fbSQian Cai 
36995515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
37005515061dSMel Gorman 	}
37015515061dSMel Gorman 
37025515061dSMel Gorman 	return wmark_ok;
37035515061dSMel Gorman }
37045515061dSMel Gorman 
37055515061dSMel Gorman /*
37065515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
37075515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
37085515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
370950694c28SMel Gorman  * when the low watermark is reached.
371050694c28SMel Gorman  *
371150694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
371250694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
37135515061dSMel Gorman  */
371450694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
37155515061dSMel Gorman 					nodemask_t *nodemask)
37165515061dSMel Gorman {
3717675becceSMel Gorman 	struct zoneref *z;
37185515061dSMel Gorman 	struct zone *zone;
3719675becceSMel Gorman 	pg_data_t *pgdat = NULL;
37205515061dSMel Gorman 
37215515061dSMel Gorman 	/*
37225515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
37235515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
37245515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
37255515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
37265515061dSMel Gorman 	 * processes to block on log_wait_commit().
37275515061dSMel Gorman 	 */
37285515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
372950694c28SMel Gorman 		goto out;
373050694c28SMel Gorman 
373150694c28SMel Gorman 	/*
373250694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
373350694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
373450694c28SMel Gorman 	 */
373550694c28SMel Gorman 	if (fatal_signal_pending(current))
373650694c28SMel Gorman 		goto out;
37375515061dSMel Gorman 
3738675becceSMel Gorman 	/*
3739675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
3740675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3741675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
3742675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
3743675becceSMel Gorman 	 *
3744675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
3745675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
3746675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
3747675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
3748675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
3749675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
3750675becceSMel Gorman 	 * should make reasonable progress.
3751675becceSMel Gorman 	 */
3752675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
375317636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
3754675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
3755675becceSMel Gorman 			continue;
3756675becceSMel Gorman 
3757675becceSMel Gorman 		/* Throttle based on the first usable node */
37585515061dSMel Gorman 		pgdat = zone->zone_pgdat;
3759c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
376050694c28SMel Gorman 			goto out;
3761675becceSMel Gorman 		break;
3762675becceSMel Gorman 	}
3763675becceSMel Gorman 
3764675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
3765675becceSMel Gorman 	if (!pgdat)
3766675becceSMel Gorman 		goto out;
37675515061dSMel Gorman 
376868243e76SMel Gorman 	/* Account for the throttling */
376968243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
377068243e76SMel Gorman 
37715515061dSMel Gorman 	/*
37725515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
37735515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
37745515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
37755515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
37765515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
37775515061dSMel Gorman 	 * second before continuing.
37785515061dSMel Gorman 	 */
37792e786d9eSMiaohe Lin 	if (!(gfp_mask & __GFP_FS))
37805515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3781c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
37822e786d9eSMiaohe Lin 	else
37835515061dSMel Gorman 		/* Throttle until kswapd wakes the process */
37845515061dSMel Gorman 		wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3785c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat));
378650694c28SMel Gorman 
378750694c28SMel Gorman 	if (fatal_signal_pending(current))
378850694c28SMel Gorman 		return true;
378950694c28SMel Gorman 
379050694c28SMel Gorman out:
379150694c28SMel Gorman 	return false;
37925515061dSMel Gorman }
37935515061dSMel Gorman 
3794dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3795327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
379666e1707bSBalbir Singh {
379733906bc5SMel Gorman 	unsigned long nr_reclaimed;
379866e1707bSBalbir Singh 	struct scan_control sc = {
379922fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3800f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3801b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
3802ee814fe2SJohannes Weiner 		.order = order,
3803ee814fe2SJohannes Weiner 		.nodemask = nodemask,
3804ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
3805ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3806a6dc60f8SJohannes Weiner 		.may_unmap = 1,
38072e2e4259SKOSAKI Motohiro 		.may_swap = 1,
380866e1707bSBalbir Singh 	};
380966e1707bSBalbir Singh 
38105515061dSMel Gorman 	/*
3811bb451fdfSGreg Thelen 	 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3812bb451fdfSGreg Thelen 	 * Confirm they are large enough for max values.
3813bb451fdfSGreg Thelen 	 */
3814bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3815bb451fdfSGreg Thelen 	BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3816bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3817bb451fdfSGreg Thelen 
3818bb451fdfSGreg Thelen 	/*
381950694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
382050694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
382150694c28SMel Gorman 	 * point.
38225515061dSMel Gorman 	 */
3823f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
38245515061dSMel Gorman 		return 1;
38255515061dSMel Gorman 
38261732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
38273481c37fSYafang Shao 	trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
382833906bc5SMel Gorman 
38293115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
383033906bc5SMel Gorman 
383133906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
38321732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
383333906bc5SMel Gorman 
383433906bc5SMel Gorman 	return nr_reclaimed;
383566e1707bSBalbir Singh }
383666e1707bSBalbir Singh 
3837c255a458SAndrew Morton #ifdef CONFIG_MEMCG
383866e1707bSBalbir Singh 
3839d2e5fb92SMichal Hocko /* Only used by soft limit reclaim. Do not reuse for anything else. */
3840a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
38414e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
3842ef8f2327SMel Gorman 						pg_data_t *pgdat,
38430ae5e89cSYing Han 						unsigned long *nr_scanned)
38444e416953SBalbir Singh {
3845afaf07a6SJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
38464e416953SBalbir Singh 	struct scan_control sc = {
3847b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3848ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
38494e416953SBalbir Singh 		.may_writepage = !laptop_mode,
38504e416953SBalbir Singh 		.may_unmap = 1,
3851b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
38524e416953SBalbir Singh 		.may_swap = !noswap,
38534e416953SBalbir Singh 	};
38540ae5e89cSYing Han 
3855d2e5fb92SMichal Hocko 	WARN_ON_ONCE(!current->reclaim_state);
3856d2e5fb92SMichal Hocko 
38574e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
38584e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3859bdce6d9eSKOSAKI Motohiro 
38609e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
38613481c37fSYafang Shao 						      sc.gfp_mask);
3862bdce6d9eSKOSAKI Motohiro 
38634e416953SBalbir Singh 	/*
38644e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
38654e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3866a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
38674e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
38684e416953SBalbir Singh 	 * the priority and make it zero.
38694e416953SBalbir Singh 	 */
3870afaf07a6SJohannes Weiner 	shrink_lruvec(lruvec, &sc);
3871bdce6d9eSKOSAKI Motohiro 
3872bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3873bdce6d9eSKOSAKI Motohiro 
38740ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
38750308f7cfSYafang Shao 
38764e416953SBalbir Singh 	return sc.nr_reclaimed;
38774e416953SBalbir Singh }
38784e416953SBalbir Singh 
387972835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3880b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
38818c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3882b70a2a21SJohannes Weiner 					   bool may_swap)
388366e1707bSBalbir Singh {
3884bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3885499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
388666e1707bSBalbir Singh 	struct scan_control sc = {
3887b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
38887dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3889ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3890b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3891ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3892ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
389366e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3894a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3895b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3896a09ed5e0SYing Han 	};
3897fa40d1eeSShakeel Butt 	/*
3898fa40d1eeSShakeel Butt 	 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
3899fa40d1eeSShakeel Butt 	 * equal pressure on all the nodes. This is based on the assumption that
3900fa40d1eeSShakeel Butt 	 * the reclaim does not bail out early.
3901fa40d1eeSShakeel Butt 	 */
3902fa40d1eeSShakeel Butt 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
390366e1707bSBalbir Singh 
39041732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
39053481c37fSYafang Shao 	trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
3906499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3907eb414681SJohannes Weiner 
39083115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3909eb414681SJohannes Weiner 
3910499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3911bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
39121732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3913bdce6d9eSKOSAKI Motohiro 
3914bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
391566e1707bSBalbir Singh }
391666e1707bSBalbir Singh #endif
391766e1707bSBalbir Singh 
39181d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3919ef8f2327SMel Gorman 				struct scan_control *sc)
3920f16015fbSJohannes Weiner {
3921b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3922b91ac374SJohannes Weiner 	struct lruvec *lruvec;
3923b95a2f2dSJohannes Weiner 
39242f368a9fSDave Hansen 	if (!can_age_anon_pages(pgdat, sc))
3925b95a2f2dSJohannes Weiner 		return;
3926b95a2f2dSJohannes Weiner 
3927b91ac374SJohannes Weiner 	lruvec = mem_cgroup_lruvec(NULL, pgdat);
3928b91ac374SJohannes Weiner 	if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
3929b91ac374SJohannes Weiner 		return;
3930b91ac374SJohannes Weiner 
3931b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3932b95a2f2dSJohannes Weiner 	do {
3933b91ac374SJohannes Weiner 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
39341a93be0eSKonstantin Khlebnikov 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
39359e3b2f8cSKonstantin Khlebnikov 				   sc, LRU_ACTIVE_ANON);
3936b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3937b95a2f2dSJohannes Weiner 	} while (memcg);
3938f16015fbSJohannes Weiner }
3939f16015fbSJohannes Weiner 
394097a225e6SJoonsoo Kim static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
39411c30844dSMel Gorman {
39421c30844dSMel Gorman 	int i;
39431c30844dSMel Gorman 	struct zone *zone;
39441c30844dSMel Gorman 
39451c30844dSMel Gorman 	/*
39461c30844dSMel Gorman 	 * Check for watermark boosts top-down as the higher zones
39471c30844dSMel Gorman 	 * are more likely to be boosted. Both watermarks and boosts
39481eba09c1SRandy Dunlap 	 * should not be checked at the same time as reclaim would
39491c30844dSMel Gorman 	 * start prematurely when there is no boosting and a lower
39501c30844dSMel Gorman 	 * zone is balanced.
39511c30844dSMel Gorman 	 */
395297a225e6SJoonsoo Kim 	for (i = highest_zoneidx; i >= 0; i--) {
39531c30844dSMel Gorman 		zone = pgdat->node_zones + i;
39541c30844dSMel Gorman 		if (!managed_zone(zone))
39551c30844dSMel Gorman 			continue;
39561c30844dSMel Gorman 
39571c30844dSMel Gorman 		if (zone->watermark_boost)
39581c30844dSMel Gorman 			return true;
39591c30844dSMel Gorman 	}
39601c30844dSMel Gorman 
39611c30844dSMel Gorman 	return false;
39621c30844dSMel Gorman }
39631c30844dSMel Gorman 
3964e716f2ebSMel Gorman /*
3965e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
396697a225e6SJoonsoo Kim  * and highest_zoneidx
3967e716f2ebSMel Gorman  */
396897a225e6SJoonsoo Kim static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
396960cefed4SJohannes Weiner {
3970e716f2ebSMel Gorman 	int i;
3971e716f2ebSMel Gorman 	unsigned long mark = -1;
3972e716f2ebSMel Gorman 	struct zone *zone;
397360cefed4SJohannes Weiner 
39741c30844dSMel Gorman 	/*
39751c30844dSMel Gorman 	 * Check watermarks bottom-up as lower zones are more likely to
39761c30844dSMel Gorman 	 * meet watermarks.
39771c30844dSMel Gorman 	 */
397897a225e6SJoonsoo Kim 	for (i = 0; i <= highest_zoneidx; i++) {
3979e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
39806256c6b4SMel Gorman 
3981e716f2ebSMel Gorman 		if (!managed_zone(zone))
3982e716f2ebSMel Gorman 			continue;
3983e716f2ebSMel Gorman 
3984c574bbe9SHuang Ying 		if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
3985c574bbe9SHuang Ying 			mark = wmark_pages(zone, WMARK_PROMO);
3986c574bbe9SHuang Ying 		else
3987e716f2ebSMel Gorman 			mark = high_wmark_pages(zone);
398897a225e6SJoonsoo Kim 		if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
39896256c6b4SMel Gorman 			return true;
399060cefed4SJohannes Weiner 	}
399160cefed4SJohannes Weiner 
3992e716f2ebSMel Gorman 	/*
399336c26128SWei Yang 	 * If a node has no managed zone within highest_zoneidx, it does not
3994e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3995e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3996e716f2ebSMel Gorman 	 */
3997e716f2ebSMel Gorman 	if (mark == -1)
3998e716f2ebSMel Gorman 		return true;
3999e716f2ebSMel Gorman 
4000e716f2ebSMel Gorman 	return false;
4001e716f2ebSMel Gorman }
4002e716f2ebSMel Gorman 
4003631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
4004631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
4005631b6e08SMel Gorman {
40061b05117dSJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
40071b05117dSJohannes Weiner 
40081b05117dSJohannes Weiner 	clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
4009631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
4010631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
4011631b6e08SMel Gorman }
4012631b6e08SMel Gorman 
40131741c877SMel Gorman /*
40145515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
40155515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
40165515061dSMel Gorman  *
40175515061dSMel Gorman  * Returns true if kswapd is ready to sleep
40185515061dSMel Gorman  */
401997a225e6SJoonsoo Kim static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
402097a225e6SJoonsoo Kim 				int highest_zoneidx)
4021f50de2d3SMel Gorman {
40225515061dSMel Gorman 	/*
40239e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
4024c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
40259e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
40269e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
40279e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
40289e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
40299e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
40309e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
40319e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
40329e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
40339e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
40345515061dSMel Gorman 	 */
40359e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
40369e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
4037f50de2d3SMel Gorman 
4038c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
4039c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
4040c73322d0SJohannes Weiner 		return true;
4041c73322d0SJohannes Weiner 
404297a225e6SJoonsoo Kim 	if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
4043631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
4044333b0a45SShantanu Goel 		return true;
40451d82de61SMel Gorman 	}
40461d82de61SMel Gorman 
4047333b0a45SShantanu Goel 	return false;
4048f50de2d3SMel Gorman }
4049f50de2d3SMel Gorman 
40501da177e4SLinus Torvalds /*
40511d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
40521d82de61SMel Gorman  * zone that is currently unbalanced.
4053b8e83b94SMel Gorman  *
4054b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
4055283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
4056283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
405775485363SMel Gorman  */
40581d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
4059accf6242SVlastimil Babka 			       struct scan_control *sc)
406075485363SMel Gorman {
40611d82de61SMel Gorman 	struct zone *zone;
40621d82de61SMel Gorman 	int z;
406375485363SMel Gorman 
40641d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
40651d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
4066970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
40671d82de61SMel Gorman 		zone = pgdat->node_zones + z;
40686aa303deSMel Gorman 		if (!managed_zone(zone))
40691d82de61SMel Gorman 			continue;
40707c954f6dSMel Gorman 
40711d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
40727c954f6dSMel Gorman 	}
40737c954f6dSMel Gorman 
40741d82de61SMel Gorman 	/*
40751d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
40761d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
40771d82de61SMel Gorman 	 */
4078970a39a3SMel Gorman 	shrink_node(pgdat, sc);
40791d82de61SMel Gorman 
40801d82de61SMel Gorman 	/*
40811d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
40821d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
40831d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
40841d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
40851d82de61SMel Gorman 	 * can direct reclaim/compact.
40861d82de61SMel Gorman 	 */
40879861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
40881d82de61SMel Gorman 		sc->order = 0;
40891d82de61SMel Gorman 
4090b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
409175485363SMel Gorman }
409275485363SMel Gorman 
4093c49c2c47SMel Gorman /* Page allocator PCP high watermark is lowered if reclaim is active. */
4094c49c2c47SMel Gorman static inline void
4095c49c2c47SMel Gorman update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
4096c49c2c47SMel Gorman {
4097c49c2c47SMel Gorman 	int i;
4098c49c2c47SMel Gorman 	struct zone *zone;
4099c49c2c47SMel Gorman 
4100c49c2c47SMel Gorman 	for (i = 0; i <= highest_zoneidx; i++) {
4101c49c2c47SMel Gorman 		zone = pgdat->node_zones + i;
4102c49c2c47SMel Gorman 
4103c49c2c47SMel Gorman 		if (!managed_zone(zone))
4104c49c2c47SMel Gorman 			continue;
4105c49c2c47SMel Gorman 
4106c49c2c47SMel Gorman 		if (active)
4107c49c2c47SMel Gorman 			set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
4108c49c2c47SMel Gorman 		else
4109c49c2c47SMel Gorman 			clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
4110c49c2c47SMel Gorman 	}
4111c49c2c47SMel Gorman }
4112c49c2c47SMel Gorman 
4113c49c2c47SMel Gorman static inline void
4114c49c2c47SMel Gorman set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
4115c49c2c47SMel Gorman {
4116c49c2c47SMel Gorman 	update_reclaim_active(pgdat, highest_zoneidx, true);
4117c49c2c47SMel Gorman }
4118c49c2c47SMel Gorman 
4119c49c2c47SMel Gorman static inline void
4120c49c2c47SMel Gorman clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
4121c49c2c47SMel Gorman {
4122c49c2c47SMel Gorman 	update_reclaim_active(pgdat, highest_zoneidx, false);
4123c49c2c47SMel Gorman }
4124c49c2c47SMel Gorman 
412575485363SMel Gorman /*
41261d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
41271d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
41281d82de61SMel Gorman  * balanced.
41291da177e4SLinus Torvalds  *
41301d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
41311da177e4SLinus Torvalds  *
41321da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
413341858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
41348bb4e7a2SWei Yang  * found to have free_pages <= high_wmark_pages(zone), any page in that zone
41351d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
41361d82de61SMel Gorman  * balanced.
41371da177e4SLinus Torvalds  */
413897a225e6SJoonsoo Kim static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
41391da177e4SLinus Torvalds {
41401da177e4SLinus Torvalds 	int i;
41410608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
41420608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
4143eb414681SJohannes Weiner 	unsigned long pflags;
41441c30844dSMel Gorman 	unsigned long nr_boost_reclaim;
41451c30844dSMel Gorman 	unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
41461c30844dSMel Gorman 	bool boosted;
41471d82de61SMel Gorman 	struct zone *zone;
4148179e9639SAndrew Morton 	struct scan_control sc = {
4149179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
4150ee814fe2SJohannes Weiner 		.order = order,
4151a6dc60f8SJohannes Weiner 		.may_unmap = 1,
4152179e9639SAndrew Morton 	};
415393781325SOmar Sandoval 
41541732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
4155eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
41564f3eaf45SMatthew Wilcox (Oracle) 	__fs_reclaim_acquire(_THIS_IP_);
415793781325SOmar Sandoval 
4158f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
41591da177e4SLinus Torvalds 
41601c30844dSMel Gorman 	/*
41611c30844dSMel Gorman 	 * Account for the reclaim boost. Note that the zone boost is left in
41621c30844dSMel Gorman 	 * place so that parallel allocations that are near the watermark will
41631c30844dSMel Gorman 	 * stall or direct reclaim until kswapd is finished.
41641c30844dSMel Gorman 	 */
41651c30844dSMel Gorman 	nr_boost_reclaim = 0;
416697a225e6SJoonsoo Kim 	for (i = 0; i <= highest_zoneidx; i++) {
41671c30844dSMel Gorman 		zone = pgdat->node_zones + i;
41681c30844dSMel Gorman 		if (!managed_zone(zone))
41691c30844dSMel Gorman 			continue;
41701c30844dSMel Gorman 
41711c30844dSMel Gorman 		nr_boost_reclaim += zone->watermark_boost;
41721c30844dSMel Gorman 		zone_boosts[i] = zone->watermark_boost;
41731c30844dSMel Gorman 	}
41741c30844dSMel Gorman 	boosted = nr_boost_reclaim;
41751c30844dSMel Gorman 
41761c30844dSMel Gorman restart:
4177c49c2c47SMel Gorman 	set_reclaim_active(pgdat, highest_zoneidx);
41781c30844dSMel Gorman 	sc.priority = DEF_PRIORITY;
41799e3b2f8cSKonstantin Khlebnikov 	do {
4180c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
4181b8e83b94SMel Gorman 		bool raise_priority = true;
41821c30844dSMel Gorman 		bool balanced;
418393781325SOmar Sandoval 		bool ret;
4184b8e83b94SMel Gorman 
418597a225e6SJoonsoo Kim 		sc.reclaim_idx = highest_zoneidx;
41861da177e4SLinus Torvalds 
418786c79f6bSMel Gorman 		/*
418884c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
418984c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
419084c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
419184c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
419284c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
419384c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
419484c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
419584c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
419686c79f6bSMel Gorman 		 */
419786c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
419886c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
419986c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
42006aa303deSMel Gorman 				if (!managed_zone(zone))
420186c79f6bSMel Gorman 					continue;
420286c79f6bSMel Gorman 
4203970a39a3SMel Gorman 				sc.reclaim_idx = i;
420486c79f6bSMel Gorman 				break;
420586c79f6bSMel Gorman 			}
420686c79f6bSMel Gorman 		}
420786c79f6bSMel Gorman 
420886c79f6bSMel Gorman 		/*
42091c30844dSMel Gorman 		 * If the pgdat is imbalanced then ignore boosting and preserve
42101c30844dSMel Gorman 		 * the watermarks for a later time and restart. Note that the
42111c30844dSMel Gorman 		 * zone watermarks will be still reset at the end of balancing
42121c30844dSMel Gorman 		 * on the grounds that the normal reclaim should be enough to
42131c30844dSMel Gorman 		 * re-evaluate if boosting is required when kswapd next wakes.
421486c79f6bSMel Gorman 		 */
421597a225e6SJoonsoo Kim 		balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
42161c30844dSMel Gorman 		if (!balanced && nr_boost_reclaim) {
42171c30844dSMel Gorman 			nr_boost_reclaim = 0;
42181c30844dSMel Gorman 			goto restart;
42191c30844dSMel Gorman 		}
42201c30844dSMel Gorman 
42211c30844dSMel Gorman 		/*
42221c30844dSMel Gorman 		 * If boosting is not active then only reclaim if there are no
42231c30844dSMel Gorman 		 * eligible zones. Note that sc.reclaim_idx is not used as
42241c30844dSMel Gorman 		 * buffer_heads_over_limit may have adjusted it.
42251c30844dSMel Gorman 		 */
42261c30844dSMel Gorman 		if (!nr_boost_reclaim && balanced)
42271da177e4SLinus Torvalds 			goto out;
4228e1dbeda6SAndrew Morton 
42291c30844dSMel Gorman 		/* Limit the priority of boosting to avoid reclaim writeback */
42301c30844dSMel Gorman 		if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
42311c30844dSMel Gorman 			raise_priority = false;
42321c30844dSMel Gorman 
42331c30844dSMel Gorman 		/*
42341c30844dSMel Gorman 		 * Do not writeback or swap pages for boosted reclaim. The
42351c30844dSMel Gorman 		 * intent is to relieve pressure not issue sub-optimal IO
42361c30844dSMel Gorman 		 * from reclaim context. If no pages are reclaimed, the
42371c30844dSMel Gorman 		 * reclaim will be aborted.
42381c30844dSMel Gorman 		 */
42391c30844dSMel Gorman 		sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
42401c30844dSMel Gorman 		sc.may_swap = !nr_boost_reclaim;
42411c30844dSMel Gorman 
42421da177e4SLinus Torvalds 		/*
42431d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
42441d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
42451d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
42461d82de61SMel Gorman 		 * about consistent aging.
42471d82de61SMel Gorman 		 */
4248ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
42491d82de61SMel Gorman 
42501d82de61SMel Gorman 		/*
4251b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
4252b7ea3c41SMel Gorman 		 * even in laptop mode.
4253b7ea3c41SMel Gorman 		 */
4254047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
4255b7ea3c41SMel Gorman 			sc.may_writepage = 1;
4256b7ea3c41SMel Gorman 
42571d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
42581da177e4SLinus Torvalds 		sc.nr_scanned = 0;
42590608f43dSAndrew Morton 		nr_soft_scanned = 0;
4260ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
42611d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
42620608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
42630608f43dSAndrew Morton 
426432a4330dSRik van Riel 		/*
42651d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
42661d82de61SMel Gorman 		 * enough pages are already being scanned that that high
42671d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
426832a4330dSRik van Riel 		 */
4269970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
4270b8e83b94SMel Gorman 			raise_priority = false;
4271d7868daeSMel Gorman 
42725515061dSMel Gorman 		/*
42735515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
42745515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
42755515061dSMel Gorman 		 * able to safely make forward progress. Wake them
42765515061dSMel Gorman 		 */
42775515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
4278c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
4279cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
42805515061dSMel Gorman 
4281b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
42824f3eaf45SMatthew Wilcox (Oracle) 		__fs_reclaim_release(_THIS_IP_);
428393781325SOmar Sandoval 		ret = try_to_freeze();
42844f3eaf45SMatthew Wilcox (Oracle) 		__fs_reclaim_acquire(_THIS_IP_);
428593781325SOmar Sandoval 		if (ret || kthread_should_stop())
4286b8e83b94SMel Gorman 			break;
4287b8e83b94SMel Gorman 
4288b8e83b94SMel Gorman 		/*
4289b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
4290b8e83b94SMel Gorman 		 * progress in reclaiming pages
4291b8e83b94SMel Gorman 		 */
4292c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
42931c30844dSMel Gorman 		nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
42941c30844dSMel Gorman 
42951c30844dSMel Gorman 		/*
42961c30844dSMel Gorman 		 * If reclaim made no progress for a boost, stop reclaim as
42971c30844dSMel Gorman 		 * IO cannot be queued and it could be an infinite loop in
42981c30844dSMel Gorman 		 * extreme circumstances.
42991c30844dSMel Gorman 		 */
43001c30844dSMel Gorman 		if (nr_boost_reclaim && !nr_reclaimed)
43011c30844dSMel Gorman 			break;
43021c30844dSMel Gorman 
4303c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
4304b8e83b94SMel Gorman 			sc.priority--;
43051d82de61SMel Gorman 	} while (sc.priority >= 1);
43061da177e4SLinus Torvalds 
4307c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
4308c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
4309c73322d0SJohannes Weiner 
4310b8e83b94SMel Gorman out:
4311c49c2c47SMel Gorman 	clear_reclaim_active(pgdat, highest_zoneidx);
4312c49c2c47SMel Gorman 
43131c30844dSMel Gorman 	/* If reclaim was boosted, account for the reclaim done in this pass */
43141c30844dSMel Gorman 	if (boosted) {
43151c30844dSMel Gorman 		unsigned long flags;
43161c30844dSMel Gorman 
431797a225e6SJoonsoo Kim 		for (i = 0; i <= highest_zoneidx; i++) {
43181c30844dSMel Gorman 			if (!zone_boosts[i])
43191c30844dSMel Gorman 				continue;
43201c30844dSMel Gorman 
43211c30844dSMel Gorman 			/* Increments are under the zone lock */
43221c30844dSMel Gorman 			zone = pgdat->node_zones + i;
43231c30844dSMel Gorman 			spin_lock_irqsave(&zone->lock, flags);
43241c30844dSMel Gorman 			zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
43251c30844dSMel Gorman 			spin_unlock_irqrestore(&zone->lock, flags);
43261c30844dSMel Gorman 		}
43271c30844dSMel Gorman 
43281c30844dSMel Gorman 		/*
43291c30844dSMel Gorman 		 * As there is now likely space, wakeup kcompact to defragment
43301c30844dSMel Gorman 		 * pageblocks.
43311c30844dSMel Gorman 		 */
433297a225e6SJoonsoo Kim 		wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
43331c30844dSMel Gorman 	}
43341c30844dSMel Gorman 
43352a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
43364f3eaf45SMatthew Wilcox (Oracle) 	__fs_reclaim_release(_THIS_IP_);
4337eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
43381732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
4339e5ca8071SYafang Shao 
43400abdee2bSMel Gorman 	/*
43411d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
43421d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
43431d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
43441d82de61SMel Gorman 	 * remain at the higher level.
43450abdee2bSMel Gorman 	 */
43461d82de61SMel Gorman 	return sc.order;
43471da177e4SLinus Torvalds }
43481da177e4SLinus Torvalds 
4349e716f2ebSMel Gorman /*
435097a225e6SJoonsoo Kim  * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
435197a225e6SJoonsoo Kim  * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
435297a225e6SJoonsoo Kim  * not a valid index then either kswapd runs for first time or kswapd couldn't
435397a225e6SJoonsoo Kim  * sleep after previous reclaim attempt (node is still unbalanced). In that
435497a225e6SJoonsoo Kim  * case return the zone index of the previous kswapd reclaim cycle.
4355e716f2ebSMel Gorman  */
435697a225e6SJoonsoo Kim static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
435797a225e6SJoonsoo Kim 					   enum zone_type prev_highest_zoneidx)
4358e716f2ebSMel Gorman {
435997a225e6SJoonsoo Kim 	enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
43605644e1fbSQian Cai 
436197a225e6SJoonsoo Kim 	return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
4362e716f2ebSMel Gorman }
4363e716f2ebSMel Gorman 
436438087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
436597a225e6SJoonsoo Kim 				unsigned int highest_zoneidx)
4366f0bc0a60SKOSAKI Motohiro {
4367f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
4368f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
4369f0bc0a60SKOSAKI Motohiro 
4370f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
4371f0bc0a60SKOSAKI Motohiro 		return;
4372f0bc0a60SKOSAKI Motohiro 
4373f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
4374f0bc0a60SKOSAKI Motohiro 
4375333b0a45SShantanu Goel 	/*
4376333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
4377333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
4378333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
4379333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
4380333b0a45SShantanu Goel 	 * succeed.
4381333b0a45SShantanu Goel 	 */
438297a225e6SJoonsoo Kim 	if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
4383fd901c95SVlastimil Babka 		/*
4384fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
4385fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
4386fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
4387fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
4388fd901c95SVlastimil Babka 		 */
4389fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
4390fd901c95SVlastimil Babka 
4391fd901c95SVlastimil Babka 		/*
4392fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
4393fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
4394fd901c95SVlastimil Babka 		 */
439597a225e6SJoonsoo Kim 		wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
4396fd901c95SVlastimil Babka 
4397f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
439838087d9bSMel Gorman 
439938087d9bSMel Gorman 		/*
440097a225e6SJoonsoo Kim 		 * If woken prematurely then reset kswapd_highest_zoneidx and
440138087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
440238087d9bSMel Gorman 		 * the previous request that slept prematurely.
440338087d9bSMel Gorman 		 */
440438087d9bSMel Gorman 		if (remaining) {
440597a225e6SJoonsoo Kim 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
440697a225e6SJoonsoo Kim 					kswapd_highest_zoneidx(pgdat,
440797a225e6SJoonsoo Kim 							highest_zoneidx));
44085644e1fbSQian Cai 
44095644e1fbSQian Cai 			if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
44105644e1fbSQian Cai 				WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
441138087d9bSMel Gorman 		}
441238087d9bSMel Gorman 
4413f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
4414f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
4415f0bc0a60SKOSAKI Motohiro 	}
4416f0bc0a60SKOSAKI Motohiro 
4417f0bc0a60SKOSAKI Motohiro 	/*
4418f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
4419f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
4420f0bc0a60SKOSAKI Motohiro 	 */
4421d9f21d42SMel Gorman 	if (!remaining &&
442297a225e6SJoonsoo Kim 	    prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
4423f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
4424f0bc0a60SKOSAKI Motohiro 
4425f0bc0a60SKOSAKI Motohiro 		/*
4426f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
4427f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
4428f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
4429f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
4430f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
4431f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
4432f0bc0a60SKOSAKI Motohiro 		 */
4433f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
44341c7e7f6cSAaditya Kumar 
44351c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
4436f0bc0a60SKOSAKI Motohiro 			schedule();
44371c7e7f6cSAaditya Kumar 
4438f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
4439f0bc0a60SKOSAKI Motohiro 	} else {
4440f0bc0a60SKOSAKI Motohiro 		if (remaining)
4441f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
4442f0bc0a60SKOSAKI Motohiro 		else
4443f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
4444f0bc0a60SKOSAKI Motohiro 	}
4445f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
4446f0bc0a60SKOSAKI Motohiro }
4447f0bc0a60SKOSAKI Motohiro 
44481da177e4SLinus Torvalds /*
44491da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
44501da177e4SLinus Torvalds  * from the init process.
44511da177e4SLinus Torvalds  *
44521da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
44531da177e4SLinus Torvalds  * free memory available even if there is no other activity
44541da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
44551da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
44561da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
44571da177e4SLinus Torvalds  *
44581da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
44591da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
44601da177e4SLinus Torvalds  */
44611da177e4SLinus Torvalds static int kswapd(void *p)
44621da177e4SLinus Torvalds {
4463e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
446497a225e6SJoonsoo Kim 	unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
44651da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t *)p;
44661da177e4SLinus Torvalds 	struct task_struct *tsk = current;
4467a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
44681da177e4SLinus Torvalds 
4469174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
4470c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
44711da177e4SLinus Torvalds 
44721da177e4SLinus Torvalds 	/*
44731da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
44741da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
44751da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
44761da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
44771da177e4SLinus Torvalds 	 *
44781da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
44791da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
44801da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
44811da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
44821da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
44831da177e4SLinus Torvalds 	 */
4484b698f0a1SHugh Dickins 	tsk->flags |= PF_MEMALLOC | PF_KSWAPD;
448583144186SRafael J. Wysocki 	set_freezable();
44861da177e4SLinus Torvalds 
44875644e1fbSQian Cai 	WRITE_ONCE(pgdat->kswapd_order, 0);
448897a225e6SJoonsoo Kim 	WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
44898cd7c588SMel Gorman 	atomic_set(&pgdat->nr_writeback_throttled, 0);
44901da177e4SLinus Torvalds 	for ( ; ; ) {
44916f6313d4SJeff Liu 		bool ret;
44923e1d1d28SChristoph Lameter 
44935644e1fbSQian Cai 		alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
449497a225e6SJoonsoo Kim 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
449597a225e6SJoonsoo Kim 							highest_zoneidx);
4496e716f2ebSMel Gorman 
449738087d9bSMel Gorman kswapd_try_sleep:
449838087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
449997a225e6SJoonsoo Kim 					highest_zoneidx);
4500215ddd66SMel Gorman 
450197a225e6SJoonsoo Kim 		/* Read the new order and highest_zoneidx */
45022b47a24cSLukas Bulwahn 		alloc_order = READ_ONCE(pgdat->kswapd_order);
450397a225e6SJoonsoo Kim 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
450497a225e6SJoonsoo Kim 							highest_zoneidx);
45055644e1fbSQian Cai 		WRITE_ONCE(pgdat->kswapd_order, 0);
450697a225e6SJoonsoo Kim 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
45071da177e4SLinus Torvalds 
45088fe23e05SDavid Rientjes 		ret = try_to_freeze();
45098fe23e05SDavid Rientjes 		if (kthread_should_stop())
45108fe23e05SDavid Rientjes 			break;
45118fe23e05SDavid Rientjes 
45128fe23e05SDavid Rientjes 		/*
45138fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
45148fe23e05SDavid Rientjes 		 * after returning from the refrigerator
4515b1296cc4SRafael J. Wysocki 		 */
451638087d9bSMel Gorman 		if (ret)
451738087d9bSMel Gorman 			continue;
45181d82de61SMel Gorman 
451938087d9bSMel Gorman 		/*
452038087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
452138087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
452238087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
452338087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
452438087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
452538087d9bSMel Gorman 		 * request (alloc_order).
452638087d9bSMel Gorman 		 */
452797a225e6SJoonsoo Kim 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
4528e5146b12SMel Gorman 						alloc_order);
452997a225e6SJoonsoo Kim 		reclaim_order = balance_pgdat(pgdat, alloc_order,
453097a225e6SJoonsoo Kim 						highest_zoneidx);
453138087d9bSMel Gorman 		if (reclaim_order < alloc_order)
453238087d9bSMel Gorman 			goto kswapd_try_sleep;
453333906bc5SMel Gorman 	}
4534b0a8cc58STakamori Yamaguchi 
4535b698f0a1SHugh Dickins 	tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD);
453671abdc15SJohannes Weiner 
45371da177e4SLinus Torvalds 	return 0;
45381da177e4SLinus Torvalds }
45391da177e4SLinus Torvalds 
45401da177e4SLinus Torvalds /*
45415ecd9d40SDavid Rientjes  * A zone is low on free memory or too fragmented for high-order memory.  If
45425ecd9d40SDavid Rientjes  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
45435ecd9d40SDavid Rientjes  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
45445ecd9d40SDavid Rientjes  * has failed or is not needed, still wake up kcompactd if only compaction is
45455ecd9d40SDavid Rientjes  * needed.
45461da177e4SLinus Torvalds  */
45475ecd9d40SDavid Rientjes void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
454897a225e6SJoonsoo Kim 		   enum zone_type highest_zoneidx)
45491da177e4SLinus Torvalds {
45501da177e4SLinus Torvalds 	pg_data_t *pgdat;
45515644e1fbSQian Cai 	enum zone_type curr_idx;
45521da177e4SLinus Torvalds 
45536aa303deSMel Gorman 	if (!managed_zone(zone))
45541da177e4SLinus Torvalds 		return;
45551da177e4SLinus Torvalds 
45565ecd9d40SDavid Rientjes 	if (!cpuset_zone_allowed(zone, gfp_flags))
45571da177e4SLinus Torvalds 		return;
4558dffcac2cSShakeel Butt 
45595644e1fbSQian Cai 	pgdat = zone->zone_pgdat;
456097a225e6SJoonsoo Kim 	curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
45615644e1fbSQian Cai 
456297a225e6SJoonsoo Kim 	if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
456397a225e6SJoonsoo Kim 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
45645644e1fbSQian Cai 
45655644e1fbSQian Cai 	if (READ_ONCE(pgdat->kswapd_order) < order)
45665644e1fbSQian Cai 		WRITE_ONCE(pgdat->kswapd_order, order);
45675644e1fbSQian Cai 
45688d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
45691da177e4SLinus Torvalds 		return;
4570e1a55637SMel Gorman 
45715ecd9d40SDavid Rientjes 	/* Hopeless node, leave it to direct reclaim if possible */
45725ecd9d40SDavid Rientjes 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
457397a225e6SJoonsoo Kim 	    (pgdat_balanced(pgdat, order, highest_zoneidx) &&
457497a225e6SJoonsoo Kim 	     !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
45755ecd9d40SDavid Rientjes 		/*
45765ecd9d40SDavid Rientjes 		 * There may be plenty of free memory available, but it's too
45775ecd9d40SDavid Rientjes 		 * fragmented for high-order allocations.  Wake up kcompactd
45785ecd9d40SDavid Rientjes 		 * and rely on compaction_suitable() to determine if it's
45795ecd9d40SDavid Rientjes 		 * needed.  If it fails, it will defer subsequent attempts to
45805ecd9d40SDavid Rientjes 		 * ratelimit its work.
45815ecd9d40SDavid Rientjes 		 */
45825ecd9d40SDavid Rientjes 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
458397a225e6SJoonsoo Kim 			wakeup_kcompactd(pgdat, order, highest_zoneidx);
4584c73322d0SJohannes Weiner 		return;
45855ecd9d40SDavid Rientjes 	}
4586c73322d0SJohannes Weiner 
458797a225e6SJoonsoo Kim 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
45885ecd9d40SDavid Rientjes 				      gfp_flags);
45898d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
45901da177e4SLinus Torvalds }
45911da177e4SLinus Torvalds 
4592c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
45931da177e4SLinus Torvalds /*
45947b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
4595d6277db4SRafael J. Wysocki  * freed pages.
4596d6277db4SRafael J. Wysocki  *
4597d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
4598d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
4599d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
46001da177e4SLinus Torvalds  */
46017b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
46021da177e4SLinus Torvalds {
4603d6277db4SRafael J. Wysocki 	struct scan_control sc = {
46047b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
4605ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
4606b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
46079e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
4608ee814fe2SJohannes Weiner 		.may_writepage = 1,
4609ee814fe2SJohannes Weiner 		.may_unmap = 1,
4610ee814fe2SJohannes Weiner 		.may_swap = 1,
4611ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
46121da177e4SLinus Torvalds 	};
46137b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
46147b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
4615499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
46161da177e4SLinus Torvalds 
4617d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
461893781325SOmar Sandoval 	noreclaim_flag = memalloc_noreclaim_save();
46191732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
4620d6277db4SRafael J. Wysocki 
46213115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4622d6277db4SRafael J. Wysocki 
46231732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
4624499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
462593781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4626d6277db4SRafael J. Wysocki 
46277b51755cSKOSAKI Motohiro 	return nr_reclaimed;
46281da177e4SLinus Torvalds }
4629c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
46301da177e4SLinus Torvalds 
46313218ae14SYasunori Goto /*
46323218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
46333218ae14SYasunori Goto  */
4634b87c517aSMiaohe Lin void kswapd_run(int nid)
46353218ae14SYasunori Goto {
46363218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
46373218ae14SYasunori Goto 
46383218ae14SYasunori Goto 	if (pgdat->kswapd)
4639b87c517aSMiaohe Lin 		return;
46403218ae14SYasunori Goto 
46413218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
46423218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
46433218ae14SYasunori Goto 		/* failure at boot is fatal */
4644c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
4645d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
4646d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
46473218ae14SYasunori Goto 	}
46483218ae14SYasunori Goto }
46493218ae14SYasunori Goto 
46508fe23e05SDavid Rientjes /*
4651d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
4652bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
46538fe23e05SDavid Rientjes  */
46548fe23e05SDavid Rientjes void kswapd_stop(int nid)
46558fe23e05SDavid Rientjes {
46568fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
46578fe23e05SDavid Rientjes 
4658d8adde17SJiang Liu 	if (kswapd) {
46598fe23e05SDavid Rientjes 		kthread_stop(kswapd);
4660d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
4661d8adde17SJiang Liu 	}
46628fe23e05SDavid Rientjes }
46638fe23e05SDavid Rientjes 
46641da177e4SLinus Torvalds static int __init kswapd_init(void)
46651da177e4SLinus Torvalds {
46666b700b5bSWei Yang 	int nid;
466769e05944SAndrew Morton 
46681da177e4SLinus Torvalds 	swap_setup();
466948fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
46703218ae14SYasunori Goto  		kswapd_run(nid);
46711da177e4SLinus Torvalds 	return 0;
46721da177e4SLinus Torvalds }
46731da177e4SLinus Torvalds 
46741da177e4SLinus Torvalds module_init(kswapd_init)
46759eeff239SChristoph Lameter 
46769eeff239SChristoph Lameter #ifdef CONFIG_NUMA
46779eeff239SChristoph Lameter /*
4678a5f5f91dSMel Gorman  * Node reclaim mode
46799eeff239SChristoph Lameter  *
4680a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
46819eeff239SChristoph Lameter  * the watermarks.
46829eeff239SChristoph Lameter  */
4683a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
46849eeff239SChristoph Lameter 
468551998364SDave Hansen /*
4686a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
4687a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
4688a92f7126SChristoph Lameter  * a zone.
4689a92f7126SChristoph Lameter  */
4690a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
4691a92f7126SChristoph Lameter 
46929eeff239SChristoph Lameter /*
4693a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
46949614634fSChristoph Lameter  * occur.
46959614634fSChristoph Lameter  */
46969614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
46979614634fSChristoph Lameter 
46989614634fSChristoph Lameter /*
46990ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
47000ff38490SChristoph Lameter  * slab reclaim needs to occur.
47010ff38490SChristoph Lameter  */
47020ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
47030ff38490SChristoph Lameter 
470411fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
470590afa5deSMel Gorman {
470611fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
470711fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
470811fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
470990afa5deSMel Gorman 
471090afa5deSMel Gorman 	/*
471190afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
471290afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
471390afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
471490afa5deSMel Gorman 	 */
471590afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
471690afa5deSMel Gorman }
471790afa5deSMel Gorman 
471890afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4719a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
472090afa5deSMel Gorman {
4721d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
4722d031a157SAlexandru Moise 	unsigned long delta = 0;
472390afa5deSMel Gorman 
472490afa5deSMel Gorman 	/*
472595bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
472690afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
472711fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
472890afa5deSMel Gorman 	 * a better estimate
472990afa5deSMel Gorman 	 */
4730a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
4731a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
473290afa5deSMel Gorman 	else
4733a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
473490afa5deSMel Gorman 
473590afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
4736a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
4737a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
473890afa5deSMel Gorman 
473990afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
474090afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
474190afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
474290afa5deSMel Gorman 
474390afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
474490afa5deSMel Gorman }
474590afa5deSMel Gorman 
47460ff38490SChristoph Lameter /*
4747a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
47489eeff239SChristoph Lameter  */
4749a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
47509eeff239SChristoph Lameter {
47517fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
475269e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
47539eeff239SChristoph Lameter 	struct task_struct *p = current;
4754499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
4755179e9639SAndrew Morton 	struct scan_control sc = {
475662b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4757f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
4758bd2f6199SJohannes Weiner 		.order = order,
4759a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
4760a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4761a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4762ee814fe2SJohannes Weiner 		.may_swap = 1,
4763f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
4764179e9639SAndrew Morton 	};
476557f29762SJohannes Weiner 	unsigned long pflags;
47669eeff239SChristoph Lameter 
4767132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4768132bb8cfSYafang Shao 					   sc.gfp_mask);
4769132bb8cfSYafang Shao 
47709eeff239SChristoph Lameter 	cond_resched();
477157f29762SJohannes Weiner 	psi_memstall_enter(&pflags);
477293781325SOmar Sandoval 	fs_reclaim_acquire(sc.gfp_mask);
4773d4f7796eSChristoph Lameter 	/*
477495bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4775d4f7796eSChristoph Lameter 	 */
4776499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
47771732d2b0SAndrew Morton 	set_task_reclaim_state(p, &sc.reclaim_state);
4778c84db23cSChristoph Lameter 
4779d8ff6fdeSMiaohe Lin 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages ||
4780d8ff6fdeSMiaohe Lin 	    node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) {
4781a92f7126SChristoph Lameter 		/*
4782894befecSAndrey Ryabinin 		 * Free memory by calling shrink node with increasing
47830ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
4784a92f7126SChristoph Lameter 		 */
4785a92f7126SChristoph Lameter 		do {
4786970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
47879e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
47880ff38490SChristoph Lameter 	}
4789a92f7126SChristoph Lameter 
47901732d2b0SAndrew Morton 	set_task_reclaim_state(p, NULL);
4791499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
479293781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
479357f29762SJohannes Weiner 	psi_memstall_leave(&pflags);
4794132bb8cfSYafang Shao 
4795132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4796132bb8cfSYafang Shao 
4797a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
47989eeff239SChristoph Lameter }
4799179e9639SAndrew Morton 
4800a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4801179e9639SAndrew Morton {
4802d773ed6bSDavid Rientjes 	int ret;
4803179e9639SAndrew Morton 
4804179e9639SAndrew Morton 	/*
4805a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
48060ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
480734aa1330SChristoph Lameter 	 *
48089614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
48099614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
4810a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
4811a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
48129614634fSChristoph Lameter 	 * unmapped file backed pages.
4813179e9639SAndrew Morton 	 */
4814a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4815d42f3245SRoman Gushchin 	    node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
4816d42f3245SRoman Gushchin 	    pgdat->min_slab_pages)
4817a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
4818179e9639SAndrew Morton 
4819179e9639SAndrew Morton 	/*
4820d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
4821179e9639SAndrew Morton 	 */
4822d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4823a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4824179e9639SAndrew Morton 
4825179e9639SAndrew Morton 	/*
4826a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
4827179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
4828179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
4829179e9639SAndrew Morton 	 * as wide as possible.
4830179e9639SAndrew Morton 	 */
4831a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4832a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4833d773ed6bSDavid Rientjes 
4834a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4835a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4836fa5e084eSMel Gorman 
4837a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
4838a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4839d773ed6bSDavid Rientjes 
484024cf7251SMel Gorman 	if (!ret)
484124cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
484224cf7251SMel Gorman 
4843d773ed6bSDavid Rientjes 	return ret;
4844179e9639SAndrew Morton }
48459eeff239SChristoph Lameter #endif
4846894bc310SLee Schermerhorn 
484789e004eaSLee Schermerhorn /**
484864e3d12fSKuo-Hsin Yang  * check_move_unevictable_pages - check pages for evictability and move to
484964e3d12fSKuo-Hsin Yang  * appropriate zone lru list
485064e3d12fSKuo-Hsin Yang  * @pvec: pagevec with lru pages to check
485189e004eaSLee Schermerhorn  *
485264e3d12fSKuo-Hsin Yang  * Checks pages for evictability, if an evictable page is in the unevictable
485364e3d12fSKuo-Hsin Yang  * lru list, moves it to the appropriate evictable lru list. This function
485464e3d12fSKuo-Hsin Yang  * should be only used for lru pages.
485589e004eaSLee Schermerhorn  */
485664e3d12fSKuo-Hsin Yang void check_move_unevictable_pages(struct pagevec *pvec)
485789e004eaSLee Schermerhorn {
48586168d0daSAlex Shi 	struct lruvec *lruvec = NULL;
485924513264SHugh Dickins 	int pgscanned = 0;
486024513264SHugh Dickins 	int pgrescued = 0;
486189e004eaSLee Schermerhorn 	int i;
486289e004eaSLee Schermerhorn 
486364e3d12fSKuo-Hsin Yang 	for (i = 0; i < pvec->nr; i++) {
486464e3d12fSKuo-Hsin Yang 		struct page *page = pvec->pages[i];
48650de340cbSMatthew Wilcox (Oracle) 		struct folio *folio = page_folio(page);
48668d8869caSHugh Dickins 		int nr_pages;
486789e004eaSLee Schermerhorn 
48688d8869caSHugh Dickins 		if (PageTransTail(page))
48698d8869caSHugh Dickins 			continue;
48708d8869caSHugh Dickins 
48718d8869caSHugh Dickins 		nr_pages = thp_nr_pages(page);
48728d8869caSHugh Dickins 		pgscanned += nr_pages;
48738d8869caSHugh Dickins 
4874d25b5bd8SAlex Shi 		/* block memcg migration during page moving between lru */
4875d25b5bd8SAlex Shi 		if (!TestClearPageLRU(page))
4876d25b5bd8SAlex Shi 			continue;
4877d25b5bd8SAlex Shi 
48780de340cbSMatthew Wilcox (Oracle) 		lruvec = folio_lruvec_relock_irq(folio, lruvec);
4879d25b5bd8SAlex Shi 		if (page_evictable(page) && PageUnevictable(page)) {
488046ae6b2cSYu Zhao 			del_page_from_lru_list(page, lruvec);
488124513264SHugh Dickins 			ClearPageUnevictable(page);
48823a9c9788SYu Zhao 			add_page_to_lru_list(page, lruvec);
48838d8869caSHugh Dickins 			pgrescued += nr_pages;
488489e004eaSLee Schermerhorn 		}
4885d25b5bd8SAlex Shi 		SetPageLRU(page);
488689e004eaSLee Schermerhorn 	}
488724513264SHugh Dickins 
48886168d0daSAlex Shi 	if (lruvec) {
488924513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
489024513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
48916168d0daSAlex Shi 		unlock_page_lruvec_irq(lruvec);
4892d25b5bd8SAlex Shi 	} else if (pgscanned) {
4893d25b5bd8SAlex Shi 		count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
489424513264SHugh Dickins 	}
489585046579SHugh Dickins }
489664e3d12fSKuo-Hsin Yang EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
4897