xref: /openbmc/linux/mm/vmscan.c (revision ac35a490237446b71e3b4b782b1596967edd0aa8)
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>
2907f67a8dSMatthew Wilcox (Oracle) #include <linux/buffer_head.h>	/* for buffer_heads_over_limit */
301da177e4SLinus Torvalds #include <linux/mm_inline.h>
311da177e4SLinus Torvalds #include <linux/backing-dev.h>
321da177e4SLinus Torvalds #include <linux/rmap.h>
331da177e4SLinus Torvalds #include <linux/topology.h>
341da177e4SLinus Torvalds #include <linux/cpu.h>
351da177e4SLinus Torvalds #include <linux/cpuset.h>
363e7d3449SMel Gorman #include <linux/compaction.h>
371da177e4SLinus Torvalds #include <linux/notifier.h>
381da177e4SLinus Torvalds #include <linux/rwsem.h>
39248a0301SRafael J. Wysocki #include <linux/delay.h>
403218ae14SYasunori Goto #include <linux/kthread.h>
417dfb7103SNigel Cunningham #include <linux/freezer.h>
4266e1707bSBalbir Singh #include <linux/memcontrol.h>
4326aa2d19SDave Hansen #include <linux/migrate.h>
44873b4771SKeika Kobayashi #include <linux/delayacct.h>
45af936a16SLee Schermerhorn #include <linux/sysctl.h>
46929bea7cSKOSAKI Motohiro #include <linux/oom.h>
4764e3d12fSKuo-Hsin Yang #include <linux/pagevec.h>
48268bb0ceSLinus Torvalds #include <linux/prefetch.h>
49b1de0d13SMitchel Humpherys #include <linux/printk.h>
50f9fe48beSRoss Zwisler #include <linux/dax.h>
51eb414681SJohannes Weiner #include <linux/psi.h>
521da177e4SLinus Torvalds 
531da177e4SLinus Torvalds #include <asm/tlbflush.h>
541da177e4SLinus Torvalds #include <asm/div64.h>
551da177e4SLinus Torvalds 
561da177e4SLinus Torvalds #include <linux/swapops.h>
57117aad1eSRafael Aquini #include <linux/balloon_compaction.h>
58c574bbe9SHuang Ying #include <linux/sched/sysctl.h>
591da177e4SLinus Torvalds 
600f8053a5SNick Piggin #include "internal.h"
61014bb1deSNeilBrown #include "swap.h"
620f8053a5SNick Piggin 
6333906bc5SMel Gorman #define CREATE_TRACE_POINTS
6433906bc5SMel Gorman #include <trace/events/vmscan.h>
6533906bc5SMel Gorman 
661da177e4SLinus Torvalds struct scan_control {
6722fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6822fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
6922fba335SKOSAKI Motohiro 
70ee814fe2SJohannes Weiner 	/*
71ee814fe2SJohannes Weiner 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
72ee814fe2SJohannes Weiner 	 * are scanned.
73ee814fe2SJohannes Weiner 	 */
74ee814fe2SJohannes Weiner 	nodemask_t	*nodemask;
759e3b2f8cSKonstantin Khlebnikov 
765f53e762SKOSAKI Motohiro 	/*
77f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
78f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
79f16015fbSJohannes Weiner 	 */
80f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
8166e1707bSBalbir Singh 
827cf111bcSJohannes Weiner 	/*
837cf111bcSJohannes Weiner 	 * Scan pressure balancing between anon and file LRUs
847cf111bcSJohannes Weiner 	 */
857cf111bcSJohannes Weiner 	unsigned long	anon_cost;
867cf111bcSJohannes Weiner 	unsigned long	file_cost;
877cf111bcSJohannes Weiner 
88b91ac374SJohannes Weiner 	/* Can active pages be deactivated as part of reclaim? */
89b91ac374SJohannes Weiner #define DEACTIVATE_ANON 1
90b91ac374SJohannes Weiner #define DEACTIVATE_FILE 2
91b91ac374SJohannes Weiner 	unsigned int may_deactivate:2;
92b91ac374SJohannes Weiner 	unsigned int force_deactivate:1;
93b91ac374SJohannes Weiner 	unsigned int skipped_deactivate:1;
94b91ac374SJohannes Weiner 
951276ad68SJohannes Weiner 	/* Writepage batching in laptop mode; RECLAIM_WRITE */
96ee814fe2SJohannes Weiner 	unsigned int may_writepage:1;
97ee814fe2SJohannes Weiner 
98ee814fe2SJohannes Weiner 	/* Can mapped pages be reclaimed? */
99ee814fe2SJohannes Weiner 	unsigned int may_unmap:1;
100ee814fe2SJohannes Weiner 
101ee814fe2SJohannes Weiner 	/* Can pages be swapped as part of reclaim? */
102ee814fe2SJohannes Weiner 	unsigned int may_swap:1;
103ee814fe2SJohannes Weiner 
10473b73bacSYosry Ahmed 	/* Proactive reclaim invoked by userspace through memory.reclaim */
10573b73bacSYosry Ahmed 	unsigned int proactive:1;
10673b73bacSYosry Ahmed 
107d6622f63SYisheng Xie 	/*
108f56ce412SJohannes Weiner 	 * Cgroup memory below memory.low is protected as long as we
109f56ce412SJohannes Weiner 	 * don't threaten to OOM. If any cgroup is reclaimed at
110f56ce412SJohannes Weiner 	 * reduced force or passed over entirely due to its memory.low
111f56ce412SJohannes Weiner 	 * setting (memcg_low_skipped), and nothing is reclaimed as a
112f56ce412SJohannes Weiner 	 * result, then go back for one more cycle that reclaims the protected
113f56ce412SJohannes Weiner 	 * memory (memcg_low_reclaim) to avert OOM.
114d6622f63SYisheng Xie 	 */
115d6622f63SYisheng Xie 	unsigned int memcg_low_reclaim:1;
116d6622f63SYisheng Xie 	unsigned int memcg_low_skipped:1;
117241994edSJohannes Weiner 
118ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
119ee814fe2SJohannes Weiner 
120ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
121ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
122ee814fe2SJohannes Weiner 
123b91ac374SJohannes Weiner 	/* There is easily reclaimable cold cache in the current node */
124b91ac374SJohannes Weiner 	unsigned int cache_trim_mode:1;
125b91ac374SJohannes Weiner 
12653138ceaSJohannes Weiner 	/* The file pages on the current node are dangerously low */
12753138ceaSJohannes Weiner 	unsigned int file_is_tiny:1;
12853138ceaSJohannes Weiner 
12926aa2d19SDave Hansen 	/* Always discard instead of demoting to lower tier memory */
13026aa2d19SDave Hansen 	unsigned int no_demotion:1;
13126aa2d19SDave Hansen 
132bb451fdfSGreg Thelen 	/* Allocation order */
133bb451fdfSGreg Thelen 	s8 order;
134bb451fdfSGreg Thelen 
135bb451fdfSGreg Thelen 	/* Scan (total_size >> priority) pages at once */
136bb451fdfSGreg Thelen 	s8 priority;
137bb451fdfSGreg Thelen 
138bb451fdfSGreg Thelen 	/* The highest zone to isolate pages for reclaim from */
139bb451fdfSGreg Thelen 	s8 reclaim_idx;
140bb451fdfSGreg Thelen 
141bb451fdfSGreg Thelen 	/* This context's GFP mask */
142bb451fdfSGreg Thelen 	gfp_t gfp_mask;
143bb451fdfSGreg Thelen 
144ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
145ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
146ee814fe2SJohannes Weiner 
147ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
148ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
149d108c772SAndrey Ryabinin 
150d108c772SAndrey Ryabinin 	struct {
151d108c772SAndrey Ryabinin 		unsigned int dirty;
152d108c772SAndrey Ryabinin 		unsigned int unqueued_dirty;
153d108c772SAndrey Ryabinin 		unsigned int congested;
154d108c772SAndrey Ryabinin 		unsigned int writeback;
155d108c772SAndrey Ryabinin 		unsigned int immediate;
156d108c772SAndrey Ryabinin 		unsigned int file_taken;
157d108c772SAndrey Ryabinin 		unsigned int taken;
158d108c772SAndrey Ryabinin 	} nr;
159e5ca8071SYafang Shao 
160e5ca8071SYafang Shao 	/* for recording the reclaimed slab by now */
161e5ca8071SYafang Shao 	struct reclaim_state reclaim_state;
1621da177e4SLinus Torvalds };
1631da177e4SLinus Torvalds 
1641da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
165166e3d32SMatthew Wilcox (Oracle) #define prefetchw_prev_lru_folio(_folio, _base, _field)			\
1661da177e4SLinus Torvalds 	do {								\
167166e3d32SMatthew Wilcox (Oracle) 		if ((_folio)->lru.prev != _base) {			\
168166e3d32SMatthew Wilcox (Oracle) 			struct folio *prev;				\
1691da177e4SLinus Torvalds 									\
170166e3d32SMatthew Wilcox (Oracle) 			prev = lru_to_folio(&(_folio->lru));		\
1711da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1721da177e4SLinus Torvalds 		}							\
1731da177e4SLinus Torvalds 	} while (0)
1741da177e4SLinus Torvalds #else
175166e3d32SMatthew Wilcox (Oracle) #define prefetchw_prev_lru_folio(_folio, _base, _field) do { } while (0)
1761da177e4SLinus Torvalds #endif
1771da177e4SLinus Torvalds 
1781da177e4SLinus Torvalds /*
179c843966cSJohannes Weiner  * From 0 .. 200.  Higher means more swappy.
1801da177e4SLinus Torvalds  */
1811da177e4SLinus Torvalds int vm_swappiness = 60;
1821da177e4SLinus Torvalds 
1830a432dcbSYang Shi static void set_task_reclaim_state(struct task_struct *task,
1840a432dcbSYang Shi 				   struct reclaim_state *rs)
1850a432dcbSYang Shi {
1860a432dcbSYang Shi 	/* Check for an overwrite */
1870a432dcbSYang Shi 	WARN_ON_ONCE(rs && task->reclaim_state);
1880a432dcbSYang Shi 
1890a432dcbSYang Shi 	/* Check for the nulling of an already-nulled member */
1900a432dcbSYang Shi 	WARN_ON_ONCE(!rs && !task->reclaim_state);
1910a432dcbSYang Shi 
1920a432dcbSYang Shi 	task->reclaim_state = rs;
1930a432dcbSYang Shi }
1940a432dcbSYang Shi 
1955035ebc6SRoman Gushchin LIST_HEAD(shrinker_list);
1965035ebc6SRoman Gushchin DECLARE_RWSEM(shrinker_rwsem);
1971da177e4SLinus Torvalds 
1980a432dcbSYang Shi #ifdef CONFIG_MEMCG
199a2fb1261SYang Shi static int shrinker_nr_max;
2002bfd3637SYang Shi 
2013c6f17e6SYang Shi /* The shrinker_info is expanded in a batch of BITS_PER_LONG */
202a2fb1261SYang Shi static inline int shrinker_map_size(int nr_items)
203a2fb1261SYang Shi {
204a2fb1261SYang Shi 	return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
205a2fb1261SYang Shi }
2062bfd3637SYang Shi 
2073c6f17e6SYang Shi static inline int shrinker_defer_size(int nr_items)
2083c6f17e6SYang Shi {
2093c6f17e6SYang Shi 	return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
2103c6f17e6SYang Shi }
2113c6f17e6SYang Shi 
212468ab843SYang Shi static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
213468ab843SYang Shi 						     int nid)
214468ab843SYang Shi {
215468ab843SYang Shi 	return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
216468ab843SYang Shi 					 lockdep_is_held(&shrinker_rwsem));
217468ab843SYang Shi }
218468ab843SYang Shi 
219e4262c4fSYang Shi static int expand_one_shrinker_info(struct mem_cgroup *memcg,
2203c6f17e6SYang Shi 				    int map_size, int defer_size,
2213c6f17e6SYang Shi 				    int old_map_size, int old_defer_size)
2222bfd3637SYang Shi {
223e4262c4fSYang Shi 	struct shrinker_info *new, *old;
2242bfd3637SYang Shi 	struct mem_cgroup_per_node *pn;
2252bfd3637SYang Shi 	int nid;
2263c6f17e6SYang Shi 	int size = map_size + defer_size;
2272bfd3637SYang Shi 
2282bfd3637SYang Shi 	for_each_node(nid) {
2292bfd3637SYang Shi 		pn = memcg->nodeinfo[nid];
230468ab843SYang Shi 		old = shrinker_info_protected(memcg, nid);
2312bfd3637SYang Shi 		/* Not yet online memcg */
2322bfd3637SYang Shi 		if (!old)
2332bfd3637SYang Shi 			return 0;
2342bfd3637SYang Shi 
2352bfd3637SYang Shi 		new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
2362bfd3637SYang Shi 		if (!new)
2372bfd3637SYang Shi 			return -ENOMEM;
2382bfd3637SYang Shi 
2393c6f17e6SYang Shi 		new->nr_deferred = (atomic_long_t *)(new + 1);
2403c6f17e6SYang Shi 		new->map = (void *)new->nr_deferred + defer_size;
2413c6f17e6SYang Shi 
2423c6f17e6SYang Shi 		/* map: set all old bits, clear all new bits */
2433c6f17e6SYang Shi 		memset(new->map, (int)0xff, old_map_size);
2443c6f17e6SYang Shi 		memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
2453c6f17e6SYang Shi 		/* nr_deferred: copy old values, clear all new values */
2463c6f17e6SYang Shi 		memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
2473c6f17e6SYang Shi 		memset((void *)new->nr_deferred + old_defer_size, 0,
2483c6f17e6SYang Shi 		       defer_size - old_defer_size);
2492bfd3637SYang Shi 
250e4262c4fSYang Shi 		rcu_assign_pointer(pn->shrinker_info, new);
25172673e86SYang Shi 		kvfree_rcu(old, rcu);
2522bfd3637SYang Shi 	}
2532bfd3637SYang Shi 
2542bfd3637SYang Shi 	return 0;
2552bfd3637SYang Shi }
2562bfd3637SYang Shi 
257e4262c4fSYang Shi void free_shrinker_info(struct mem_cgroup *memcg)
2582bfd3637SYang Shi {
2592bfd3637SYang Shi 	struct mem_cgroup_per_node *pn;
260e4262c4fSYang Shi 	struct shrinker_info *info;
2612bfd3637SYang Shi 	int nid;
2622bfd3637SYang Shi 
2632bfd3637SYang Shi 	for_each_node(nid) {
2642bfd3637SYang Shi 		pn = memcg->nodeinfo[nid];
265e4262c4fSYang Shi 		info = rcu_dereference_protected(pn->shrinker_info, true);
266e4262c4fSYang Shi 		kvfree(info);
267e4262c4fSYang Shi 		rcu_assign_pointer(pn->shrinker_info, NULL);
2682bfd3637SYang Shi 	}
2692bfd3637SYang Shi }
2702bfd3637SYang Shi 
271e4262c4fSYang Shi int alloc_shrinker_info(struct mem_cgroup *memcg)
2722bfd3637SYang Shi {
273e4262c4fSYang Shi 	struct shrinker_info *info;
2742bfd3637SYang Shi 	int nid, size, ret = 0;
2753c6f17e6SYang Shi 	int map_size, defer_size = 0;
2762bfd3637SYang Shi 
277d27cf2aaSYang Shi 	down_write(&shrinker_rwsem);
2783c6f17e6SYang Shi 	map_size = shrinker_map_size(shrinker_nr_max);
2793c6f17e6SYang Shi 	defer_size = shrinker_defer_size(shrinker_nr_max);
2803c6f17e6SYang Shi 	size = map_size + defer_size;
2812bfd3637SYang Shi 	for_each_node(nid) {
282e4262c4fSYang Shi 		info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
283e4262c4fSYang Shi 		if (!info) {
284e4262c4fSYang Shi 			free_shrinker_info(memcg);
2852bfd3637SYang Shi 			ret = -ENOMEM;
2862bfd3637SYang Shi 			break;
2872bfd3637SYang Shi 		}
2883c6f17e6SYang Shi 		info->nr_deferred = (atomic_long_t *)(info + 1);
2893c6f17e6SYang Shi 		info->map = (void *)info->nr_deferred + defer_size;
290e4262c4fSYang Shi 		rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
2912bfd3637SYang Shi 	}
292d27cf2aaSYang Shi 	up_write(&shrinker_rwsem);
2932bfd3637SYang Shi 
2942bfd3637SYang Shi 	return ret;
2952bfd3637SYang Shi }
2962bfd3637SYang Shi 
2973c6f17e6SYang Shi static inline bool need_expand(int nr_max)
2983c6f17e6SYang Shi {
2993c6f17e6SYang Shi 	return round_up(nr_max, BITS_PER_LONG) >
3003c6f17e6SYang Shi 	       round_up(shrinker_nr_max, BITS_PER_LONG);
3013c6f17e6SYang Shi }
3023c6f17e6SYang Shi 
303e4262c4fSYang Shi static int expand_shrinker_info(int new_id)
3042bfd3637SYang Shi {
3053c6f17e6SYang Shi 	int ret = 0;
306a2fb1261SYang Shi 	int new_nr_max = new_id + 1;
3073c6f17e6SYang Shi 	int map_size, defer_size = 0;
3083c6f17e6SYang Shi 	int old_map_size, old_defer_size = 0;
3092bfd3637SYang Shi 	struct mem_cgroup *memcg;
3102bfd3637SYang Shi 
3113c6f17e6SYang Shi 	if (!need_expand(new_nr_max))
312a2fb1261SYang Shi 		goto out;
3132bfd3637SYang Shi 
3142bfd3637SYang Shi 	if (!root_mem_cgroup)
315d27cf2aaSYang Shi 		goto out;
316d27cf2aaSYang Shi 
317d27cf2aaSYang Shi 	lockdep_assert_held(&shrinker_rwsem);
3182bfd3637SYang Shi 
3193c6f17e6SYang Shi 	map_size = shrinker_map_size(new_nr_max);
3203c6f17e6SYang Shi 	defer_size = shrinker_defer_size(new_nr_max);
3213c6f17e6SYang Shi 	old_map_size = shrinker_map_size(shrinker_nr_max);
3223c6f17e6SYang Shi 	old_defer_size = shrinker_defer_size(shrinker_nr_max);
3233c6f17e6SYang Shi 
3242bfd3637SYang Shi 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3252bfd3637SYang Shi 	do {
3263c6f17e6SYang Shi 		ret = expand_one_shrinker_info(memcg, map_size, defer_size,
3273c6f17e6SYang Shi 					       old_map_size, old_defer_size);
3282bfd3637SYang Shi 		if (ret) {
3292bfd3637SYang Shi 			mem_cgroup_iter_break(NULL, memcg);
330d27cf2aaSYang Shi 			goto out;
3312bfd3637SYang Shi 		}
3322bfd3637SYang Shi 	} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
333d27cf2aaSYang Shi out:
3342bfd3637SYang Shi 	if (!ret)
335a2fb1261SYang Shi 		shrinker_nr_max = new_nr_max;
336d27cf2aaSYang Shi 
3372bfd3637SYang Shi 	return ret;
3382bfd3637SYang Shi }
3392bfd3637SYang Shi 
3402bfd3637SYang Shi void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
3412bfd3637SYang Shi {
3422bfd3637SYang Shi 	if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
343e4262c4fSYang Shi 		struct shrinker_info *info;
3442bfd3637SYang Shi 
3452bfd3637SYang Shi 		rcu_read_lock();
346e4262c4fSYang Shi 		info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
3472bfd3637SYang Shi 		/* Pairs with smp mb in shrink_slab() */
3482bfd3637SYang Shi 		smp_mb__before_atomic();
349e4262c4fSYang Shi 		set_bit(shrinker_id, info->map);
3502bfd3637SYang Shi 		rcu_read_unlock();
3512bfd3637SYang Shi 	}
3522bfd3637SYang Shi }
3532bfd3637SYang Shi 
354b4c2b231SKirill Tkhai static DEFINE_IDR(shrinker_idr);
355b4c2b231SKirill Tkhai 
356b4c2b231SKirill Tkhai static int prealloc_memcg_shrinker(struct shrinker *shrinker)
357b4c2b231SKirill Tkhai {
358b4c2b231SKirill Tkhai 	int id, ret = -ENOMEM;
359b4c2b231SKirill Tkhai 
360476b30a0SYang Shi 	if (mem_cgroup_disabled())
361476b30a0SYang Shi 		return -ENOSYS;
362476b30a0SYang Shi 
363b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
364b4c2b231SKirill Tkhai 	/* This may call shrinker, so it must use down_read_trylock() */
36541ca668aSYang Shi 	id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
366b4c2b231SKirill Tkhai 	if (id < 0)
367b4c2b231SKirill Tkhai 		goto unlock;
368b4c2b231SKirill Tkhai 
3690a4465d3SKirill Tkhai 	if (id >= shrinker_nr_max) {
370e4262c4fSYang Shi 		if (expand_shrinker_info(id)) {
3710a4465d3SKirill Tkhai 			idr_remove(&shrinker_idr, id);
3720a4465d3SKirill Tkhai 			goto unlock;
3730a4465d3SKirill Tkhai 		}
3740a4465d3SKirill Tkhai 	}
375b4c2b231SKirill Tkhai 	shrinker->id = id;
376b4c2b231SKirill Tkhai 	ret = 0;
377b4c2b231SKirill Tkhai unlock:
378b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
379b4c2b231SKirill Tkhai 	return ret;
380b4c2b231SKirill Tkhai }
381b4c2b231SKirill Tkhai 
382b4c2b231SKirill Tkhai static void unregister_memcg_shrinker(struct shrinker *shrinker)
383b4c2b231SKirill Tkhai {
384b4c2b231SKirill Tkhai 	int id = shrinker->id;
385b4c2b231SKirill Tkhai 
386b4c2b231SKirill Tkhai 	BUG_ON(id < 0);
387b4c2b231SKirill Tkhai 
38841ca668aSYang Shi 	lockdep_assert_held(&shrinker_rwsem);
38941ca668aSYang Shi 
390b4c2b231SKirill Tkhai 	idr_remove(&shrinker_idr, id);
391b4c2b231SKirill Tkhai }
392b4c2b231SKirill Tkhai 
39386750830SYang Shi static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
39486750830SYang Shi 				   struct mem_cgroup *memcg)
39586750830SYang Shi {
39686750830SYang Shi 	struct shrinker_info *info;
39786750830SYang Shi 
39886750830SYang Shi 	info = shrinker_info_protected(memcg, nid);
39986750830SYang Shi 	return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
40086750830SYang Shi }
40186750830SYang Shi 
40286750830SYang Shi static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
40386750830SYang Shi 				  struct mem_cgroup *memcg)
40486750830SYang Shi {
40586750830SYang Shi 	struct shrinker_info *info;
40686750830SYang Shi 
40786750830SYang Shi 	info = shrinker_info_protected(memcg, nid);
40886750830SYang Shi 	return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
40986750830SYang Shi }
41086750830SYang Shi 
411a178015cSYang Shi void reparent_shrinker_deferred(struct mem_cgroup *memcg)
412a178015cSYang Shi {
413a178015cSYang Shi 	int i, nid;
414a178015cSYang Shi 	long nr;
415a178015cSYang Shi 	struct mem_cgroup *parent;
416a178015cSYang Shi 	struct shrinker_info *child_info, *parent_info;
417a178015cSYang Shi 
418a178015cSYang Shi 	parent = parent_mem_cgroup(memcg);
419a178015cSYang Shi 	if (!parent)
420a178015cSYang Shi 		parent = root_mem_cgroup;
421a178015cSYang Shi 
422a178015cSYang Shi 	/* Prevent from concurrent shrinker_info expand */
423a178015cSYang Shi 	down_read(&shrinker_rwsem);
424a178015cSYang Shi 	for_each_node(nid) {
425a178015cSYang Shi 		child_info = shrinker_info_protected(memcg, nid);
426a178015cSYang Shi 		parent_info = shrinker_info_protected(parent, nid);
427a178015cSYang Shi 		for (i = 0; i < shrinker_nr_max; i++) {
428a178015cSYang Shi 			nr = atomic_long_read(&child_info->nr_deferred[i]);
429a178015cSYang Shi 			atomic_long_add(nr, &parent_info->nr_deferred[i]);
430a178015cSYang Shi 		}
431a178015cSYang Shi 	}
432a178015cSYang Shi 	up_read(&shrinker_rwsem);
433a178015cSYang Shi }
434a178015cSYang Shi 
435b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
43689b5fae5SJohannes Weiner {
437b5ead35eSJohannes Weiner 	return sc->target_mem_cgroup;
43889b5fae5SJohannes Weiner }
43997c9341fSTejun Heo 
44097c9341fSTejun Heo /**
441b5ead35eSJohannes Weiner  * writeback_throttling_sane - is the usual dirty throttling mechanism available?
44297c9341fSTejun Heo  * @sc: scan_control in question
44397c9341fSTejun Heo  *
44497c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
44597c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
44697c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
44797c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
44897c9341fSTejun Heo  * allocation and configurability.
44997c9341fSTejun Heo  *
45097c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
45197c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
45297c9341fSTejun Heo  */
453b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
45497c9341fSTejun Heo {
455b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
45697c9341fSTejun Heo 		return true;
45797c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
45869234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
45997c9341fSTejun Heo 		return true;
46097c9341fSTejun Heo #endif
46197c9341fSTejun Heo 	return false;
46297c9341fSTejun Heo }
46391a45470SKAMEZAWA Hiroyuki #else
4640a432dcbSYang Shi static int prealloc_memcg_shrinker(struct shrinker *shrinker)
4650a432dcbSYang Shi {
466476b30a0SYang Shi 	return -ENOSYS;
4670a432dcbSYang Shi }
4680a432dcbSYang Shi 
4690a432dcbSYang Shi static void unregister_memcg_shrinker(struct shrinker *shrinker)
4700a432dcbSYang Shi {
4710a432dcbSYang Shi }
4720a432dcbSYang Shi 
47386750830SYang Shi static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
47486750830SYang Shi 				   struct mem_cgroup *memcg)
47586750830SYang Shi {
47686750830SYang Shi 	return 0;
47786750830SYang Shi }
47886750830SYang Shi 
47986750830SYang Shi static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
48086750830SYang Shi 				  struct mem_cgroup *memcg)
48186750830SYang Shi {
48286750830SYang Shi 	return 0;
48386750830SYang Shi }
48486750830SYang Shi 
485b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
48689b5fae5SJohannes Weiner {
487b5ead35eSJohannes Weiner 	return false;
48889b5fae5SJohannes Weiner }
48997c9341fSTejun Heo 
490b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
49197c9341fSTejun Heo {
49297c9341fSTejun Heo 	return true;
49397c9341fSTejun Heo }
49491a45470SKAMEZAWA Hiroyuki #endif
49591a45470SKAMEZAWA Hiroyuki 
49686750830SYang Shi static long xchg_nr_deferred(struct shrinker *shrinker,
49786750830SYang Shi 			     struct shrink_control *sc)
49886750830SYang Shi {
49986750830SYang Shi 	int nid = sc->nid;
50086750830SYang Shi 
50186750830SYang Shi 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
50286750830SYang Shi 		nid = 0;
50386750830SYang Shi 
50486750830SYang Shi 	if (sc->memcg &&
50586750830SYang Shi 	    (shrinker->flags & SHRINKER_MEMCG_AWARE))
50686750830SYang Shi 		return xchg_nr_deferred_memcg(nid, shrinker,
50786750830SYang Shi 					      sc->memcg);
50886750830SYang Shi 
50986750830SYang Shi 	return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
51086750830SYang Shi }
51186750830SYang Shi 
51286750830SYang Shi 
51386750830SYang Shi static long add_nr_deferred(long nr, struct shrinker *shrinker,
51486750830SYang Shi 			    struct shrink_control *sc)
51586750830SYang Shi {
51686750830SYang Shi 	int nid = sc->nid;
51786750830SYang Shi 
51886750830SYang Shi 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
51986750830SYang Shi 		nid = 0;
52086750830SYang Shi 
52186750830SYang Shi 	if (sc->memcg &&
52286750830SYang Shi 	    (shrinker->flags & SHRINKER_MEMCG_AWARE))
52386750830SYang Shi 		return add_nr_deferred_memcg(nr, nid, shrinker,
52486750830SYang Shi 					     sc->memcg);
52586750830SYang Shi 
52686750830SYang Shi 	return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
52786750830SYang Shi }
52886750830SYang Shi 
52926aa2d19SDave Hansen static bool can_demote(int nid, struct scan_control *sc)
53026aa2d19SDave Hansen {
53120b51af1SHuang Ying 	if (!numa_demotion_enabled)
53220b51af1SHuang Ying 		return false;
5333f1509c5SJohannes Weiner 	if (sc && sc->no_demotion)
53426aa2d19SDave Hansen 		return false;
53526aa2d19SDave Hansen 	if (next_demotion_node(nid) == NUMA_NO_NODE)
53626aa2d19SDave Hansen 		return false;
53726aa2d19SDave Hansen 
53820b51af1SHuang Ying 	return true;
53926aa2d19SDave Hansen }
54026aa2d19SDave Hansen 
541a2a36488SKeith Busch static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
542a2a36488SKeith Busch 					  int nid,
543a2a36488SKeith Busch 					  struct scan_control *sc)
544a2a36488SKeith Busch {
545a2a36488SKeith Busch 	if (memcg == NULL) {
546a2a36488SKeith Busch 		/*
547a2a36488SKeith Busch 		 * For non-memcg reclaim, is there
548a2a36488SKeith Busch 		 * space in any swap device?
549a2a36488SKeith Busch 		 */
550a2a36488SKeith Busch 		if (get_nr_swap_pages() > 0)
551a2a36488SKeith Busch 			return true;
552a2a36488SKeith Busch 	} else {
553a2a36488SKeith Busch 		/* Is the memcg below its swap limit? */
554a2a36488SKeith Busch 		if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
555a2a36488SKeith Busch 			return true;
556a2a36488SKeith Busch 	}
557a2a36488SKeith Busch 
558a2a36488SKeith Busch 	/*
559a2a36488SKeith Busch 	 * The page can not be swapped.
560a2a36488SKeith Busch 	 *
561a2a36488SKeith Busch 	 * Can it be reclaimed from this node via demotion?
562a2a36488SKeith Busch 	 */
563a2a36488SKeith Busch 	return can_demote(nid, sc);
564a2a36488SKeith Busch }
565a2a36488SKeith Busch 
5665a1c84b4SMel Gorman /*
5675a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
5685a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
5695a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
5705a1c84b4SMel Gorman  */
5715a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
5725a1c84b4SMel Gorman {
5735a1c84b4SMel Gorman 	unsigned long nr;
5745a1c84b4SMel Gorman 
5755a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
5765a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
577a2a36488SKeith Busch 	if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
5785a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
5795a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
5805a1c84b4SMel Gorman 
5815a1c84b4SMel Gorman 	return nr;
5825a1c84b4SMel Gorman }
5835a1c84b4SMel Gorman 
584fd538803SMichal Hocko /**
585fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
586fd538803SMichal Hocko  * @lruvec: lru vector
587fd538803SMichal Hocko  * @lru: lru to use
5888b3a899aSWei Yang  * @zone_idx: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list)
589fd538803SMichal Hocko  */
5902091339dSYu Zhao static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
5912091339dSYu Zhao 				     int zone_idx)
592c9f299d9SKOSAKI Motohiro {
593de3b0150SJohannes Weiner 	unsigned long size = 0;
594fd538803SMichal Hocko 	int zid;
595a3d8e054SKOSAKI Motohiro 
5968b3a899aSWei Yang 	for (zid = 0; zid <= zone_idx; zid++) {
597fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
598fd538803SMichal Hocko 
599fd538803SMichal Hocko 		if (!managed_zone(zone))
600fd538803SMichal Hocko 			continue;
601fd538803SMichal Hocko 
602fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
603de3b0150SJohannes Weiner 			size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
604fd538803SMichal Hocko 		else
605de3b0150SJohannes Weiner 			size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
606c9f299d9SKOSAKI Motohiro 	}
607de3b0150SJohannes Weiner 	return size;
608b4536f0cSMichal Hocko }
609b4536f0cSMichal Hocko 
6101da177e4SLinus Torvalds /*
6111d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
6121da177e4SLinus Torvalds  */
613e33c267aSRoman Gushchin static int __prealloc_shrinker(struct shrinker *shrinker)
6141da177e4SLinus Torvalds {
615476b30a0SYang Shi 	unsigned int size;
616476b30a0SYang Shi 	int err;
6171d3d4437SGlauber Costa 
618476b30a0SYang Shi 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
619476b30a0SYang Shi 		err = prealloc_memcg_shrinker(shrinker);
620476b30a0SYang Shi 		if (err != -ENOSYS)
621476b30a0SYang Shi 			return err;
622476b30a0SYang Shi 
623476b30a0SYang Shi 		shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
624476b30a0SYang Shi 	}
625476b30a0SYang Shi 
626476b30a0SYang Shi 	size = sizeof(*shrinker->nr_deferred);
6271d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
6281d3d4437SGlauber Costa 		size *= nr_node_ids;
6291d3d4437SGlauber Costa 
6301d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
6311d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
6321d3d4437SGlauber Costa 		return -ENOMEM;
633b4c2b231SKirill Tkhai 
6348e04944fSTetsuo Handa 	return 0;
6358e04944fSTetsuo Handa }
6361d3d4437SGlauber Costa 
637e33c267aSRoman Gushchin #ifdef CONFIG_SHRINKER_DEBUG
638e33c267aSRoman Gushchin int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...)
639e33c267aSRoman Gushchin {
640e33c267aSRoman Gushchin 	va_list ap;
641e33c267aSRoman Gushchin 	int err;
642e33c267aSRoman Gushchin 
643e33c267aSRoman Gushchin 	va_start(ap, fmt);
644e33c267aSRoman Gushchin 	shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
645e33c267aSRoman Gushchin 	va_end(ap);
646e33c267aSRoman Gushchin 	if (!shrinker->name)
647e33c267aSRoman Gushchin 		return -ENOMEM;
648e33c267aSRoman Gushchin 
649e33c267aSRoman Gushchin 	err = __prealloc_shrinker(shrinker);
65014773bfaSTetsuo Handa 	if (err) {
651e33c267aSRoman Gushchin 		kfree_const(shrinker->name);
65214773bfaSTetsuo Handa 		shrinker->name = NULL;
65314773bfaSTetsuo Handa 	}
654e33c267aSRoman Gushchin 
655e33c267aSRoman Gushchin 	return err;
656e33c267aSRoman Gushchin }
657e33c267aSRoman Gushchin #else
658e33c267aSRoman Gushchin int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...)
659e33c267aSRoman Gushchin {
660e33c267aSRoman Gushchin 	return __prealloc_shrinker(shrinker);
661e33c267aSRoman Gushchin }
662e33c267aSRoman Gushchin #endif
663e33c267aSRoman Gushchin 
6648e04944fSTetsuo Handa void free_prealloced_shrinker(struct shrinker *shrinker)
6658e04944fSTetsuo Handa {
666e33c267aSRoman Gushchin #ifdef CONFIG_SHRINKER_DEBUG
667e33c267aSRoman Gushchin 	kfree_const(shrinker->name);
66814773bfaSTetsuo Handa 	shrinker->name = NULL;
669e33c267aSRoman Gushchin #endif
67041ca668aSYang Shi 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
67141ca668aSYang Shi 		down_write(&shrinker_rwsem);
672b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
67341ca668aSYang Shi 		up_write(&shrinker_rwsem);
674476b30a0SYang Shi 		return;
67541ca668aSYang Shi 	}
676b4c2b231SKirill Tkhai 
6778e04944fSTetsuo Handa 	kfree(shrinker->nr_deferred);
6788e04944fSTetsuo Handa 	shrinker->nr_deferred = NULL;
6798e04944fSTetsuo Handa }
6808e04944fSTetsuo Handa 
6818e04944fSTetsuo Handa void register_shrinker_prepared(struct shrinker *shrinker)
6828e04944fSTetsuo Handa {
6831da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
6841da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
68541ca668aSYang Shi 	shrinker->flags |= SHRINKER_REGISTERED;
6865035ebc6SRoman Gushchin 	shrinker_debugfs_add(shrinker);
6871da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
6888e04944fSTetsuo Handa }
6898e04944fSTetsuo Handa 
690e33c267aSRoman Gushchin static int __register_shrinker(struct shrinker *shrinker)
6918e04944fSTetsuo Handa {
692e33c267aSRoman Gushchin 	int err = __prealloc_shrinker(shrinker);
6938e04944fSTetsuo Handa 
6948e04944fSTetsuo Handa 	if (err)
6958e04944fSTetsuo Handa 		return err;
6968e04944fSTetsuo Handa 	register_shrinker_prepared(shrinker);
6971d3d4437SGlauber Costa 	return 0;
6981da177e4SLinus Torvalds }
699e33c267aSRoman Gushchin 
700e33c267aSRoman Gushchin #ifdef CONFIG_SHRINKER_DEBUG
701e33c267aSRoman Gushchin int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
702e33c267aSRoman Gushchin {
703e33c267aSRoman Gushchin 	va_list ap;
704e33c267aSRoman Gushchin 	int err;
705e33c267aSRoman Gushchin 
706e33c267aSRoman Gushchin 	va_start(ap, fmt);
707e33c267aSRoman Gushchin 	shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
708e33c267aSRoman Gushchin 	va_end(ap);
709e33c267aSRoman Gushchin 	if (!shrinker->name)
710e33c267aSRoman Gushchin 		return -ENOMEM;
711e33c267aSRoman Gushchin 
712e33c267aSRoman Gushchin 	err = __register_shrinker(shrinker);
71314773bfaSTetsuo Handa 	if (err) {
714e33c267aSRoman Gushchin 		kfree_const(shrinker->name);
71514773bfaSTetsuo Handa 		shrinker->name = NULL;
71614773bfaSTetsuo Handa 	}
717e33c267aSRoman Gushchin 	return err;
718e33c267aSRoman Gushchin }
719e33c267aSRoman Gushchin #else
720e33c267aSRoman Gushchin int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
721e33c267aSRoman Gushchin {
722e33c267aSRoman Gushchin 	return __register_shrinker(shrinker);
723e33c267aSRoman Gushchin }
724e33c267aSRoman Gushchin #endif
7258e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
7261da177e4SLinus Torvalds 
7271da177e4SLinus Torvalds /*
7281da177e4SLinus Torvalds  * Remove one
7291da177e4SLinus Torvalds  */
7308e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
7311da177e4SLinus Torvalds {
73241ca668aSYang Shi 	if (!(shrinker->flags & SHRINKER_REGISTERED))
733bb422a73STetsuo Handa 		return;
73441ca668aSYang Shi 
7351da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
7361da177e4SLinus Torvalds 	list_del(&shrinker->list);
73741ca668aSYang Shi 	shrinker->flags &= ~SHRINKER_REGISTERED;
73841ca668aSYang Shi 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
73941ca668aSYang Shi 		unregister_memcg_shrinker(shrinker);
7405035ebc6SRoman Gushchin 	shrinker_debugfs_remove(shrinker);
7411da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
74241ca668aSYang Shi 
743ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
744bb422a73STetsuo Handa 	shrinker->nr_deferred = NULL;
7451da177e4SLinus Torvalds }
7468e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
7471da177e4SLinus Torvalds 
748880121beSChristian König /**
749880121beSChristian König  * synchronize_shrinkers - Wait for all running shrinkers to complete.
750880121beSChristian König  *
751880121beSChristian König  * This is equivalent to calling unregister_shrink() and register_shrinker(),
752880121beSChristian König  * but atomically and with less overhead. This is useful to guarantee that all
753880121beSChristian König  * shrinker invocations have seen an update, before freeing memory, similar to
754880121beSChristian König  * rcu.
755880121beSChristian König  */
756880121beSChristian König void synchronize_shrinkers(void)
757880121beSChristian König {
758880121beSChristian König 	down_write(&shrinker_rwsem);
759880121beSChristian König 	up_write(&shrinker_rwsem);
760880121beSChristian König }
761880121beSChristian König EXPORT_SYMBOL(synchronize_shrinkers);
762880121beSChristian König 
7631da177e4SLinus Torvalds #define SHRINK_BATCH 128
7641d3d4437SGlauber Costa 
765cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
7669092c71bSJosef Bacik 				    struct shrinker *shrinker, int priority)
7671da177e4SLinus Torvalds {
76824f7c6b9SDave Chinner 	unsigned long freed = 0;
7691da177e4SLinus Torvalds 	unsigned long long delta;
770635697c6SKonstantin Khlebnikov 	long total_scan;
771d5bc5fd3SVladimir Davydov 	long freeable;
772acf92b48SDave Chinner 	long nr;
773acf92b48SDave Chinner 	long new_nr;
774e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
775e9299f50SDave Chinner 					  : SHRINK_BATCH;
7765f33a080SShaohua Li 	long scanned = 0, next_deferred;
7771da177e4SLinus Torvalds 
778d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
7799b996468SKirill Tkhai 	if (freeable == 0 || freeable == SHRINK_EMPTY)
7809b996468SKirill Tkhai 		return freeable;
781635697c6SKonstantin Khlebnikov 
782acf92b48SDave Chinner 	/*
783acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
784acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
785acf92b48SDave Chinner 	 * don't also do this scanning work.
786acf92b48SDave Chinner 	 */
78786750830SYang Shi 	nr = xchg_nr_deferred(shrinker, shrinkctl);
788acf92b48SDave Chinner 
7894b85afbdSJohannes Weiner 	if (shrinker->seeks) {
7909092c71bSJosef Bacik 		delta = freeable >> priority;
7919092c71bSJosef Bacik 		delta *= 4;
7929092c71bSJosef Bacik 		do_div(delta, shrinker->seeks);
7934b85afbdSJohannes Weiner 	} else {
7944b85afbdSJohannes Weiner 		/*
7954b85afbdSJohannes Weiner 		 * These objects don't require any IO to create. Trim
7964b85afbdSJohannes Weiner 		 * them aggressively under memory pressure to keep
7974b85afbdSJohannes Weiner 		 * them from causing refetches in the IO caches.
7984b85afbdSJohannes Weiner 		 */
7994b85afbdSJohannes Weiner 		delta = freeable / 2;
8004b85afbdSJohannes Weiner 	}
801172b06c3SRoman Gushchin 
80218bb473eSYang Shi 	total_scan = nr >> priority;
803acf92b48SDave Chinner 	total_scan += delta;
80418bb473eSYang Shi 	total_scan = min(total_scan, (2 * freeable));
8051da177e4SLinus Torvalds 
80624f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
8079092c71bSJosef Bacik 				   freeable, delta, total_scan, priority);
80809576073SDave Chinner 
8090b1fb40aSVladimir Davydov 	/*
8100b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
8110b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
8120b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
8130b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
8140b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
8150b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
8160b1fb40aSVladimir Davydov 	 * batch_size.
8170b1fb40aSVladimir Davydov 	 *
8180b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
8190b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
820d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
8210b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
8220b1fb40aSVladimir Davydov 	 * possible.
8230b1fb40aSVladimir Davydov 	 */
8240b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
825d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
82624f7c6b9SDave Chinner 		unsigned long ret;
8270b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
8281da177e4SLinus Torvalds 
8290b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
830d460acb5SChris Wilson 		shrinkctl->nr_scanned = nr_to_scan;
83124f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
83224f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
8331da177e4SLinus Torvalds 			break;
83424f7c6b9SDave Chinner 		freed += ret;
83524f7c6b9SDave Chinner 
836d460acb5SChris Wilson 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
837d460acb5SChris Wilson 		total_scan -= shrinkctl->nr_scanned;
838d460acb5SChris Wilson 		scanned += shrinkctl->nr_scanned;
8391da177e4SLinus Torvalds 
8401da177e4SLinus Torvalds 		cond_resched();
8411da177e4SLinus Torvalds 	}
8421da177e4SLinus Torvalds 
84318bb473eSYang Shi 	/*
84418bb473eSYang Shi 	 * The deferred work is increased by any new work (delta) that wasn't
84518bb473eSYang Shi 	 * done, decreased by old deferred work that was done now.
84618bb473eSYang Shi 	 *
84718bb473eSYang Shi 	 * And it is capped to two times of the freeable items.
84818bb473eSYang Shi 	 */
84918bb473eSYang Shi 	next_deferred = max_t(long, (nr + delta - scanned), 0);
85018bb473eSYang Shi 	next_deferred = min(next_deferred, (2 * freeable));
85118bb473eSYang Shi 
852acf92b48SDave Chinner 	/*
853acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
85486750830SYang Shi 	 * manner that handles concurrent updates.
855acf92b48SDave Chinner 	 */
85686750830SYang Shi 	new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
857acf92b48SDave Chinner 
8588efb4b59SYang Shi 	trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
8591d3d4437SGlauber Costa 	return freed;
8601d3d4437SGlauber Costa }
8611d3d4437SGlauber Costa 
8620a432dcbSYang Shi #ifdef CONFIG_MEMCG
863b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
864b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
865b0dedc49SKirill Tkhai {
866e4262c4fSYang Shi 	struct shrinker_info *info;
867b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
868b8e57efaSKirill Tkhai 	int i;
869b0dedc49SKirill Tkhai 
8700a432dcbSYang Shi 	if (!mem_cgroup_online(memcg))
871b0dedc49SKirill Tkhai 		return 0;
872b0dedc49SKirill Tkhai 
873b0dedc49SKirill Tkhai 	if (!down_read_trylock(&shrinker_rwsem))
874b0dedc49SKirill Tkhai 		return 0;
875b0dedc49SKirill Tkhai 
876468ab843SYang Shi 	info = shrinker_info_protected(memcg, nid);
877e4262c4fSYang Shi 	if (unlikely(!info))
878b0dedc49SKirill Tkhai 		goto unlock;
879b0dedc49SKirill Tkhai 
880e4262c4fSYang Shi 	for_each_set_bit(i, info->map, shrinker_nr_max) {
881b0dedc49SKirill Tkhai 		struct shrink_control sc = {
882b0dedc49SKirill Tkhai 			.gfp_mask = gfp_mask,
883b0dedc49SKirill Tkhai 			.nid = nid,
884b0dedc49SKirill Tkhai 			.memcg = memcg,
885b0dedc49SKirill Tkhai 		};
886b0dedc49SKirill Tkhai 		struct shrinker *shrinker;
887b0dedc49SKirill Tkhai 
888b0dedc49SKirill Tkhai 		shrinker = idr_find(&shrinker_idr, i);
88941ca668aSYang Shi 		if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
8907e010df5SKirill Tkhai 			if (!shrinker)
891e4262c4fSYang Shi 				clear_bit(i, info->map);
892b0dedc49SKirill Tkhai 			continue;
893b0dedc49SKirill Tkhai 		}
894b0dedc49SKirill Tkhai 
8950a432dcbSYang Shi 		/* Call non-slab shrinkers even though kmem is disabled */
8960a432dcbSYang Shi 		if (!memcg_kmem_enabled() &&
8970a432dcbSYang Shi 		    !(shrinker->flags & SHRINKER_NONSLAB))
8980a432dcbSYang Shi 			continue;
8990a432dcbSYang Shi 
900b0dedc49SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
901f90280d6SKirill Tkhai 		if (ret == SHRINK_EMPTY) {
902e4262c4fSYang Shi 			clear_bit(i, info->map);
903f90280d6SKirill Tkhai 			/*
904f90280d6SKirill Tkhai 			 * After the shrinker reported that it had no objects to
905f90280d6SKirill Tkhai 			 * free, but before we cleared the corresponding bit in
906f90280d6SKirill Tkhai 			 * the memcg shrinker map, a new object might have been
907f90280d6SKirill Tkhai 			 * added. To make sure, we have the bit set in this
908f90280d6SKirill Tkhai 			 * case, we invoke the shrinker one more time and reset
909f90280d6SKirill Tkhai 			 * the bit if it reports that it is not empty anymore.
910f90280d6SKirill Tkhai 			 * The memory barrier here pairs with the barrier in
9112bfd3637SYang Shi 			 * set_shrinker_bit():
912f90280d6SKirill Tkhai 			 *
913f90280d6SKirill Tkhai 			 * list_lru_add()     shrink_slab_memcg()
914f90280d6SKirill Tkhai 			 *   list_add_tail()    clear_bit()
915f90280d6SKirill Tkhai 			 *   <MB>               <MB>
916f90280d6SKirill Tkhai 			 *   set_bit()          do_shrink_slab()
917f90280d6SKirill Tkhai 			 */
918f90280d6SKirill Tkhai 			smp_mb__after_atomic();
919f90280d6SKirill Tkhai 			ret = do_shrink_slab(&sc, shrinker, priority);
9209b996468SKirill Tkhai 			if (ret == SHRINK_EMPTY)
9219b996468SKirill Tkhai 				ret = 0;
922f90280d6SKirill Tkhai 			else
9232bfd3637SYang Shi 				set_shrinker_bit(memcg, nid, i);
924f90280d6SKirill Tkhai 		}
925b0dedc49SKirill Tkhai 		freed += ret;
926b0dedc49SKirill Tkhai 
927b0dedc49SKirill Tkhai 		if (rwsem_is_contended(&shrinker_rwsem)) {
928b0dedc49SKirill Tkhai 			freed = freed ? : 1;
929b0dedc49SKirill Tkhai 			break;
930b0dedc49SKirill Tkhai 		}
931b0dedc49SKirill Tkhai 	}
932b0dedc49SKirill Tkhai unlock:
933b0dedc49SKirill Tkhai 	up_read(&shrinker_rwsem);
934b0dedc49SKirill Tkhai 	return freed;
935b0dedc49SKirill Tkhai }
9360a432dcbSYang Shi #else /* CONFIG_MEMCG */
937b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
938b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
939b0dedc49SKirill Tkhai {
940b0dedc49SKirill Tkhai 	return 0;
941b0dedc49SKirill Tkhai }
9420a432dcbSYang Shi #endif /* CONFIG_MEMCG */
943b0dedc49SKirill Tkhai 
9446b4f7799SJohannes Weiner /**
945cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
9466b4f7799SJohannes Weiner  * @gfp_mask: allocation context
9476b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
948cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
9499092c71bSJosef Bacik  * @priority: the reclaim priority
9501d3d4437SGlauber Costa  *
9516b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
9521d3d4437SGlauber Costa  *
9536b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
9546b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
9551d3d4437SGlauber Costa  *
956aeed1d32SVladimir Davydov  * @memcg specifies the memory cgroup to target. Unaware shrinkers
957aeed1d32SVladimir Davydov  * are called only if it is the root cgroup.
958cb731d6cSVladimir Davydov  *
9599092c71bSJosef Bacik  * @priority is sc->priority, we take the number of objects and >> by priority
9609092c71bSJosef Bacik  * in order to get the scan target.
9611d3d4437SGlauber Costa  *
9626b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
9631d3d4437SGlauber Costa  */
964cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
965cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
9669092c71bSJosef Bacik 				 int priority)
9671d3d4437SGlauber Costa {
968b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
9691d3d4437SGlauber Costa 	struct shrinker *shrinker;
9701d3d4437SGlauber Costa 
971fa1e512fSYang Shi 	/*
972fa1e512fSYang Shi 	 * The root memcg might be allocated even though memcg is disabled
973fa1e512fSYang Shi 	 * via "cgroup_disable=memory" boot parameter.  This could make
974fa1e512fSYang Shi 	 * mem_cgroup_is_root() return false, then just run memcg slab
975fa1e512fSYang Shi 	 * shrink, but skip global shrink.  This may result in premature
976fa1e512fSYang Shi 	 * oom.
977fa1e512fSYang Shi 	 */
978fa1e512fSYang Shi 	if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
979b0dedc49SKirill Tkhai 		return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
980cb731d6cSVladimir Davydov 
981e830c63aSTetsuo Handa 	if (!down_read_trylock(&shrinker_rwsem))
9821d3d4437SGlauber Costa 		goto out;
9831d3d4437SGlauber Costa 
9841d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
9856b4f7799SJohannes Weiner 		struct shrink_control sc = {
9866b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
9876b4f7799SJohannes Weiner 			.nid = nid,
988cb731d6cSVladimir Davydov 			.memcg = memcg,
9896b4f7799SJohannes Weiner 		};
9906b4f7799SJohannes Weiner 
9919b996468SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
9929b996468SKirill Tkhai 		if (ret == SHRINK_EMPTY)
9939b996468SKirill Tkhai 			ret = 0;
9949b996468SKirill Tkhai 		freed += ret;
995e496612cSMinchan Kim 		/*
996e496612cSMinchan Kim 		 * Bail out if someone want to register a new shrinker to
99755b65a57SEthon Paul 		 * prevent the registration from being stalled for long periods
998e496612cSMinchan Kim 		 * by parallel ongoing shrinking.
999e496612cSMinchan Kim 		 */
1000e496612cSMinchan Kim 		if (rwsem_is_contended(&shrinker_rwsem)) {
1001e496612cSMinchan Kim 			freed = freed ? : 1;
1002e496612cSMinchan Kim 			break;
1003e496612cSMinchan Kim 		}
1004ec97097bSVladimir Davydov 	}
10051d3d4437SGlauber Costa 
10061da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
1007f06590bdSMinchan Kim out:
1008f06590bdSMinchan Kim 	cond_resched();
100924f7c6b9SDave Chinner 	return freed;
10101da177e4SLinus Torvalds }
10111da177e4SLinus Torvalds 
1012e4b424b7SGang Li static void drop_slab_node(int nid)
1013cb731d6cSVladimir Davydov {
1014cb731d6cSVladimir Davydov 	unsigned long freed;
10151399af7eSVlastimil Babka 	int shift = 0;
1016cb731d6cSVladimir Davydov 
1017cb731d6cSVladimir Davydov 	do {
1018cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
1019cb731d6cSVladimir Davydov 
1020069c411dSChunxin Zang 		if (fatal_signal_pending(current))
1021069c411dSChunxin Zang 			return;
1022069c411dSChunxin Zang 
1023cb731d6cSVladimir Davydov 		freed = 0;
1024aeed1d32SVladimir Davydov 		memcg = mem_cgroup_iter(NULL, NULL, NULL);
1025cb731d6cSVladimir Davydov 		do {
10269092c71bSJosef Bacik 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
1027cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
10281399af7eSVlastimil Babka 	} while ((freed >> shift++) > 1);
1029cb731d6cSVladimir Davydov }
1030cb731d6cSVladimir Davydov 
1031cb731d6cSVladimir Davydov void drop_slab(void)
1032cb731d6cSVladimir Davydov {
1033cb731d6cSVladimir Davydov 	int nid;
1034cb731d6cSVladimir Davydov 
1035cb731d6cSVladimir Davydov 	for_each_online_node(nid)
1036cb731d6cSVladimir Davydov 		drop_slab_node(nid);
1037cb731d6cSVladimir Davydov }
1038cb731d6cSVladimir Davydov 
1039e0cd5e7fSMatthew Wilcox (Oracle) static inline int is_page_cache_freeable(struct folio *folio)
10401da177e4SLinus Torvalds {
1041ceddc3a5SJohannes Weiner 	/*
1042ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
104367891fffSMatthew Wilcox 	 * that isolated the page, the page cache and optional buffer
104467891fffSMatthew Wilcox 	 * heads at page->private.
1045ceddc3a5SJohannes Weiner 	 */
1046e0cd5e7fSMatthew Wilcox (Oracle) 	return folio_ref_count(folio) - folio_test_private(folio) ==
1047e0cd5e7fSMatthew Wilcox (Oracle) 		1 + folio_nr_pages(folio);
10481da177e4SLinus Torvalds }
10491da177e4SLinus Torvalds 
10501da177e4SLinus Torvalds /*
1051e0cd5e7fSMatthew Wilcox (Oracle)  * We detected a synchronous write error writing a folio out.  Probably
10521da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
10531da177e4SLinus Torvalds  * fsync(), msync() or close().
10541da177e4SLinus Torvalds  *
10551da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
1056e0cd5e7fSMatthew Wilcox (Oracle)  * prevents it from being freed up.  But we have a ref on the folio and once
1057e0cd5e7fSMatthew Wilcox (Oracle)  * that folio is locked, the mapping is pinned.
10581da177e4SLinus Torvalds  *
1059e0cd5e7fSMatthew Wilcox (Oracle)  * We're allowed to run sleeping folio_lock() here because we know the caller has
10601da177e4SLinus Torvalds  * __GFP_FS.
10611da177e4SLinus Torvalds  */
10621da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
1063e0cd5e7fSMatthew Wilcox (Oracle) 				struct folio *folio, int error)
10641da177e4SLinus Torvalds {
1065e0cd5e7fSMatthew Wilcox (Oracle) 	folio_lock(folio);
1066e0cd5e7fSMatthew Wilcox (Oracle) 	if (folio_mapping(folio) == mapping)
10673e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
1068e0cd5e7fSMatthew Wilcox (Oracle) 	folio_unlock(folio);
10691da177e4SLinus Torvalds }
10701da177e4SLinus Torvalds 
10711b4e3f26SMel Gorman static bool skip_throttle_noprogress(pg_data_t *pgdat)
10721b4e3f26SMel Gorman {
10731b4e3f26SMel Gorman 	int reclaimable = 0, write_pending = 0;
10741b4e3f26SMel Gorman 	int i;
10751b4e3f26SMel Gorman 
10761b4e3f26SMel Gorman 	/*
10771b4e3f26SMel Gorman 	 * If kswapd is disabled, reschedule if necessary but do not
10781b4e3f26SMel Gorman 	 * throttle as the system is likely near OOM.
10791b4e3f26SMel Gorman 	 */
10801b4e3f26SMel Gorman 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
10811b4e3f26SMel Gorman 		return true;
10821b4e3f26SMel Gorman 
10831b4e3f26SMel Gorman 	/*
10841b4e3f26SMel Gorman 	 * If there are a lot of dirty/writeback pages then do not
10851b4e3f26SMel Gorman 	 * throttle as throttling will occur when the pages cycle
10861b4e3f26SMel Gorman 	 * towards the end of the LRU if still under writeback.
10871b4e3f26SMel Gorman 	 */
10881b4e3f26SMel Gorman 	for (i = 0; i < MAX_NR_ZONES; i++) {
10891b4e3f26SMel Gorman 		struct zone *zone = pgdat->node_zones + i;
10901b4e3f26SMel Gorman 
109136c26128SWei Yang 		if (!managed_zone(zone))
10921b4e3f26SMel Gorman 			continue;
10931b4e3f26SMel Gorman 
10941b4e3f26SMel Gorman 		reclaimable += zone_reclaimable_pages(zone);
10951b4e3f26SMel Gorman 		write_pending += zone_page_state_snapshot(zone,
10961b4e3f26SMel Gorman 						  NR_ZONE_WRITE_PENDING);
10971b4e3f26SMel Gorman 	}
10981b4e3f26SMel Gorman 	if (2 * write_pending <= reclaimable)
10991b4e3f26SMel Gorman 		return true;
11001b4e3f26SMel Gorman 
11011b4e3f26SMel Gorman 	return false;
11021b4e3f26SMel Gorman }
11031b4e3f26SMel Gorman 
1104c3f4a9a2SMel Gorman void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason)
11058cd7c588SMel Gorman {
11068cd7c588SMel Gorman 	wait_queue_head_t *wqh = &pgdat->reclaim_wait[reason];
1107c3f4a9a2SMel Gorman 	long timeout, ret;
11088cd7c588SMel Gorman 	DEFINE_WAIT(wait);
11098cd7c588SMel Gorman 
11108cd7c588SMel Gorman 	/*
11118cd7c588SMel Gorman 	 * Do not throttle IO workers, kthreads other than kswapd or
11128cd7c588SMel Gorman 	 * workqueues. They may be required for reclaim to make
11138cd7c588SMel Gorman 	 * forward progress (e.g. journalling workqueues or kthreads).
11148cd7c588SMel Gorman 	 */
11158cd7c588SMel Gorman 	if (!current_is_kswapd() &&
1116b485c6f1SMel Gorman 	    current->flags & (PF_IO_WORKER|PF_KTHREAD)) {
1117b485c6f1SMel Gorman 		cond_resched();
11188cd7c588SMel Gorman 		return;
1119b485c6f1SMel Gorman 	}
11208cd7c588SMel Gorman 
1121c3f4a9a2SMel Gorman 	/*
1122c3f4a9a2SMel Gorman 	 * These figures are pulled out of thin air.
1123c3f4a9a2SMel Gorman 	 * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many
1124c3f4a9a2SMel Gorman 	 * parallel reclaimers which is a short-lived event so the timeout is
1125c3f4a9a2SMel Gorman 	 * short. Failing to make progress or waiting on writeback are
1126c3f4a9a2SMel Gorman 	 * potentially long-lived events so use a longer timeout. This is shaky
1127c3f4a9a2SMel Gorman 	 * logic as a failure to make progress could be due to anything from
1128c3f4a9a2SMel Gorman 	 * writeback to a slow device to excessive references pages at the tail
1129c3f4a9a2SMel Gorman 	 * of the inactive LRU.
1130c3f4a9a2SMel Gorman 	 */
1131c3f4a9a2SMel Gorman 	switch(reason) {
1132c3f4a9a2SMel Gorman 	case VMSCAN_THROTTLE_WRITEBACK:
1133c3f4a9a2SMel Gorman 		timeout = HZ/10;
1134c3f4a9a2SMel Gorman 
1135c3f4a9a2SMel Gorman 		if (atomic_inc_return(&pgdat->nr_writeback_throttled) == 1) {
11368cd7c588SMel Gorman 			WRITE_ONCE(pgdat->nr_reclaim_start,
11378cd7c588SMel Gorman 				node_page_state(pgdat, NR_THROTTLED_WRITTEN));
11388cd7c588SMel Gorman 		}
11398cd7c588SMel Gorman 
1140c3f4a9a2SMel Gorman 		break;
11411b4e3f26SMel Gorman 	case VMSCAN_THROTTLE_CONGESTED:
11421b4e3f26SMel Gorman 		fallthrough;
1143c3f4a9a2SMel Gorman 	case VMSCAN_THROTTLE_NOPROGRESS:
11441b4e3f26SMel Gorman 		if (skip_throttle_noprogress(pgdat)) {
11451b4e3f26SMel Gorman 			cond_resched();
11461b4e3f26SMel Gorman 			return;
11471b4e3f26SMel Gorman 		}
11481b4e3f26SMel Gorman 
11491b4e3f26SMel Gorman 		timeout = 1;
11501b4e3f26SMel Gorman 
1151c3f4a9a2SMel Gorman 		break;
1152c3f4a9a2SMel Gorman 	case VMSCAN_THROTTLE_ISOLATED:
1153c3f4a9a2SMel Gorman 		timeout = HZ/50;
1154c3f4a9a2SMel Gorman 		break;
1155c3f4a9a2SMel Gorman 	default:
1156c3f4a9a2SMel Gorman 		WARN_ON_ONCE(1);
1157c3f4a9a2SMel Gorman 		timeout = HZ;
1158c3f4a9a2SMel Gorman 		break;
1159c3f4a9a2SMel Gorman 	}
1160c3f4a9a2SMel Gorman 
11618cd7c588SMel Gorman 	prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE);
11628cd7c588SMel Gorman 	ret = schedule_timeout(timeout);
11638cd7c588SMel Gorman 	finish_wait(wqh, &wait);
1164d818fca1SMel Gorman 
1165c3f4a9a2SMel Gorman 	if (reason == VMSCAN_THROTTLE_WRITEBACK)
11668cd7c588SMel Gorman 		atomic_dec(&pgdat->nr_writeback_throttled);
11678cd7c588SMel Gorman 
11688cd7c588SMel Gorman 	trace_mm_vmscan_throttled(pgdat->node_id, jiffies_to_usecs(timeout),
11698cd7c588SMel Gorman 				jiffies_to_usecs(timeout - ret),
11708cd7c588SMel Gorman 				reason);
11718cd7c588SMel Gorman }
11728cd7c588SMel Gorman 
11738cd7c588SMel Gorman /*
11748cd7c588SMel Gorman  * Account for pages written if tasks are throttled waiting on dirty
11758cd7c588SMel Gorman  * pages to clean. If enough pages have been cleaned since throttling
11768cd7c588SMel Gorman  * started then wakeup the throttled tasks.
11778cd7c588SMel Gorman  */
1178512b7931SLinus Torvalds void __acct_reclaim_writeback(pg_data_t *pgdat, struct folio *folio,
11798cd7c588SMel Gorman 							int nr_throttled)
11808cd7c588SMel Gorman {
11818cd7c588SMel Gorman 	unsigned long nr_written;
11828cd7c588SMel Gorman 
1183512b7931SLinus Torvalds 	node_stat_add_folio(folio, NR_THROTTLED_WRITTEN);
11848cd7c588SMel Gorman 
11858cd7c588SMel Gorman 	/*
11868cd7c588SMel Gorman 	 * This is an inaccurate read as the per-cpu deltas may not
11878cd7c588SMel Gorman 	 * be synchronised. However, given that the system is
11888cd7c588SMel Gorman 	 * writeback throttled, it is not worth taking the penalty
11898cd7c588SMel Gorman 	 * of getting an accurate count. At worst, the throttle
11908cd7c588SMel Gorman 	 * timeout guarantees forward progress.
11918cd7c588SMel Gorman 	 */
11928cd7c588SMel Gorman 	nr_written = node_page_state(pgdat, NR_THROTTLED_WRITTEN) -
11938cd7c588SMel Gorman 		READ_ONCE(pgdat->nr_reclaim_start);
11948cd7c588SMel Gorman 
11958cd7c588SMel Gorman 	if (nr_written > SWAP_CLUSTER_MAX * nr_throttled)
11968cd7c588SMel Gorman 		wake_up(&pgdat->reclaim_wait[VMSCAN_THROTTLE_WRITEBACK]);
11978cd7c588SMel Gorman }
11988cd7c588SMel Gorman 
119904e62a29SChristoph Lameter /* possible outcome of pageout() */
120004e62a29SChristoph Lameter typedef enum {
120104e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
120204e62a29SChristoph Lameter 	PAGE_KEEP,
120304e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
120404e62a29SChristoph Lameter 	PAGE_ACTIVATE,
120504e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
120604e62a29SChristoph Lameter 	PAGE_SUCCESS,
120704e62a29SChristoph Lameter 	/* page is clean and locked */
120804e62a29SChristoph Lameter 	PAGE_CLEAN,
120904e62a29SChristoph Lameter } pageout_t;
121004e62a29SChristoph Lameter 
12111da177e4SLinus Torvalds /*
12121742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
12131742f19fSAndrew Morton  * Calls ->writepage().
12141da177e4SLinus Torvalds  */
12152282679fSNeilBrown static pageout_t pageout(struct folio *folio, struct address_space *mapping,
12162282679fSNeilBrown 			 struct swap_iocb **plug)
12171da177e4SLinus Torvalds {
12181da177e4SLinus Torvalds 	/*
1219e0cd5e7fSMatthew Wilcox (Oracle) 	 * If the folio is dirty, only perform writeback if that write
12201da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
12211da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
12221da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
12231da177e4SLinus Torvalds 	 * PagePrivate for that.
12241da177e4SLinus Torvalds 	 *
12258174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
1226e0cd5e7fSMatthew Wilcox (Oracle) 	 * this folio's queue, we can perform writeback even if that
12271da177e4SLinus Torvalds 	 * will block.
12281da177e4SLinus Torvalds 	 *
1229e0cd5e7fSMatthew Wilcox (Oracle) 	 * If the folio is swapcache, write it back even if that would
12301da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
12311da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
12321da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
12331da177e4SLinus Torvalds 	 */
1234e0cd5e7fSMatthew Wilcox (Oracle) 	if (!is_page_cache_freeable(folio))
12351da177e4SLinus Torvalds 		return PAGE_KEEP;
12361da177e4SLinus Torvalds 	if (!mapping) {
12371da177e4SLinus Torvalds 		/*
1238e0cd5e7fSMatthew Wilcox (Oracle) 		 * Some data journaling orphaned folios can have
1239e0cd5e7fSMatthew Wilcox (Oracle) 		 * folio->mapping == NULL while being dirty with clean buffers.
12401da177e4SLinus Torvalds 		 */
1241e0cd5e7fSMatthew Wilcox (Oracle) 		if (folio_test_private(folio)) {
124268189fefSMatthew Wilcox (Oracle) 			if (try_to_free_buffers(folio)) {
1243e0cd5e7fSMatthew Wilcox (Oracle) 				folio_clear_dirty(folio);
1244e0cd5e7fSMatthew Wilcox (Oracle) 				pr_info("%s: orphaned folio\n", __func__);
12451da177e4SLinus Torvalds 				return PAGE_CLEAN;
12461da177e4SLinus Torvalds 			}
12471da177e4SLinus Torvalds 		}
12481da177e4SLinus Torvalds 		return PAGE_KEEP;
12491da177e4SLinus Torvalds 	}
12501da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
12511da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
12521da177e4SLinus Torvalds 
1253e0cd5e7fSMatthew Wilcox (Oracle) 	if (folio_clear_dirty_for_io(folio)) {
12541da177e4SLinus Torvalds 		int res;
12551da177e4SLinus Torvalds 		struct writeback_control wbc = {
12561da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
12571da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
1258111ebb6eSOGAWA Hirofumi 			.range_start = 0,
1259111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
12601da177e4SLinus Torvalds 			.for_reclaim = 1,
12612282679fSNeilBrown 			.swap_plug = plug,
12621da177e4SLinus Torvalds 		};
12631da177e4SLinus Torvalds 
1264e0cd5e7fSMatthew Wilcox (Oracle) 		folio_set_reclaim(folio);
1265e0cd5e7fSMatthew Wilcox (Oracle) 		res = mapping->a_ops->writepage(&folio->page, &wbc);
12661da177e4SLinus Torvalds 		if (res < 0)
1267e0cd5e7fSMatthew Wilcox (Oracle) 			handle_write_error(mapping, folio, res);
1268994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
1269e0cd5e7fSMatthew Wilcox (Oracle) 			folio_clear_reclaim(folio);
12701da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
12711da177e4SLinus Torvalds 		}
1272c661b078SAndy Whitcroft 
1273e0cd5e7fSMatthew Wilcox (Oracle) 		if (!folio_test_writeback(folio)) {
12741da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
1275e0cd5e7fSMatthew Wilcox (Oracle) 			folio_clear_reclaim(folio);
12761da177e4SLinus Torvalds 		}
1277e0cd5e7fSMatthew Wilcox (Oracle) 		trace_mm_vmscan_write_folio(folio);
1278e0cd5e7fSMatthew Wilcox (Oracle) 		node_stat_add_folio(folio, NR_VMSCAN_WRITE);
12791da177e4SLinus Torvalds 		return PAGE_SUCCESS;
12801da177e4SLinus Torvalds 	}
12811da177e4SLinus Torvalds 
12821da177e4SLinus Torvalds 	return PAGE_CLEAN;
12831da177e4SLinus Torvalds }
12841da177e4SLinus Torvalds 
1285a649fd92SAndrew Morton /*
1286e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
1287e286781dSNick Piggin  * gets returned with a refcount of 0.
1288a649fd92SAndrew Morton  */
1289be7c07d6SMatthew Wilcox (Oracle) static int __remove_mapping(struct address_space *mapping, struct folio *folio,
1290b910718aSJohannes Weiner 			    bool reclaimed, struct mem_cgroup *target_memcg)
129149d2e9ccSChristoph Lameter {
1292bd4c82c2SHuang Ying 	int refcount;
1293aae466b0SJoonsoo Kim 	void *shadow = NULL;
1294c4843a75SGreg Thelen 
1295be7c07d6SMatthew Wilcox (Oracle) 	BUG_ON(!folio_test_locked(folio));
1296be7c07d6SMatthew Wilcox (Oracle) 	BUG_ON(mapping != folio_mapping(folio));
129749d2e9ccSChristoph Lameter 
1298be7c07d6SMatthew Wilcox (Oracle) 	if (!folio_test_swapcache(folio))
129951b8c1feSJohannes Weiner 		spin_lock(&mapping->host->i_lock);
130030472509SJohannes Weiner 	xa_lock_irq(&mapping->i_pages);
130149d2e9ccSChristoph Lameter 	/*
13020fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
13030fd0e6b0SNick Piggin 	 *
13040fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
13050fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
13060fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
13070fd0e6b0SNick Piggin 	 * here, then the following race may occur:
13080fd0e6b0SNick Piggin 	 *
13090fd0e6b0SNick Piggin 	 * get_user_pages(&page);
13100fd0e6b0SNick Piggin 	 * [user mapping goes away]
13110fd0e6b0SNick Piggin 	 * write_to(page);
13120fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
13130fd0e6b0SNick Piggin 	 * SetPageDirty(page);
13140fd0e6b0SNick Piggin 	 * put_page(page);
13150fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
13160fd0e6b0SNick Piggin 	 *
13170fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
13180fd0e6b0SNick Piggin 	 *
13190fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
13200fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
13210139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
13220fd0e6b0SNick Piggin 	 *
13230fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
1324b93b0163SMatthew Wilcox 	 * and thus under the i_pages lock, then this ordering is not required.
132549d2e9ccSChristoph Lameter 	 */
1326be7c07d6SMatthew Wilcox (Oracle) 	refcount = 1 + folio_nr_pages(folio);
1327be7c07d6SMatthew Wilcox (Oracle) 	if (!folio_ref_freeze(folio, refcount))
132849d2e9ccSChristoph Lameter 		goto cannot_free;
13291c4c3b99SJiang Biao 	/* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
1330be7c07d6SMatthew Wilcox (Oracle) 	if (unlikely(folio_test_dirty(folio))) {
1331be7c07d6SMatthew Wilcox (Oracle) 		folio_ref_unfreeze(folio, refcount);
133249d2e9ccSChristoph Lameter 		goto cannot_free;
1333e286781dSNick Piggin 	}
133449d2e9ccSChristoph Lameter 
1335be7c07d6SMatthew Wilcox (Oracle) 	if (folio_test_swapcache(folio)) {
1336be7c07d6SMatthew Wilcox (Oracle) 		swp_entry_t swap = folio_swap_entry(folio);
1337*ac35a490SYu Zhao 
1338*ac35a490SYu Zhao 		/* get a shadow entry before mem_cgroup_swapout() clears folio_memcg() */
1339aae466b0SJoonsoo Kim 		if (reclaimed && !mapping_exiting(mapping))
13408927f647SMatthew Wilcox (Oracle) 			shadow = workingset_eviction(folio, target_memcg);
1341*ac35a490SYu Zhao 		mem_cgroup_swapout(folio, swap);
1342ceff9d33SMatthew Wilcox (Oracle) 		__delete_from_swap_cache(folio, swap, shadow);
134330472509SJohannes Weiner 		xa_unlock_irq(&mapping->i_pages);
1344be7c07d6SMatthew Wilcox (Oracle) 		put_swap_page(&folio->page, swap);
1345e286781dSNick Piggin 	} else {
1346d2329aa0SMatthew Wilcox (Oracle) 		void (*free_folio)(struct folio *);
13476072d13cSLinus Torvalds 
1348d2329aa0SMatthew Wilcox (Oracle) 		free_folio = mapping->a_ops->free_folio;
1349a528910eSJohannes Weiner 		/*
1350a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
1351a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
1352a528910eSJohannes Weiner 		 *
1353a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
1354238c3046Sdylan-meiners 		 * already exiting.  This is not just an optimization,
1355a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
1356a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
1357a528910eSJohannes Weiner 		 * back.
1358f9fe48beSRoss Zwisler 		 *
1359f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
1360f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
1361f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
1362f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
1363b93b0163SMatthew Wilcox 		 * same address_space.
1364a528910eSJohannes Weiner 		 */
1365be7c07d6SMatthew Wilcox (Oracle) 		if (reclaimed && folio_is_file_lru(folio) &&
1366f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
13678927f647SMatthew Wilcox (Oracle) 			shadow = workingset_eviction(folio, target_memcg);
13688927f647SMatthew Wilcox (Oracle) 		__filemap_remove_folio(folio, shadow);
136930472509SJohannes Weiner 		xa_unlock_irq(&mapping->i_pages);
137051b8c1feSJohannes Weiner 		if (mapping_shrinkable(mapping))
137151b8c1feSJohannes Weiner 			inode_add_lru(mapping->host);
137251b8c1feSJohannes Weiner 		spin_unlock(&mapping->host->i_lock);
13736072d13cSLinus Torvalds 
1374d2329aa0SMatthew Wilcox (Oracle) 		if (free_folio)
1375d2329aa0SMatthew Wilcox (Oracle) 			free_folio(folio);
1376e286781dSNick Piggin 	}
1377e286781dSNick Piggin 
137849d2e9ccSChristoph Lameter 	return 1;
137949d2e9ccSChristoph Lameter 
138049d2e9ccSChristoph Lameter cannot_free:
138130472509SJohannes Weiner 	xa_unlock_irq(&mapping->i_pages);
1382be7c07d6SMatthew Wilcox (Oracle) 	if (!folio_test_swapcache(folio))
138351b8c1feSJohannes Weiner 		spin_unlock(&mapping->host->i_lock);
138449d2e9ccSChristoph Lameter 	return 0;
138549d2e9ccSChristoph Lameter }
138649d2e9ccSChristoph Lameter 
13875100da38SMatthew Wilcox (Oracle) /**
13885100da38SMatthew Wilcox (Oracle)  * remove_mapping() - Attempt to remove a folio from its mapping.
13895100da38SMatthew Wilcox (Oracle)  * @mapping: The address space.
13905100da38SMatthew Wilcox (Oracle)  * @folio: The folio to remove.
13915100da38SMatthew Wilcox (Oracle)  *
13925100da38SMatthew Wilcox (Oracle)  * If the folio is dirty, under writeback or if someone else has a ref
13935100da38SMatthew Wilcox (Oracle)  * on it, removal will fail.
13945100da38SMatthew Wilcox (Oracle)  * Return: The number of pages removed from the mapping.  0 if the folio
13955100da38SMatthew Wilcox (Oracle)  * could not be removed.
13965100da38SMatthew Wilcox (Oracle)  * Context: The caller should have a single refcount on the folio and
13975100da38SMatthew Wilcox (Oracle)  * hold its lock.
1398e286781dSNick Piggin  */
13995100da38SMatthew Wilcox (Oracle) long remove_mapping(struct address_space *mapping, struct folio *folio)
1400e286781dSNick Piggin {
1401be7c07d6SMatthew Wilcox (Oracle) 	if (__remove_mapping(mapping, folio, false, NULL)) {
1402e286781dSNick Piggin 		/*
14035100da38SMatthew Wilcox (Oracle) 		 * Unfreezing the refcount with 1 effectively
1404e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
1405e286781dSNick Piggin 		 * atomic operation.
1406e286781dSNick Piggin 		 */
1407be7c07d6SMatthew Wilcox (Oracle) 		folio_ref_unfreeze(folio, 1);
14085100da38SMatthew Wilcox (Oracle) 		return folio_nr_pages(folio);
1409e286781dSNick Piggin 	}
1410e286781dSNick Piggin 	return 0;
1411e286781dSNick Piggin }
1412e286781dSNick Piggin 
1413894bc310SLee Schermerhorn /**
1414ca6d60f3SMatthew Wilcox (Oracle)  * folio_putback_lru - Put previously isolated folio onto appropriate LRU list.
1415ca6d60f3SMatthew Wilcox (Oracle)  * @folio: Folio to be returned to an LRU list.
1416894bc310SLee Schermerhorn  *
1417ca6d60f3SMatthew Wilcox (Oracle)  * Add previously isolated @folio to appropriate LRU list.
1418ca6d60f3SMatthew Wilcox (Oracle)  * The folio may still be unevictable for other reasons.
1419894bc310SLee Schermerhorn  *
1420ca6d60f3SMatthew Wilcox (Oracle)  * Context: lru_lock must not be held, interrupts must be enabled.
1421894bc310SLee Schermerhorn  */
1422ca6d60f3SMatthew Wilcox (Oracle) void folio_putback_lru(struct folio *folio)
1423894bc310SLee Schermerhorn {
1424ca6d60f3SMatthew Wilcox (Oracle) 	folio_add_lru(folio);
1425ca6d60f3SMatthew Wilcox (Oracle) 	folio_put(folio);		/* drop ref from isolate */
1426894bc310SLee Schermerhorn }
1427894bc310SLee Schermerhorn 
1428dfc8d636SJohannes Weiner enum page_references {
1429dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
1430dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
143164574746SJohannes Weiner 	PAGEREF_KEEP,
1432dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
1433dfc8d636SJohannes Weiner };
1434dfc8d636SJohannes Weiner 
1435d92013d1SMatthew Wilcox (Oracle) static enum page_references folio_check_references(struct folio *folio,
1436dfc8d636SJohannes Weiner 						  struct scan_control *sc)
1437dfc8d636SJohannes Weiner {
1438d92013d1SMatthew Wilcox (Oracle) 	int referenced_ptes, referenced_folio;
1439dfc8d636SJohannes Weiner 	unsigned long vm_flags;
1440dfc8d636SJohannes Weiner 
1441b3ac0413SMatthew Wilcox (Oracle) 	referenced_ptes = folio_referenced(folio, 1, sc->target_mem_cgroup,
1442c3ac9a8aSJohannes Weiner 					   &vm_flags);
1443d92013d1SMatthew Wilcox (Oracle) 	referenced_folio = folio_test_clear_referenced(folio);
1444dfc8d636SJohannes Weiner 
1445dfc8d636SJohannes Weiner 	/*
1446d92013d1SMatthew Wilcox (Oracle) 	 * The supposedly reclaimable folio was found to be in a VM_LOCKED vma.
1447d92013d1SMatthew Wilcox (Oracle) 	 * Let the folio, now marked Mlocked, be moved to the unevictable list.
1448dfc8d636SJohannes Weiner 	 */
1449dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
145047d4f3eeSHugh Dickins 		return PAGEREF_ACTIVATE;
1451dfc8d636SJohannes Weiner 
14526d4675e6SMinchan Kim 	/* rmap lock contention: rotate */
14536d4675e6SMinchan Kim 	if (referenced_ptes == -1)
14546d4675e6SMinchan Kim 		return PAGEREF_KEEP;
14556d4675e6SMinchan Kim 
145664574746SJohannes Weiner 	if (referenced_ptes) {
145764574746SJohannes Weiner 		/*
1458d92013d1SMatthew Wilcox (Oracle) 		 * All mapped folios start out with page table
145964574746SJohannes Weiner 		 * references from the instantiating fault, so we need
14609030fb0bSLinus Torvalds 		 * to look twice if a mapped file/anon folio is used more
146164574746SJohannes Weiner 		 * than once.
146264574746SJohannes Weiner 		 *
146364574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
146464574746SJohannes Weiner 		 * inactive list.  Another page table reference will
146564574746SJohannes Weiner 		 * lead to its activation.
146664574746SJohannes Weiner 		 *
1467d92013d1SMatthew Wilcox (Oracle) 		 * Note: the mark is set for activated folios as well
1468d92013d1SMatthew Wilcox (Oracle) 		 * so that recently deactivated but used folios are
146964574746SJohannes Weiner 		 * quickly recovered.
147064574746SJohannes Weiner 		 */
1471d92013d1SMatthew Wilcox (Oracle) 		folio_set_referenced(folio);
147264574746SJohannes Weiner 
1473d92013d1SMatthew Wilcox (Oracle) 		if (referenced_folio || referenced_ptes > 1)
1474dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
1475dfc8d636SJohannes Weiner 
1476c909e993SKonstantin Khlebnikov 		/*
1477d92013d1SMatthew Wilcox (Oracle) 		 * Activate file-backed executable folios after first usage.
1478c909e993SKonstantin Khlebnikov 		 */
1479f19a27e3SMiaohe Lin 		if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio))
1480c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
1481c909e993SKonstantin Khlebnikov 
148264574746SJohannes Weiner 		return PAGEREF_KEEP;
148364574746SJohannes Weiner 	}
148464574746SJohannes Weiner 
1485d92013d1SMatthew Wilcox (Oracle) 	/* Reclaim if clean, defer dirty folios to writeback */
1486f19a27e3SMiaohe Lin 	if (referenced_folio && folio_is_file_lru(folio))
1487dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
148864574746SJohannes Weiner 
148964574746SJohannes Weiner 	return PAGEREF_RECLAIM;
1490dfc8d636SJohannes Weiner }
1491dfc8d636SJohannes Weiner 
1492e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
1493e20c41b1SMatthew Wilcox (Oracle) static void folio_check_dirty_writeback(struct folio *folio,
1494e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
1495e2be15f6SMel Gorman {
1496b4597226SMel Gorman 	struct address_space *mapping;
1497b4597226SMel Gorman 
1498e2be15f6SMel Gorman 	/*
1499e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
150032a331a7SMiaohe Lin 	 * from reclaim context. Do not stall reclaim based on them.
150132a331a7SMiaohe Lin 	 * MADV_FREE anonymous pages are put into inactive file list too.
150232a331a7SMiaohe Lin 	 * They could be mistakenly treated as file lru. So further anon
150332a331a7SMiaohe Lin 	 * test is needed.
1504e2be15f6SMel Gorman 	 */
1505e20c41b1SMatthew Wilcox (Oracle) 	if (!folio_is_file_lru(folio) ||
1506e20c41b1SMatthew Wilcox (Oracle) 	    (folio_test_anon(folio) && !folio_test_swapbacked(folio))) {
1507e2be15f6SMel Gorman 		*dirty = false;
1508e2be15f6SMel Gorman 		*writeback = false;
1509e2be15f6SMel Gorman 		return;
1510e2be15f6SMel Gorman 	}
1511e2be15f6SMel Gorman 
1512e20c41b1SMatthew Wilcox (Oracle) 	/* By default assume that the folio flags are accurate */
1513e20c41b1SMatthew Wilcox (Oracle) 	*dirty = folio_test_dirty(folio);
1514e20c41b1SMatthew Wilcox (Oracle) 	*writeback = folio_test_writeback(folio);
1515b4597226SMel Gorman 
1516b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
1517e20c41b1SMatthew Wilcox (Oracle) 	if (!folio_test_private(folio))
1518b4597226SMel Gorman 		return;
1519b4597226SMel Gorman 
1520e20c41b1SMatthew Wilcox (Oracle) 	mapping = folio_mapping(folio);
1521b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
1522520f301cSMatthew Wilcox (Oracle) 		mapping->a_ops->is_dirty_writeback(folio, dirty, writeback);
1523e2be15f6SMel Gorman }
1524e2be15f6SMel Gorman 
152526aa2d19SDave Hansen static struct page *alloc_demote_page(struct page *page, unsigned long node)
152626aa2d19SDave Hansen {
152726aa2d19SDave Hansen 	struct migration_target_control mtc = {
152826aa2d19SDave Hansen 		/*
152926aa2d19SDave Hansen 		 * Allocate from 'node', or fail quickly and quietly.
153026aa2d19SDave Hansen 		 * When this happens, 'page' will likely just be discarded
153126aa2d19SDave Hansen 		 * instead of migrated.
153226aa2d19SDave Hansen 		 */
153326aa2d19SDave Hansen 		.gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
153426aa2d19SDave Hansen 			    __GFP_THISNODE  | __GFP_NOWARN |
153526aa2d19SDave Hansen 			    __GFP_NOMEMALLOC | GFP_NOWAIT,
153626aa2d19SDave Hansen 		.nid = node
153726aa2d19SDave Hansen 	};
153826aa2d19SDave Hansen 
153926aa2d19SDave Hansen 	return alloc_migration_target(page, (unsigned long)&mtc);
154026aa2d19SDave Hansen }
154126aa2d19SDave Hansen 
154226aa2d19SDave Hansen /*
154326aa2d19SDave Hansen  * Take pages on @demote_list and attempt to demote them to
154426aa2d19SDave Hansen  * another node.  Pages which are not demoted are left on
154526aa2d19SDave Hansen  * @demote_pages.
154626aa2d19SDave Hansen  */
154726aa2d19SDave Hansen static unsigned int demote_page_list(struct list_head *demote_pages,
154826aa2d19SDave Hansen 				     struct pglist_data *pgdat)
154926aa2d19SDave Hansen {
155026aa2d19SDave Hansen 	int target_nid = next_demotion_node(pgdat->node_id);
155126aa2d19SDave Hansen 	unsigned int nr_succeeded;
155226aa2d19SDave Hansen 
155326aa2d19SDave Hansen 	if (list_empty(demote_pages))
155426aa2d19SDave Hansen 		return 0;
155526aa2d19SDave Hansen 
155626aa2d19SDave Hansen 	if (target_nid == NUMA_NO_NODE)
155726aa2d19SDave Hansen 		return 0;
155826aa2d19SDave Hansen 
155926aa2d19SDave Hansen 	/* Demotion ignores all cpuset and mempolicy settings */
1560cb75463cSKai Song 	migrate_pages(demote_pages, alloc_demote_page, NULL,
156126aa2d19SDave Hansen 			    target_nid, MIGRATE_ASYNC, MR_DEMOTION,
156226aa2d19SDave Hansen 			    &nr_succeeded);
156326aa2d19SDave Hansen 
1564668e4147SYang Shi 	if (current_is_kswapd())
1565668e4147SYang Shi 		__count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1566668e4147SYang Shi 	else
1567668e4147SYang Shi 		__count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1568668e4147SYang Shi 
156926aa2d19SDave Hansen 	return nr_succeeded;
157026aa2d19SDave Hansen }
157126aa2d19SDave Hansen 
1572c28a0e96SMatthew Wilcox (Oracle) static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask)
1573d791ea67SNeilBrown {
1574d791ea67SNeilBrown 	if (gfp_mask & __GFP_FS)
1575d791ea67SNeilBrown 		return true;
1576c28a0e96SMatthew Wilcox (Oracle) 	if (!folio_test_swapcache(folio) || !(gfp_mask & __GFP_IO))
1577d791ea67SNeilBrown 		return false;
1578d791ea67SNeilBrown 	/*
1579d791ea67SNeilBrown 	 * We can "enter_fs" for swap-cache with only __GFP_IO
1580d791ea67SNeilBrown 	 * providing this isn't SWP_FS_OPS.
1581d791ea67SNeilBrown 	 * ->flags can be updated non-atomicially (scan_swap_map_slots),
1582d791ea67SNeilBrown 	 * but that will never affect SWP_FS_OPS, so the data_race
1583d791ea67SNeilBrown 	 * is safe.
1584d791ea67SNeilBrown 	 */
1585b98c359fSMatthew Wilcox (Oracle) 	return !data_race(folio_swap_flags(folio) & SWP_FS_OPS);
1586d791ea67SNeilBrown }
1587d791ea67SNeilBrown 
1588e286781dSNick Piggin /*
15891742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
15901da177e4SLinus Torvalds  */
1591730ec8c0SManinder Singh static unsigned int shrink_page_list(struct list_head *page_list,
1592599d0c95SMel Gorman 				     struct pglist_data *pgdat,
1593f84f6e2bSMel Gorman 				     struct scan_control *sc,
15943c710c1aSMichal Hocko 				     struct reclaim_stat *stat,
15958940b34aSMinchan Kim 				     bool ignore_references)
15961da177e4SLinus Torvalds {
15971da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
1598abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
159926aa2d19SDave Hansen 	LIST_HEAD(demote_pages);
1600730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
1601730ec8c0SManinder Singh 	unsigned int pgactivate = 0;
160226aa2d19SDave Hansen 	bool do_demote_pass;
16032282679fSNeilBrown 	struct swap_iocb *plug = NULL;
16041da177e4SLinus Torvalds 
1605060f005fSKirill Tkhai 	memset(stat, 0, sizeof(*stat));
16061da177e4SLinus Torvalds 	cond_resched();
160726aa2d19SDave Hansen 	do_demote_pass = can_demote(pgdat->node_id, sc);
16081da177e4SLinus Torvalds 
160926aa2d19SDave Hansen retry:
16101da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
16111da177e4SLinus Torvalds 		struct address_space *mapping;
1612be7c07d6SMatthew Wilcox (Oracle) 		struct folio *folio;
16138940b34aSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM;
1614d791ea67SNeilBrown 		bool dirty, writeback;
161598879b3bSYang Shi 		unsigned int nr_pages;
16161da177e4SLinus Torvalds 
16171da177e4SLinus Torvalds 		cond_resched();
16181da177e4SLinus Torvalds 
1619be7c07d6SMatthew Wilcox (Oracle) 		folio = lru_to_folio(page_list);
1620be7c07d6SMatthew Wilcox (Oracle) 		list_del(&folio->lru);
16211da177e4SLinus Torvalds 
1622c28a0e96SMatthew Wilcox (Oracle) 		if (!folio_trylock(folio))
16231da177e4SLinus Torvalds 			goto keep;
16241da177e4SLinus Torvalds 
1625c28a0e96SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
16261da177e4SLinus Torvalds 
1627c28a0e96SMatthew Wilcox (Oracle) 		nr_pages = folio_nr_pages(folio);
162898879b3bSYang Shi 
1629c28a0e96SMatthew Wilcox (Oracle) 		/* Account the number of base pages */
163098879b3bSYang Shi 		sc->nr_scanned += nr_pages;
163180e43426SChristoph Lameter 
1632c28a0e96SMatthew Wilcox (Oracle) 		if (unlikely(!folio_evictable(folio)))
1633ad6b6704SMinchan Kim 			goto activate_locked;
1634894bc310SLee Schermerhorn 
16351bee2c16SMatthew Wilcox (Oracle) 		if (!sc->may_unmap && folio_mapped(folio))
163680e43426SChristoph Lameter 			goto keep_locked;
163780e43426SChristoph Lameter 
1638e62e384eSMichal Hocko 		/*
1639894befecSAndrey Ryabinin 		 * The number of dirty pages determines if a node is marked
16408cd7c588SMel Gorman 		 * reclaim_congested. kswapd will stall and start writing
1641c28a0e96SMatthew Wilcox (Oracle) 		 * folios if the tail of the LRU is all dirty unqueued folios.
1642e2be15f6SMel Gorman 		 */
1643e20c41b1SMatthew Wilcox (Oracle) 		folio_check_dirty_writeback(folio, &dirty, &writeback);
1644e2be15f6SMel Gorman 		if (dirty || writeback)
1645c79b7b96SMatthew Wilcox (Oracle) 			stat->nr_dirty += nr_pages;
1646e2be15f6SMel Gorman 
1647e2be15f6SMel Gorman 		if (dirty && !writeback)
1648c79b7b96SMatthew Wilcox (Oracle) 			stat->nr_unqueued_dirty += nr_pages;
1649e2be15f6SMel Gorman 
1650d04e8acdSMel Gorman 		/*
1651c28a0e96SMatthew Wilcox (Oracle) 		 * Treat this folio as congested if folios are cycling
1652c28a0e96SMatthew Wilcox (Oracle) 		 * through the LRU so quickly that the folios marked
1653c28a0e96SMatthew Wilcox (Oracle) 		 * for immediate reclaim are making it to the end of
1654c28a0e96SMatthew Wilcox (Oracle) 		 * the LRU a second time.
1655d04e8acdSMel Gorman 		 */
1656c28a0e96SMatthew Wilcox (Oracle) 		if (writeback && folio_test_reclaim(folio))
1657c79b7b96SMatthew Wilcox (Oracle) 			stat->nr_congested += nr_pages;
1658e2be15f6SMel Gorman 
1659e2be15f6SMel Gorman 		/*
1660d33e4e14SMatthew Wilcox (Oracle) 		 * If a folio at the tail of the LRU is under writeback, there
1661283aba9fSMel Gorman 		 * are three cases to consider.
1662e62e384eSMichal Hocko 		 *
1663c28a0e96SMatthew Wilcox (Oracle) 		 * 1) If reclaim is encountering an excessive number
1664c28a0e96SMatthew Wilcox (Oracle) 		 *    of folios under writeback and this folio has both
1665c28a0e96SMatthew Wilcox (Oracle) 		 *    the writeback and reclaim flags set, then it
1666d33e4e14SMatthew Wilcox (Oracle) 		 *    indicates that folios are being queued for I/O but
1667d33e4e14SMatthew Wilcox (Oracle) 		 *    are being recycled through the LRU before the I/O
1668d33e4e14SMatthew Wilcox (Oracle) 		 *    can complete. Waiting on the folio itself risks an
1669d33e4e14SMatthew Wilcox (Oracle) 		 *    indefinite stall if it is impossible to writeback
1670d33e4e14SMatthew Wilcox (Oracle) 		 *    the folio due to I/O error or disconnected storage
1671d33e4e14SMatthew Wilcox (Oracle) 		 *    so instead note that the LRU is being scanned too
1672d33e4e14SMatthew Wilcox (Oracle) 		 *    quickly and the caller can stall after the folio
1673d33e4e14SMatthew Wilcox (Oracle) 		 *    list has been processed.
1674c3b94f44SHugh Dickins 		 *
1675d33e4e14SMatthew Wilcox (Oracle) 		 * 2) Global or new memcg reclaim encounters a folio that is
1676ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1677ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1678d33e4e14SMatthew Wilcox (Oracle) 		 *    not to fs). In this case mark the folio for immediate
167997c9341fSTejun Heo 		 *    reclaim and continue scanning.
1680283aba9fSMel Gorman 		 *
1681d791ea67SNeilBrown 		 *    Require may_enter_fs() because we would wait on fs, which
1682d33e4e14SMatthew Wilcox (Oracle) 		 *    may not have submitted I/O yet. And the loop driver might
1683d33e4e14SMatthew Wilcox (Oracle) 		 *    enter reclaim, and deadlock if it waits on a folio for
1684283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1685283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1686283aba9fSMel Gorman 		 *    would probably show more reasons.
1687283aba9fSMel Gorman 		 *
1688d33e4e14SMatthew Wilcox (Oracle) 		 * 3) Legacy memcg encounters a folio that already has the
1689d33e4e14SMatthew Wilcox (Oracle) 		 *    reclaim flag set. memcg does not have any dirty folio
1690283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1691d33e4e14SMatthew Wilcox (Oracle) 		 *    folios are in writeback and there is nothing else to
1692283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1693c55e8d03SJohannes Weiner 		 *
1694d33e4e14SMatthew Wilcox (Oracle) 		 * In cases 1) and 2) we activate the folios to get them out of
1695d33e4e14SMatthew Wilcox (Oracle) 		 * the way while we continue scanning for clean folios on the
1696c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1697c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1698c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1699c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1700c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1701c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1702e62e384eSMichal Hocko 		 */
1703d33e4e14SMatthew Wilcox (Oracle) 		if (folio_test_writeback(folio)) {
1704283aba9fSMel Gorman 			/* Case 1 above */
1705283aba9fSMel Gorman 			if (current_is_kswapd() &&
1706d33e4e14SMatthew Wilcox (Oracle) 			    folio_test_reclaim(folio) &&
1707599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1708c79b7b96SMatthew Wilcox (Oracle) 				stat->nr_immediate += nr_pages;
1709c55e8d03SJohannes Weiner 				goto activate_locked;
1710283aba9fSMel Gorman 
1711283aba9fSMel Gorman 			/* Case 2 above */
1712b5ead35eSJohannes Weiner 			} else if (writeback_throttling_sane(sc) ||
1713d33e4e14SMatthew Wilcox (Oracle) 			    !folio_test_reclaim(folio) ||
1714c28a0e96SMatthew Wilcox (Oracle) 			    !may_enter_fs(folio, sc->gfp_mask)) {
1715c3b94f44SHugh Dickins 				/*
1716d33e4e14SMatthew Wilcox (Oracle) 				 * This is slightly racy -
1717c28a0e96SMatthew Wilcox (Oracle) 				 * folio_end_writeback() might have
1718c28a0e96SMatthew Wilcox (Oracle) 				 * just cleared the reclaim flag, then
1719c28a0e96SMatthew Wilcox (Oracle) 				 * setting the reclaim flag here ends up
1720c28a0e96SMatthew Wilcox (Oracle) 				 * interpreted as the readahead flag - but
1721c28a0e96SMatthew Wilcox (Oracle) 				 * that does not matter enough to care.
1722c28a0e96SMatthew Wilcox (Oracle) 				 * What we do want is for this folio to
1723c28a0e96SMatthew Wilcox (Oracle) 				 * have the reclaim flag set next time
1724c28a0e96SMatthew Wilcox (Oracle) 				 * memcg reclaim reaches the tests above,
1725c28a0e96SMatthew Wilcox (Oracle) 				 * so it will then wait for writeback to
1726c28a0e96SMatthew Wilcox (Oracle) 				 * avoid OOM; and it's also appropriate
1727d33e4e14SMatthew Wilcox (Oracle) 				 * in global reclaim.
1728c3b94f44SHugh Dickins 				 */
1729d33e4e14SMatthew Wilcox (Oracle) 				folio_set_reclaim(folio);
1730c79b7b96SMatthew Wilcox (Oracle) 				stat->nr_writeback += nr_pages;
1731c55e8d03SJohannes Weiner 				goto activate_locked;
1732283aba9fSMel Gorman 
1733283aba9fSMel Gorman 			/* Case 3 above */
1734283aba9fSMel Gorman 			} else {
1735d33e4e14SMatthew Wilcox (Oracle) 				folio_unlock(folio);
1736d33e4e14SMatthew Wilcox (Oracle) 				folio_wait_writeback(folio);
1737d33e4e14SMatthew Wilcox (Oracle) 				/* then go back and try same folio again */
1738d33e4e14SMatthew Wilcox (Oracle) 				list_add_tail(&folio->lru, page_list);
17397fadc820SHugh Dickins 				continue;
1740e62e384eSMichal Hocko 			}
1741283aba9fSMel Gorman 		}
17421da177e4SLinus Torvalds 
17438940b34aSMinchan Kim 		if (!ignore_references)
1744d92013d1SMatthew Wilcox (Oracle) 			references = folio_check_references(folio, sc);
174502c6de8dSMinchan Kim 
1746dfc8d636SJohannes Weiner 		switch (references) {
1747dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
17481da177e4SLinus Torvalds 			goto activate_locked;
174964574746SJohannes Weiner 		case PAGEREF_KEEP:
175098879b3bSYang Shi 			stat->nr_ref_keep += nr_pages;
175164574746SJohannes Weiner 			goto keep_locked;
1752dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1753dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1754c28a0e96SMatthew Wilcox (Oracle) 			; /* try to reclaim the folio below */
1755dfc8d636SJohannes Weiner 		}
17561da177e4SLinus Torvalds 
17571da177e4SLinus Torvalds 		/*
1758c28a0e96SMatthew Wilcox (Oracle) 		 * Before reclaiming the folio, try to relocate
175926aa2d19SDave Hansen 		 * its contents to another node.
176026aa2d19SDave Hansen 		 */
176126aa2d19SDave Hansen 		if (do_demote_pass &&
1762c28a0e96SMatthew Wilcox (Oracle) 		    (thp_migration_supported() || !folio_test_large(folio))) {
1763c28a0e96SMatthew Wilcox (Oracle) 			list_add(&folio->lru, &demote_pages);
1764c28a0e96SMatthew Wilcox (Oracle) 			folio_unlock(folio);
176526aa2d19SDave Hansen 			continue;
176626aa2d19SDave Hansen 		}
176726aa2d19SDave Hansen 
176826aa2d19SDave Hansen 		/*
17691da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
17701da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1771c28a0e96SMatthew Wilcox (Oracle) 		 * Lazyfree folio could be freed directly
17721da177e4SLinus Torvalds 		 */
1773c28a0e96SMatthew Wilcox (Oracle) 		if (folio_test_anon(folio) && folio_test_swapbacked(folio)) {
1774c28a0e96SMatthew Wilcox (Oracle) 			if (!folio_test_swapcache(folio)) {
177563eb6b93SHugh Dickins 				if (!(sc->gfp_mask & __GFP_IO))
177663eb6b93SHugh Dickins 					goto keep_locked;
1777d4b4084aSMatthew Wilcox (Oracle) 				if (folio_maybe_dma_pinned(folio))
1778feb889fbSLinus Torvalds 					goto keep_locked;
1779c28a0e96SMatthew Wilcox (Oracle) 				if (folio_test_large(folio)) {
1780c28a0e96SMatthew Wilcox (Oracle) 					/* cannot split folio, skip it */
1781d4b4084aSMatthew Wilcox (Oracle) 					if (!can_split_folio(folio, NULL))
1782b8f593cdSHuang Ying 						goto activate_locked;
1783747552b1SHuang Ying 					/*
1784c28a0e96SMatthew Wilcox (Oracle) 					 * Split folios without a PMD map right
1785747552b1SHuang Ying 					 * away. Chances are some or all of the
1786747552b1SHuang Ying 					 * tail pages can be freed without IO.
1787747552b1SHuang Ying 					 */
1788d4b4084aSMatthew Wilcox (Oracle) 					if (!folio_entire_mapcount(folio) &&
1789346cf613SMatthew Wilcox (Oracle) 					    split_folio_to_list(folio,
1790bd4c82c2SHuang Ying 								page_list))
1791747552b1SHuang Ying 						goto activate_locked;
1792747552b1SHuang Ying 				}
179309c02e56SMatthew Wilcox (Oracle) 				if (!add_to_swap(folio)) {
179409c02e56SMatthew Wilcox (Oracle) 					if (!folio_test_large(folio))
179598879b3bSYang Shi 						goto activate_locked_split;
1796bd4c82c2SHuang Ying 					/* Fallback to swap normal pages */
1797346cf613SMatthew Wilcox (Oracle) 					if (split_folio_to_list(folio,
1798bd4c82c2SHuang Ying 								page_list))
17990f074658SMinchan Kim 						goto activate_locked;
1800fe490cc0SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1801fe490cc0SHuang Ying 					count_vm_event(THP_SWPOUT_FALLBACK);
1802fe490cc0SHuang Ying #endif
180309c02e56SMatthew Wilcox (Oracle) 					if (!add_to_swap(folio))
180498879b3bSYang Shi 						goto activate_locked_split;
18050f074658SMinchan Kim 				}
1806bd4c82c2SHuang Ying 			}
1807c28a0e96SMatthew Wilcox (Oracle) 		} else if (folio_test_swapbacked(folio) &&
1808c28a0e96SMatthew Wilcox (Oracle) 			   folio_test_large(folio)) {
1809c28a0e96SMatthew Wilcox (Oracle) 			/* Split shmem folio */
1810346cf613SMatthew Wilcox (Oracle) 			if (split_folio_to_list(folio, page_list))
18117751b2daSKirill A. Shutemov 				goto keep_locked;
1812e2be15f6SMel Gorman 		}
18131da177e4SLinus Torvalds 
18141da177e4SLinus Torvalds 		/*
1815c28a0e96SMatthew Wilcox (Oracle) 		 * If the folio was split above, the tail pages will make
1816c28a0e96SMatthew Wilcox (Oracle) 		 * their own pass through this function and be accounted
1817c28a0e96SMatthew Wilcox (Oracle) 		 * then.
181898879b3bSYang Shi 		 */
1819c28a0e96SMatthew Wilcox (Oracle) 		if ((nr_pages > 1) && !folio_test_large(folio)) {
182098879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
182198879b3bSYang Shi 			nr_pages = 1;
182298879b3bSYang Shi 		}
182398879b3bSYang Shi 
182498879b3bSYang Shi 		/*
18251bee2c16SMatthew Wilcox (Oracle) 		 * The folio is mapped into the page tables of one or more
18261da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
18271da177e4SLinus Torvalds 		 */
18281bee2c16SMatthew Wilcox (Oracle) 		if (folio_mapped(folio)) {
1829013339dfSShakeel Butt 			enum ttu_flags flags = TTU_BATCH_FLUSH;
18301bee2c16SMatthew Wilcox (Oracle) 			bool was_swapbacked = folio_test_swapbacked(folio);
1831bd4c82c2SHuang Ying 
18321bee2c16SMatthew Wilcox (Oracle) 			if (folio_test_pmd_mappable(folio))
1833bd4c82c2SHuang Ying 				flags |= TTU_SPLIT_HUGE_PMD;
18341f318a9bSJaewon Kim 
1835869f7ee6SMatthew Wilcox (Oracle) 			try_to_unmap(folio, flags);
18361bee2c16SMatthew Wilcox (Oracle) 			if (folio_mapped(folio)) {
183798879b3bSYang Shi 				stat->nr_unmap_fail += nr_pages;
18381bee2c16SMatthew Wilcox (Oracle) 				if (!was_swapbacked &&
18391bee2c16SMatthew Wilcox (Oracle) 				    folio_test_swapbacked(folio))
18401f318a9bSJaewon Kim 					stat->nr_lazyfree_fail += nr_pages;
18411da177e4SLinus Torvalds 				goto activate_locked;
18421da177e4SLinus Torvalds 			}
18431da177e4SLinus Torvalds 		}
18441da177e4SLinus Torvalds 
18455441d490SMatthew Wilcox (Oracle) 		mapping = folio_mapping(folio);
184649bd2bf9SMatthew Wilcox (Oracle) 		if (folio_test_dirty(folio)) {
1847ee72886dSMel Gorman 			/*
184849bd2bf9SMatthew Wilcox (Oracle) 			 * Only kswapd can writeback filesystem folios
18494eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
185049bd2bf9SMatthew Wilcox (Oracle) 			 * injecting inefficient single-folio I/O into
18514eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
185249bd2bf9SMatthew Wilcox (Oracle) 			 * write folios when we've encountered many
185349bd2bf9SMatthew Wilcox (Oracle) 			 * dirty folios, and when we've already scanned
185449bd2bf9SMatthew Wilcox (Oracle) 			 * the rest of the LRU for clean folios and see
185549bd2bf9SMatthew Wilcox (Oracle) 			 * the same dirty folios again (with the reclaim
185649bd2bf9SMatthew Wilcox (Oracle) 			 * flag set).
1857ee72886dSMel Gorman 			 */
185849bd2bf9SMatthew Wilcox (Oracle) 			if (folio_is_file_lru(folio) &&
185949bd2bf9SMatthew Wilcox (Oracle) 			    (!current_is_kswapd() ||
186049bd2bf9SMatthew Wilcox (Oracle) 			     !folio_test_reclaim(folio) ||
1861599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
186249ea7eb6SMel Gorman 				/*
186349ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
186449bd2bf9SMatthew Wilcox (Oracle) 				 * Similar in principle to deactivate_page()
186549bd2bf9SMatthew Wilcox (Oracle) 				 * except we already have the folio isolated
186649ea7eb6SMel Gorman 				 * and know it's dirty
186749ea7eb6SMel Gorman 				 */
186849bd2bf9SMatthew Wilcox (Oracle) 				node_stat_mod_folio(folio, NR_VMSCAN_IMMEDIATE,
186949bd2bf9SMatthew Wilcox (Oracle) 						nr_pages);
187049bd2bf9SMatthew Wilcox (Oracle) 				folio_set_reclaim(folio);
187149ea7eb6SMel Gorman 
1872c55e8d03SJohannes Weiner 				goto activate_locked;
1873ee72886dSMel Gorman 			}
1874ee72886dSMel Gorman 
1875dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
18761da177e4SLinus Torvalds 				goto keep_locked;
1877c28a0e96SMatthew Wilcox (Oracle) 			if (!may_enter_fs(folio, sc->gfp_mask))
18781da177e4SLinus Torvalds 				goto keep_locked;
187952a8363eSChristoph Lameter 			if (!sc->may_writepage)
18801da177e4SLinus Torvalds 				goto keep_locked;
18811da177e4SLinus Torvalds 
1882d950c947SMel Gorman 			/*
188349bd2bf9SMatthew Wilcox (Oracle) 			 * Folio is dirty. Flush the TLB if a writable entry
188449bd2bf9SMatthew Wilcox (Oracle) 			 * potentially exists to avoid CPU writes after I/O
1885d950c947SMel Gorman 			 * starts and then write it out here.
1886d950c947SMel Gorman 			 */
1887d950c947SMel Gorman 			try_to_unmap_flush_dirty();
18882282679fSNeilBrown 			switch (pageout(folio, mapping, &plug)) {
18891da177e4SLinus Torvalds 			case PAGE_KEEP:
18901da177e4SLinus Torvalds 				goto keep_locked;
18911da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
18921da177e4SLinus Torvalds 				goto activate_locked;
18931da177e4SLinus Torvalds 			case PAGE_SUCCESS:
1894c79b7b96SMatthew Wilcox (Oracle) 				stat->nr_pageout += nr_pages;
189596f8bf4fSJohannes Weiner 
189649bd2bf9SMatthew Wilcox (Oracle) 				if (folio_test_writeback(folio))
189741ac1999SMel Gorman 					goto keep;
189849bd2bf9SMatthew Wilcox (Oracle) 				if (folio_test_dirty(folio))
18991da177e4SLinus Torvalds 					goto keep;
19007d3579e8SKOSAKI Motohiro 
19011da177e4SLinus Torvalds 				/*
19021da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
190349bd2bf9SMatthew Wilcox (Oracle) 				 * ahead and try to reclaim the folio.
19041da177e4SLinus Torvalds 				 */
190549bd2bf9SMatthew Wilcox (Oracle) 				if (!folio_trylock(folio))
19061da177e4SLinus Torvalds 					goto keep;
190749bd2bf9SMatthew Wilcox (Oracle) 				if (folio_test_dirty(folio) ||
190849bd2bf9SMatthew Wilcox (Oracle) 				    folio_test_writeback(folio))
19091da177e4SLinus Torvalds 					goto keep_locked;
191049bd2bf9SMatthew Wilcox (Oracle) 				mapping = folio_mapping(folio);
191101359eb2SGustavo A. R. Silva 				fallthrough;
19121da177e4SLinus Torvalds 			case PAGE_CLEAN:
191349bd2bf9SMatthew Wilcox (Oracle) 				; /* try to free the folio below */
19141da177e4SLinus Torvalds 			}
19151da177e4SLinus Torvalds 		}
19161da177e4SLinus Torvalds 
19171da177e4SLinus Torvalds 		/*
19180a36111cSMatthew Wilcox (Oracle) 		 * If the folio has buffers, try to free the buffer
19190a36111cSMatthew Wilcox (Oracle) 		 * mappings associated with this folio. If we succeed
19200a36111cSMatthew Wilcox (Oracle) 		 * we try to free the folio as well.
19211da177e4SLinus Torvalds 		 *
19220a36111cSMatthew Wilcox (Oracle) 		 * We do this even if the folio is dirty.
19230a36111cSMatthew Wilcox (Oracle) 		 * filemap_release_folio() does not perform I/O, but it
19240a36111cSMatthew Wilcox (Oracle) 		 * is possible for a folio to have the dirty flag set,
19250a36111cSMatthew Wilcox (Oracle) 		 * but it is actually clean (all its buffers are clean).
19260a36111cSMatthew Wilcox (Oracle) 		 * This happens if the buffers were written out directly,
19270a36111cSMatthew Wilcox (Oracle) 		 * with submit_bh(). ext3 will do this, as well as
19280a36111cSMatthew Wilcox (Oracle) 		 * the blockdev mapping.  filemap_release_folio() will
19290a36111cSMatthew Wilcox (Oracle) 		 * discover that cleanness and will drop the buffers
19300a36111cSMatthew Wilcox (Oracle) 		 * and mark the folio clean - it can be freed.
19311da177e4SLinus Torvalds 		 *
19320a36111cSMatthew Wilcox (Oracle) 		 * Rarely, folios can have buffers and no ->mapping.
19330a36111cSMatthew Wilcox (Oracle) 		 * These are the folios which were not successfully
19340a36111cSMatthew Wilcox (Oracle) 		 * invalidated in truncate_cleanup_folio().  We try to
19350a36111cSMatthew Wilcox (Oracle) 		 * drop those buffers here and if that worked, and the
19360a36111cSMatthew Wilcox (Oracle) 		 * folio is no longer mapped into process address space
19370a36111cSMatthew Wilcox (Oracle) 		 * (refcount == 1) it can be freed.  Otherwise, leave
19380a36111cSMatthew Wilcox (Oracle) 		 * the folio on the LRU so it is swappable.
19391da177e4SLinus Torvalds 		 */
19400a36111cSMatthew Wilcox (Oracle) 		if (folio_has_private(folio)) {
19410a36111cSMatthew Wilcox (Oracle) 			if (!filemap_release_folio(folio, sc->gfp_mask))
19421da177e4SLinus Torvalds 				goto activate_locked;
19430a36111cSMatthew Wilcox (Oracle) 			if (!mapping && folio_ref_count(folio) == 1) {
19440a36111cSMatthew Wilcox (Oracle) 				folio_unlock(folio);
19450a36111cSMatthew Wilcox (Oracle) 				if (folio_put_testzero(folio))
19461da177e4SLinus Torvalds 					goto free_it;
1947e286781dSNick Piggin 				else {
1948e286781dSNick Piggin 					/*
1949e286781dSNick Piggin 					 * rare race with speculative reference.
1950e286781dSNick Piggin 					 * the speculative reference will free
19510a36111cSMatthew Wilcox (Oracle) 					 * this folio shortly, so we may
1952e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1953e286781dSNick Piggin 					 * leave it off the LRU).
1954e286781dSNick Piggin 					 */
19559aafcffcSMiaohe Lin 					nr_reclaimed += nr_pages;
1956e286781dSNick Piggin 					continue;
1957e286781dSNick Piggin 				}
1958e286781dSNick Piggin 			}
19591da177e4SLinus Torvalds 		}
19601da177e4SLinus Torvalds 
196164daa5d8SMatthew Wilcox (Oracle) 		if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) {
1962802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
196364daa5d8SMatthew Wilcox (Oracle) 			if (!folio_ref_freeze(folio, 1))
196449d2e9ccSChristoph Lameter 				goto keep_locked;
1965d17be2d9SMiaohe Lin 			/*
196664daa5d8SMatthew Wilcox (Oracle) 			 * The folio has only one reference left, which is
1967d17be2d9SMiaohe Lin 			 * from the isolation. After the caller puts the
196864daa5d8SMatthew Wilcox (Oracle) 			 * folio back on the lru and drops the reference, the
196964daa5d8SMatthew Wilcox (Oracle) 			 * folio will be freed anyway. It doesn't matter
197064daa5d8SMatthew Wilcox (Oracle) 			 * which lru it goes on. So we don't bother checking
197164daa5d8SMatthew Wilcox (Oracle) 			 * the dirty flag here.
1972d17be2d9SMiaohe Lin 			 */
197364daa5d8SMatthew Wilcox (Oracle) 			count_vm_events(PGLAZYFREED, nr_pages);
197464daa5d8SMatthew Wilcox (Oracle) 			count_memcg_folio_events(folio, PGLAZYFREED, nr_pages);
1975be7c07d6SMatthew Wilcox (Oracle) 		} else if (!mapping || !__remove_mapping(mapping, folio, true,
1976b910718aSJohannes Weiner 							 sc->target_mem_cgroup))
1977802a3a92SShaohua Li 			goto keep_locked;
19789a1ea439SHugh Dickins 
1979c28a0e96SMatthew Wilcox (Oracle) 		folio_unlock(folio);
1980e286781dSNick Piggin free_it:
198198879b3bSYang Shi 		/*
1982c28a0e96SMatthew Wilcox (Oracle) 		 * Folio may get swapped out as a whole, need to account
1983c28a0e96SMatthew Wilcox (Oracle) 		 * all pages in it.
198498879b3bSYang Shi 		 */
198598879b3bSYang Shi 		nr_reclaimed += nr_pages;
1986abe4c3b5SMel Gorman 
1987abe4c3b5SMel Gorman 		/*
1988abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1989abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1990abe4c3b5SMel Gorman 		 */
1991c28a0e96SMatthew Wilcox (Oracle) 		if (unlikely(folio_test_large(folio)))
19925375336cSMatthew Wilcox (Oracle) 			destroy_large_folio(folio);
19937ae88534SYang Shi 		else
1994c28a0e96SMatthew Wilcox (Oracle) 			list_add(&folio->lru, &free_pages);
19951da177e4SLinus Torvalds 		continue;
19961da177e4SLinus Torvalds 
199798879b3bSYang Shi activate_locked_split:
199898879b3bSYang Shi 		/*
199998879b3bSYang Shi 		 * The tail pages that are failed to add into swap cache
200098879b3bSYang Shi 		 * reach here.  Fixup nr_scanned and nr_pages.
200198879b3bSYang Shi 		 */
200298879b3bSYang Shi 		if (nr_pages > 1) {
200398879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
200498879b3bSYang Shi 			nr_pages = 1;
200598879b3bSYang Shi 		}
20061da177e4SLinus Torvalds activate_locked:
200768a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
2008246b6480SMatthew Wilcox (Oracle) 		if (folio_test_swapcache(folio) &&
2009246b6480SMatthew Wilcox (Oracle) 		    (mem_cgroup_swap_full(&folio->page) ||
2010246b6480SMatthew Wilcox (Oracle) 		     folio_test_mlocked(folio)))
2011246b6480SMatthew Wilcox (Oracle) 			try_to_free_swap(&folio->page);
2012246b6480SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
2013246b6480SMatthew Wilcox (Oracle) 		if (!folio_test_mlocked(folio)) {
2014246b6480SMatthew Wilcox (Oracle) 			int type = folio_is_file_lru(folio);
2015246b6480SMatthew Wilcox (Oracle) 			folio_set_active(folio);
201698879b3bSYang Shi 			stat->nr_activate[type] += nr_pages;
2017246b6480SMatthew Wilcox (Oracle) 			count_memcg_folio_events(folio, PGACTIVATE, nr_pages);
2018ad6b6704SMinchan Kim 		}
20191da177e4SLinus Torvalds keep_locked:
2020c28a0e96SMatthew Wilcox (Oracle) 		folio_unlock(folio);
20211da177e4SLinus Torvalds keep:
2022c28a0e96SMatthew Wilcox (Oracle) 		list_add(&folio->lru, &ret_pages);
2023c28a0e96SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(folio_test_lru(folio) ||
2024c28a0e96SMatthew Wilcox (Oracle) 				folio_test_unevictable(folio), folio);
20251da177e4SLinus Torvalds 	}
202626aa2d19SDave Hansen 	/* 'page_list' is always empty here */
202726aa2d19SDave Hansen 
2028c28a0e96SMatthew Wilcox (Oracle) 	/* Migrate folios selected for demotion */
202926aa2d19SDave Hansen 	nr_reclaimed += demote_page_list(&demote_pages, pgdat);
2030c28a0e96SMatthew Wilcox (Oracle) 	/* Folios that could not be demoted are still in @demote_pages */
203126aa2d19SDave Hansen 	if (!list_empty(&demote_pages)) {
2032c28a0e96SMatthew Wilcox (Oracle) 		/* Folios which weren't demoted go back on @page_list for retry: */
203326aa2d19SDave Hansen 		list_splice_init(&demote_pages, page_list);
203426aa2d19SDave Hansen 		do_demote_pass = false;
203526aa2d19SDave Hansen 		goto retry;
203626aa2d19SDave Hansen 	}
2037abe4c3b5SMel Gorman 
203898879b3bSYang Shi 	pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
203998879b3bSYang Shi 
2040747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
204172b252aeSMel Gorman 	try_to_unmap_flush();
20422d4894b5SMel Gorman 	free_unref_page_list(&free_pages);
2043abe4c3b5SMel Gorman 
20441da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
2045886cf190SKirill Tkhai 	count_vm_events(PGACTIVATE, pgactivate);
20460a31bc97SJohannes Weiner 
20472282679fSNeilBrown 	if (plug)
20482282679fSNeilBrown 		swap_write_unplug(plug);
204905ff5137SAndrew Morton 	return nr_reclaimed;
20501da177e4SLinus Torvalds }
20511da177e4SLinus Torvalds 
2052730ec8c0SManinder Singh unsigned int reclaim_clean_pages_from_list(struct zone *zone,
2053b8cecb93SMatthew Wilcox (Oracle) 					    struct list_head *folio_list)
205402c6de8dSMinchan Kim {
205502c6de8dSMinchan Kim 	struct scan_control sc = {
205602c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
205702c6de8dSMinchan Kim 		.may_unmap = 1,
205802c6de8dSMinchan Kim 	};
20591f318a9bSJaewon Kim 	struct reclaim_stat stat;
2060730ec8c0SManinder Singh 	unsigned int nr_reclaimed;
2061b8cecb93SMatthew Wilcox (Oracle) 	struct folio *folio, *next;
2062b8cecb93SMatthew Wilcox (Oracle) 	LIST_HEAD(clean_folios);
20632d2b8d2bSYu Zhao 	unsigned int noreclaim_flag;
206402c6de8dSMinchan Kim 
2065b8cecb93SMatthew Wilcox (Oracle) 	list_for_each_entry_safe(folio, next, folio_list, lru) {
2066b8cecb93SMatthew Wilcox (Oracle) 		if (!folio_test_hugetlb(folio) && folio_is_file_lru(folio) &&
2067b8cecb93SMatthew Wilcox (Oracle) 		    !folio_test_dirty(folio) && !__folio_test_movable(folio) &&
2068b8cecb93SMatthew Wilcox (Oracle) 		    !folio_test_unevictable(folio)) {
2069b8cecb93SMatthew Wilcox (Oracle) 			folio_clear_active(folio);
2070b8cecb93SMatthew Wilcox (Oracle) 			list_move(&folio->lru, &clean_folios);
207102c6de8dSMinchan Kim 		}
207202c6de8dSMinchan Kim 	}
207302c6de8dSMinchan Kim 
20742d2b8d2bSYu Zhao 	/*
20752d2b8d2bSYu Zhao 	 * We should be safe here since we are only dealing with file pages and
20762d2b8d2bSYu Zhao 	 * we are not kswapd and therefore cannot write dirty file pages. But
20772d2b8d2bSYu Zhao 	 * call memalloc_noreclaim_save() anyway, just in case these conditions
20782d2b8d2bSYu Zhao 	 * change in the future.
20792d2b8d2bSYu Zhao 	 */
20802d2b8d2bSYu Zhao 	noreclaim_flag = memalloc_noreclaim_save();
2081b8cecb93SMatthew Wilcox (Oracle) 	nr_reclaimed = shrink_page_list(&clean_folios, zone->zone_pgdat, &sc,
2082013339dfSShakeel Butt 					&stat, true);
20832d2b8d2bSYu Zhao 	memalloc_noreclaim_restore(noreclaim_flag);
20842d2b8d2bSYu Zhao 
2085b8cecb93SMatthew Wilcox (Oracle) 	list_splice(&clean_folios, folio_list);
20862da9f630SNicholas Piggin 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
20872da9f630SNicholas Piggin 			    -(long)nr_reclaimed);
20881f318a9bSJaewon Kim 	/*
20891f318a9bSJaewon Kim 	 * Since lazyfree pages are isolated from file LRU from the beginning,
20901f318a9bSJaewon Kim 	 * they will rotate back to anonymous LRU in the end if it failed to
20911f318a9bSJaewon Kim 	 * discard so isolated count will be mismatched.
20921f318a9bSJaewon Kim 	 * Compensate the isolated count for both LRU lists.
20931f318a9bSJaewon Kim 	 */
20941f318a9bSJaewon Kim 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
20951f318a9bSJaewon Kim 			    stat.nr_lazyfree_fail);
20961f318a9bSJaewon Kim 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
20972da9f630SNicholas Piggin 			    -(long)stat.nr_lazyfree_fail);
20981f318a9bSJaewon Kim 	return nr_reclaimed;
209902c6de8dSMinchan Kim }
210002c6de8dSMinchan Kim 
21015ad333ebSAndy Whitcroft /*
21027ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
210355b65a57SEthon Paul  * be complete before mem_cgroup_update_lru_size due to a sanity check.
21047ee36a14SMel Gorman  */
21057ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
2106b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
21077ee36a14SMel Gorman {
21087ee36a14SMel Gorman 	int zid;
21097ee36a14SMel Gorman 
21107ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
21117ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
21127ee36a14SMel Gorman 			continue;
21137ee36a14SMel Gorman 
2114a892cb6bSWei Yang 		update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
21157ee36a14SMel Gorman 	}
21167ee36a14SMel Gorman 
21177ee36a14SMel Gorman }
21187ee36a14SMel Gorman 
2119f611fab7SMel Gorman /*
212015b44736SHugh Dickins  * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
212115b44736SHugh Dickins  *
212215b44736SHugh Dickins  * lruvec->lru_lock is heavily contended.  Some of the functions that
21231da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
21241da177e4SLinus Torvalds  * and working on them outside the LRU lock.
21251da177e4SLinus Torvalds  *
21261da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
21271da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
21281da177e4SLinus Torvalds  *
212915b44736SHugh Dickins  * Lru_lock must be held before calling this function.
21301da177e4SLinus Torvalds  *
2131791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
21325dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
21331da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
2134f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
2135fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
21363cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
21371da177e4SLinus Torvalds  *
21381da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
21391da177e4SLinus Torvalds  */
214069e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
21415dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
2142fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
2143a9e7c39fSKirill Tkhai 		enum lru_list lru)
21441da177e4SLinus Torvalds {
214575b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
214669e05944SAndrew Morton 	unsigned long nr_taken = 0;
2147599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
21487cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
21493db65812SJohannes Weiner 	unsigned long skipped = 0;
2150791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
2151166e3d32SMatthew Wilcox (Oracle) 	LIST_HEAD(folios_skipped);
21521da177e4SLinus Torvalds 
215398879b3bSYang Shi 	total_scan = 0;
2154791b48b6SMinchan Kim 	scan = 0;
215598879b3bSYang Shi 	while (scan < nr_to_scan && !list_empty(src)) {
215689f6c88aSHugh Dickins 		struct list_head *move_to = src;
2157166e3d32SMatthew Wilcox (Oracle) 		struct folio *folio;
21585ad333ebSAndy Whitcroft 
2159166e3d32SMatthew Wilcox (Oracle) 		folio = lru_to_folio(src);
2160166e3d32SMatthew Wilcox (Oracle) 		prefetchw_prev_lru_folio(folio, src, flags);
21611da177e4SLinus Torvalds 
2162166e3d32SMatthew Wilcox (Oracle) 		nr_pages = folio_nr_pages(folio);
216398879b3bSYang Shi 		total_scan += nr_pages;
216498879b3bSYang Shi 
2165166e3d32SMatthew Wilcox (Oracle) 		if (folio_zonenum(folio) > sc->reclaim_idx) {
2166166e3d32SMatthew Wilcox (Oracle) 			nr_skipped[folio_zonenum(folio)] += nr_pages;
2167166e3d32SMatthew Wilcox (Oracle) 			move_to = &folios_skipped;
216889f6c88aSHugh Dickins 			goto move;
2169b2e18757SMel Gorman 		}
2170b2e18757SMel Gorman 
2171791b48b6SMinchan Kim 		/*
2172166e3d32SMatthew Wilcox (Oracle) 		 * Do not count skipped folios because that makes the function
2173166e3d32SMatthew Wilcox (Oracle) 		 * return with no isolated folios if the LRU mostly contains
2174166e3d32SMatthew Wilcox (Oracle) 		 * ineligible folios.  This causes the VM to not reclaim any
2175166e3d32SMatthew Wilcox (Oracle) 		 * folios, triggering a premature OOM.
2176166e3d32SMatthew Wilcox (Oracle) 		 * Account all pages in a folio.
2177791b48b6SMinchan Kim 		 */
217898879b3bSYang Shi 		scan += nr_pages;
217989f6c88aSHugh Dickins 
2180166e3d32SMatthew Wilcox (Oracle) 		if (!folio_test_lru(folio))
218189f6c88aSHugh Dickins 			goto move;
2182166e3d32SMatthew Wilcox (Oracle) 		if (!sc->may_unmap && folio_mapped(folio))
218389f6c88aSHugh Dickins 			goto move;
218489f6c88aSHugh Dickins 
21859df41314SAlex Shi 		/*
2186166e3d32SMatthew Wilcox (Oracle) 		 * Be careful not to clear the lru flag until after we're
2187166e3d32SMatthew Wilcox (Oracle) 		 * sure the folio is not being freed elsewhere -- the
2188166e3d32SMatthew Wilcox (Oracle) 		 * folio release code relies on it.
21899df41314SAlex Shi 		 */
2190166e3d32SMatthew Wilcox (Oracle) 		if (unlikely(!folio_try_get(folio)))
219189f6c88aSHugh Dickins 			goto move;
21929df41314SAlex Shi 
2193166e3d32SMatthew Wilcox (Oracle) 		if (!folio_test_clear_lru(folio)) {
2194166e3d32SMatthew Wilcox (Oracle) 			/* Another thread is already isolating this folio */
2195166e3d32SMatthew Wilcox (Oracle) 			folio_put(folio);
219689f6c88aSHugh Dickins 			goto move;
21979df41314SAlex Shi 		}
21989df41314SAlex Shi 
2199599d0c95SMel Gorman 		nr_taken += nr_pages;
2200166e3d32SMatthew Wilcox (Oracle) 		nr_zone_taken[folio_zonenum(folio)] += nr_pages;
220189f6c88aSHugh Dickins 		move_to = dst;
220289f6c88aSHugh Dickins move:
2203166e3d32SMatthew Wilcox (Oracle) 		list_move(&folio->lru, move_to);
22045ad333ebSAndy Whitcroft 	}
22051da177e4SLinus Torvalds 
2206b2e18757SMel Gorman 	/*
2207166e3d32SMatthew Wilcox (Oracle) 	 * Splice any skipped folios to the start of the LRU list. Note that
2208b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
2209b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2210166e3d32SMatthew Wilcox (Oracle) 	 * scanning would soon rescan the same folios to skip and waste lots
2211b2cb6826SMiaohe Lin 	 * of cpu cycles.
2212b2e18757SMel Gorman 	 */
2213166e3d32SMatthew Wilcox (Oracle) 	if (!list_empty(&folios_skipped)) {
22147cc30fcfSMel Gorman 		int zid;
22157cc30fcfSMel Gorman 
2216166e3d32SMatthew Wilcox (Oracle) 		list_splice(&folios_skipped, src);
22177cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
22187cc30fcfSMel Gorman 			if (!nr_skipped[zid])
22197cc30fcfSMel Gorman 				continue;
22207cc30fcfSMel Gorman 
22217cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
22221265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
22237cc30fcfSMel Gorman 		}
22247cc30fcfSMel Gorman 	}
2225791b48b6SMinchan Kim 	*nr_scanned = total_scan;
22261265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
222789f6c88aSHugh Dickins 				    total_scan, skipped, nr_taken,
222889f6c88aSHugh Dickins 				    sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
2229b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
22301da177e4SLinus Torvalds 	return nr_taken;
22311da177e4SLinus Torvalds }
22321da177e4SLinus Torvalds 
223362695a84SNick Piggin /**
2234d1d8a3b4SMatthew Wilcox (Oracle)  * folio_isolate_lru() - Try to isolate a folio from its LRU list.
2235d1d8a3b4SMatthew Wilcox (Oracle)  * @folio: Folio to isolate from its LRU list.
223662695a84SNick Piggin  *
2237d1d8a3b4SMatthew Wilcox (Oracle)  * Isolate a @folio from an LRU list and adjust the vmstat statistic
2238d1d8a3b4SMatthew Wilcox (Oracle)  * corresponding to whatever LRU list the folio was on.
223962695a84SNick Piggin  *
2240d1d8a3b4SMatthew Wilcox (Oracle)  * The folio will have its LRU flag cleared.  If it was found on the
2241d1d8a3b4SMatthew Wilcox (Oracle)  * active list, it will have the Active flag set.  If it was found on the
2242d1d8a3b4SMatthew Wilcox (Oracle)  * unevictable list, it will have the Unevictable flag set.  These flags
2243894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
224462695a84SNick Piggin  *
2245d1d8a3b4SMatthew Wilcox (Oracle)  * Context:
2246a5d09bedSMike Rapoport  *
224762695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
2248d1d8a3b4SMatthew Wilcox (Oracle)  *     fundamental difference from isolate_lru_pages() (which is called
224962695a84SNick Piggin  *     without a stable reference).
2250d1d8a3b4SMatthew Wilcox (Oracle)  * (2) The lru_lock must not be held.
2251d1d8a3b4SMatthew Wilcox (Oracle)  * (3) Interrupts must be enabled.
2252d1d8a3b4SMatthew Wilcox (Oracle)  *
2253d1d8a3b4SMatthew Wilcox (Oracle)  * Return: 0 if the folio was removed from an LRU list.
2254d1d8a3b4SMatthew Wilcox (Oracle)  * -EBUSY if the folio was not on an LRU list.
225562695a84SNick Piggin  */
2256d1d8a3b4SMatthew Wilcox (Oracle) int folio_isolate_lru(struct folio *folio)
225762695a84SNick Piggin {
225862695a84SNick Piggin 	int ret = -EBUSY;
225962695a84SNick Piggin 
2260d1d8a3b4SMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(!folio_ref_count(folio), folio);
22610c917313SKonstantin Khlebnikov 
2262d1d8a3b4SMatthew Wilcox (Oracle) 	if (folio_test_clear_lru(folio)) {
2263fa9add64SHugh Dickins 		struct lruvec *lruvec;
226462695a84SNick Piggin 
2265d1d8a3b4SMatthew Wilcox (Oracle) 		folio_get(folio);
2266e809c3feSMatthew Wilcox (Oracle) 		lruvec = folio_lruvec_lock_irq(folio);
2267d1d8a3b4SMatthew Wilcox (Oracle) 		lruvec_del_folio(lruvec, folio);
22686168d0daSAlex Shi 		unlock_page_lruvec_irq(lruvec);
2269fa9add64SHugh Dickins 		ret = 0;
227062695a84SNick Piggin 	}
2271d25b5bd8SAlex Shi 
227262695a84SNick Piggin 	return ret;
227362695a84SNick Piggin }
227462695a84SNick Piggin 
22755ad333ebSAndy Whitcroft /*
2276d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
2277178821b8SXianting Tian  * then get rescheduled. When there are massive number of tasks doing page
2278d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2279d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
2280d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
228135cd7815SRik van Riel  */
2282599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
228335cd7815SRik van Riel 		struct scan_control *sc)
228435cd7815SRik van Riel {
228535cd7815SRik van Riel 	unsigned long inactive, isolated;
2286d818fca1SMel Gorman 	bool too_many;
228735cd7815SRik van Riel 
228835cd7815SRik van Riel 	if (current_is_kswapd())
228935cd7815SRik van Riel 		return 0;
229035cd7815SRik van Riel 
2291b5ead35eSJohannes Weiner 	if (!writeback_throttling_sane(sc))
229235cd7815SRik van Riel 		return 0;
229335cd7815SRik van Riel 
229435cd7815SRik van Riel 	if (file) {
2295599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2296599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
229735cd7815SRik van Riel 	} else {
2298599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2299599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
230035cd7815SRik van Riel 	}
230135cd7815SRik van Riel 
23023cf23841SFengguang Wu 	/*
23033cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
23043cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
23053cf23841SFengguang Wu 	 * deadlock.
23063cf23841SFengguang Wu 	 */
2307d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
23083cf23841SFengguang Wu 		inactive >>= 3;
23093cf23841SFengguang Wu 
2310d818fca1SMel Gorman 	too_many = isolated > inactive;
2311d818fca1SMel Gorman 
2312d818fca1SMel Gorman 	/* Wake up tasks throttled due to too_many_isolated. */
2313d818fca1SMel Gorman 	if (!too_many)
2314d818fca1SMel Gorman 		wake_throttle_isolated(pgdat);
2315d818fca1SMel Gorman 
2316d818fca1SMel Gorman 	return too_many;
231735cd7815SRik van Riel }
231835cd7815SRik van Riel 
2319a222f341SKirill Tkhai /*
2320ff00a170SMatthew Wilcox (Oracle)  * move_pages_to_lru() moves folios from private @list to appropriate LRU list.
2321ff00a170SMatthew Wilcox (Oracle)  * On return, @list is reused as a list of folios to be freed by the caller.
2322a222f341SKirill Tkhai  *
2323a222f341SKirill Tkhai  * Returns the number of pages moved to the given lruvec.
2324a222f341SKirill Tkhai  */
23259ef56b78SMuchun Song static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2326a222f341SKirill Tkhai 				      struct list_head *list)
232766635629SMel Gorman {
2328a222f341SKirill Tkhai 	int nr_pages, nr_moved = 0;
2329ff00a170SMatthew Wilcox (Oracle) 	LIST_HEAD(folios_to_free);
233066635629SMel Gorman 
2331a222f341SKirill Tkhai 	while (!list_empty(list)) {
2332ff00a170SMatthew Wilcox (Oracle) 		struct folio *folio = lru_to_folio(list);
2333ff00a170SMatthew Wilcox (Oracle) 
2334ff00a170SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
2335ff00a170SMatthew Wilcox (Oracle) 		list_del(&folio->lru);
2336ff00a170SMatthew Wilcox (Oracle) 		if (unlikely(!folio_evictable(folio))) {
23376168d0daSAlex Shi 			spin_unlock_irq(&lruvec->lru_lock);
2338ff00a170SMatthew Wilcox (Oracle) 			folio_putback_lru(folio);
23396168d0daSAlex Shi 			spin_lock_irq(&lruvec->lru_lock);
234066635629SMel Gorman 			continue;
234166635629SMel Gorman 		}
2342fa9add64SHugh Dickins 
23433d06afabSAlex Shi 		/*
2344ff00a170SMatthew Wilcox (Oracle) 		 * The folio_set_lru needs to be kept here for list integrity.
23453d06afabSAlex Shi 		 * Otherwise:
23463d06afabSAlex Shi 		 *   #0 move_pages_to_lru             #1 release_pages
2347ff00a170SMatthew Wilcox (Oracle) 		 *   if (!folio_put_testzero())
2348ff00a170SMatthew Wilcox (Oracle) 		 *				      if (folio_put_testzero())
2349ff00a170SMatthew Wilcox (Oracle) 		 *				        !lru //skip lru_lock
2350ff00a170SMatthew Wilcox (Oracle) 		 *     folio_set_lru()
2351ff00a170SMatthew Wilcox (Oracle) 		 *     list_add(&folio->lru,)
2352ff00a170SMatthew Wilcox (Oracle) 		 *                                        list_add(&folio->lru,)
23533d06afabSAlex Shi 		 */
2354ff00a170SMatthew Wilcox (Oracle) 		folio_set_lru(folio);
2355a222f341SKirill Tkhai 
2356ff00a170SMatthew Wilcox (Oracle) 		if (unlikely(folio_put_testzero(folio))) {
2357ff00a170SMatthew Wilcox (Oracle) 			__folio_clear_lru_flags(folio);
23582bcf8879SHugh Dickins 
2359ff00a170SMatthew Wilcox (Oracle) 			if (unlikely(folio_test_large(folio))) {
23606168d0daSAlex Shi 				spin_unlock_irq(&lruvec->lru_lock);
23615375336cSMatthew Wilcox (Oracle) 				destroy_large_folio(folio);
23626168d0daSAlex Shi 				spin_lock_irq(&lruvec->lru_lock);
23632bcf8879SHugh Dickins 			} else
2364ff00a170SMatthew Wilcox (Oracle) 				list_add(&folio->lru, &folios_to_free);
23653d06afabSAlex Shi 
23663d06afabSAlex Shi 			continue;
23673d06afabSAlex Shi 		}
23683d06afabSAlex Shi 
2369afca9157SAlex Shi 		/*
2370afca9157SAlex Shi 		 * All pages were isolated from the same lruvec (and isolation
2371afca9157SAlex Shi 		 * inhibits memcg migration).
2372afca9157SAlex Shi 		 */
2373ff00a170SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(!folio_matches_lruvec(folio, lruvec), folio);
2374ff00a170SMatthew Wilcox (Oracle) 		lruvec_add_folio(lruvec, folio);
2375ff00a170SMatthew Wilcox (Oracle) 		nr_pages = folio_nr_pages(folio);
2376a222f341SKirill Tkhai 		nr_moved += nr_pages;
2377ff00a170SMatthew Wilcox (Oracle) 		if (folio_test_active(folio))
237831d8fcacSJohannes Weiner 			workingset_age_nonresident(lruvec, nr_pages);
237966635629SMel Gorman 	}
238066635629SMel Gorman 
23813f79768fSHugh Dickins 	/*
23823f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
23833f79768fSHugh Dickins 	 */
2384ff00a170SMatthew Wilcox (Oracle) 	list_splice(&folios_to_free, list);
2385a222f341SKirill Tkhai 
2386a222f341SKirill Tkhai 	return nr_moved;
238766635629SMel Gorman }
238866635629SMel Gorman 
238966635629SMel Gorman /*
23905829f7dbSMiaohe Lin  * If a kernel thread (such as nfsd for loop-back mounts) services a backing
23915829f7dbSMiaohe Lin  * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case
23925829f7dbSMiaohe Lin  * we should not throttle.  Otherwise it is safe to do so.
2393399ba0b9SNeilBrown  */
2394399ba0b9SNeilBrown static int current_may_throttle(void)
2395399ba0b9SNeilBrown {
2396b9b1335eSNeilBrown 	return !(current->flags & PF_LOCAL_THROTTLE);
2397399ba0b9SNeilBrown }
2398399ba0b9SNeilBrown 
2399399ba0b9SNeilBrown /*
2400b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
24011742f19fSAndrew Morton  * of reclaimed pages
24021da177e4SLinus Torvalds  */
24039ef56b78SMuchun Song static unsigned long
24041a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
24059e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
24061da177e4SLinus Torvalds {
24071da177e4SLinus Torvalds 	LIST_HEAD(page_list);
2408e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
2409730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
2410e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
2411060f005fSKirill Tkhai 	struct reclaim_stat stat;
2412497a6c1bSJohannes Weiner 	bool file = is_file_lru(lru);
2413f46b7912SKirill Tkhai 	enum vm_event_item item;
2414599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2415db73ee0dSMichal Hocko 	bool stalled = false;
241678dc583dSKOSAKI Motohiro 
2417599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
2418db73ee0dSMichal Hocko 		if (stalled)
2419db73ee0dSMichal Hocko 			return 0;
2420db73ee0dSMichal Hocko 
2421db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
2422db73ee0dSMichal Hocko 		stalled = true;
2423c3f4a9a2SMel Gorman 		reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
242435cd7815SRik van Riel 
242535cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
242635cd7815SRik van Riel 		if (fatal_signal_pending(current))
242735cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
242835cd7815SRik van Riel 	}
242935cd7815SRik van Riel 
24301da177e4SLinus Torvalds 	lru_add_drain();
2431f80c0673SMinchan Kim 
24326168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
24331da177e4SLinus Torvalds 
24345dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
2435a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
243695d918fcSKonstantin Khlebnikov 
2437599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2438f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
2439b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
2440f46b7912SKirill Tkhai 		__count_vm_events(item, nr_scanned);
2441f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
2442497a6c1bSJohannes Weiner 	__count_vm_events(PGSCAN_ANON + file, nr_scanned);
2443497a6c1bSJohannes Weiner 
24446168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
2445d563c050SHillf Danton 
2446d563c050SHillf Danton 	if (nr_taken == 0)
244766635629SMel Gorman 		return 0;
2448b35ea17bSKOSAKI Motohiro 
2449013339dfSShakeel Butt 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
2450c661b078SAndy Whitcroft 
24516168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2452497a6c1bSJohannes Weiner 	move_pages_to_lru(lruvec, &page_list);
2453497a6c1bSJohannes Weiner 
2454497a6c1bSJohannes Weiner 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2455f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
2456b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
2457f46b7912SKirill Tkhai 		__count_vm_events(item, nr_reclaimed);
2458f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
2459497a6c1bSJohannes Weiner 	__count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
24606168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
24613f79768fSHugh Dickins 
246275cc3c91SAlex Shi 	lru_note_cost(lruvec, file, stat.nr_pageout);
2463747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
24642d4894b5SMel Gorman 	free_unref_page_list(&page_list);
2465e11da5b4SMel Gorman 
246692df3a72SMel Gorman 	/*
24671c610d5fSAndrey Ryabinin 	 * If dirty pages are scanned that are not queued for IO, it
24681c610d5fSAndrey Ryabinin 	 * implies that flushers are not doing their job. This can
24691c610d5fSAndrey Ryabinin 	 * happen when memory pressure pushes dirty pages to the end of
24701c610d5fSAndrey Ryabinin 	 * the LRU before the dirty limits are breached and the dirty
24711c610d5fSAndrey Ryabinin 	 * data has expired. It can also happen when the proportion of
24721c610d5fSAndrey Ryabinin 	 * dirty pages grows not through writes but through memory
24731c610d5fSAndrey Ryabinin 	 * pressure reclaiming all the clean cache. And in some cases,
24741c610d5fSAndrey Ryabinin 	 * the flushers simply cannot keep up with the allocation
24751c610d5fSAndrey Ryabinin 	 * rate. Nudge the flusher threads in case they are asleep.
24761c610d5fSAndrey Ryabinin 	 */
24771c610d5fSAndrey Ryabinin 	if (stat.nr_unqueued_dirty == nr_taken)
24781c610d5fSAndrey Ryabinin 		wakeup_flusher_threads(WB_REASON_VMSCAN);
24791c610d5fSAndrey Ryabinin 
2480d108c772SAndrey Ryabinin 	sc->nr.dirty += stat.nr_dirty;
2481d108c772SAndrey Ryabinin 	sc->nr.congested += stat.nr_congested;
2482d108c772SAndrey Ryabinin 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2483d108c772SAndrey Ryabinin 	sc->nr.writeback += stat.nr_writeback;
2484d108c772SAndrey Ryabinin 	sc->nr.immediate += stat.nr_immediate;
2485d108c772SAndrey Ryabinin 	sc->nr.taken += nr_taken;
2486d108c772SAndrey Ryabinin 	if (file)
2487d108c772SAndrey Ryabinin 		sc->nr.file_taken += nr_taken;
24888e950282SMel Gorman 
2489599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2490d51d1e64SSteven Rostedt 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
249105ff5137SAndrew Morton 	return nr_reclaimed;
24921da177e4SLinus Torvalds }
24931da177e4SLinus Torvalds 
249415b44736SHugh Dickins /*
249507f67a8dSMatthew Wilcox (Oracle)  * shrink_active_list() moves folios from the active LRU to the inactive LRU.
249615b44736SHugh Dickins  *
249707f67a8dSMatthew Wilcox (Oracle)  * We move them the other way if the folio is referenced by one or more
249815b44736SHugh Dickins  * processes.
249915b44736SHugh Dickins  *
250007f67a8dSMatthew Wilcox (Oracle)  * If the folios are mostly unmapped, the processing is fast and it is
250115b44736SHugh Dickins  * appropriate to hold lru_lock across the whole operation.  But if
250207f67a8dSMatthew Wilcox (Oracle)  * the folios are mapped, the processing is slow (folio_referenced()), so
250307f67a8dSMatthew Wilcox (Oracle)  * we should drop lru_lock around each folio.  It's impossible to balance
250407f67a8dSMatthew Wilcox (Oracle)  * this, so instead we remove the folios from the LRU while processing them.
250507f67a8dSMatthew Wilcox (Oracle)  * It is safe to rely on the active flag against the non-LRU folios in here
250607f67a8dSMatthew Wilcox (Oracle)  * because nobody will play with that bit on a non-LRU folio.
250715b44736SHugh Dickins  *
250807f67a8dSMatthew Wilcox (Oracle)  * The downside is that we have to touch folio->_refcount against each folio.
250907f67a8dSMatthew Wilcox (Oracle)  * But we had to alter folio->flags anyway.
251015b44736SHugh Dickins  */
2511f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
25121a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
2513f16015fbSJohannes Weiner 			       struct scan_control *sc,
25149e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
25151cfb419bSKAMEZAWA Hiroyuki {
251644c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
2517f626012dSHugh Dickins 	unsigned long nr_scanned;
25186fe6b7e3SWu Fengguang 	unsigned long vm_flags;
251907f67a8dSMatthew Wilcox (Oracle) 	LIST_HEAD(l_hold);	/* The folios which were snipped off */
25208cab4754SWu Fengguang 	LIST_HEAD(l_active);
2521b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
25229d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
25239d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
25243cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
2525599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
25261cfb419bSKAMEZAWA Hiroyuki 
25271da177e4SLinus Torvalds 	lru_add_drain();
2528f80c0673SMinchan Kim 
25296168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2530925b7673SJohannes Weiner 
25315dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2532a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
253389b5fae5SJohannes Weiner 
2534599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
25351cfb419bSKAMEZAWA Hiroyuki 
2536912c0572SShakeel Butt 	if (!cgroup_reclaim(sc))
2537599d0c95SMel Gorman 		__count_vm_events(PGREFILL, nr_scanned);
25382fa2690cSYafang Shao 	__count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
25399d5e6a9fSHugh Dickins 
25406168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
25411da177e4SLinus Torvalds 
25421da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
2543b3ac0413SMatthew Wilcox (Oracle) 		struct folio *folio;
2544b3ac0413SMatthew Wilcox (Oracle) 
25451da177e4SLinus Torvalds 		cond_resched();
2546b3ac0413SMatthew Wilcox (Oracle) 		folio = lru_to_folio(&l_hold);
2547b3ac0413SMatthew Wilcox (Oracle) 		list_del(&folio->lru);
25487e9cd484SRik van Riel 
254907f67a8dSMatthew Wilcox (Oracle) 		if (unlikely(!folio_evictable(folio))) {
255007f67a8dSMatthew Wilcox (Oracle) 			folio_putback_lru(folio);
2551894bc310SLee Schermerhorn 			continue;
2552894bc310SLee Schermerhorn 		}
2553894bc310SLee Schermerhorn 
2554cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
255536a3b14bSMatthew Wilcox (Oracle) 			if (folio_test_private(folio) && folio_trylock(folio)) {
255636a3b14bSMatthew Wilcox (Oracle) 				if (folio_test_private(folio))
255707f67a8dSMatthew Wilcox (Oracle) 					filemap_release_folio(folio, 0);
255807f67a8dSMatthew Wilcox (Oracle) 				folio_unlock(folio);
2559cc715d99SMel Gorman 			}
2560cc715d99SMel Gorman 		}
2561cc715d99SMel Gorman 
25626d4675e6SMinchan Kim 		/* Referenced or rmap lock contention: rotate */
2563b3ac0413SMatthew Wilcox (Oracle) 		if (folio_referenced(folio, 0, sc->target_mem_cgroup,
25646d4675e6SMinchan Kim 				     &vm_flags) != 0) {
25658cab4754SWu Fengguang 			/*
256607f67a8dSMatthew Wilcox (Oracle) 			 * Identify referenced, file-backed active folios and
25678cab4754SWu Fengguang 			 * give them one more trip around the active list. So
25688cab4754SWu Fengguang 			 * that executable code get better chances to stay in
256907f67a8dSMatthew Wilcox (Oracle) 			 * memory under moderate memory pressure.  Anon folios
25708cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
257107f67a8dSMatthew Wilcox (Oracle) 			 * IO, plus JVM can create lots of anon VM_EXEC folios,
25728cab4754SWu Fengguang 			 * so we ignore them here.
25738cab4754SWu Fengguang 			 */
257407f67a8dSMatthew Wilcox (Oracle) 			if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio)) {
257507f67a8dSMatthew Wilcox (Oracle) 				nr_rotated += folio_nr_pages(folio);
257607f67a8dSMatthew Wilcox (Oracle) 				list_add(&folio->lru, &l_active);
25778cab4754SWu Fengguang 				continue;
25788cab4754SWu Fengguang 			}
25798cab4754SWu Fengguang 		}
25807e9cd484SRik van Riel 
258107f67a8dSMatthew Wilcox (Oracle) 		folio_clear_active(folio);	/* we are de-activating */
258207f67a8dSMatthew Wilcox (Oracle) 		folio_set_workingset(folio);
258307f67a8dSMatthew Wilcox (Oracle) 		list_add(&folio->lru, &l_inactive);
25841da177e4SLinus Torvalds 	}
25851da177e4SLinus Torvalds 
2586b555749aSAndrew Morton 	/*
258707f67a8dSMatthew Wilcox (Oracle) 	 * Move folios back to the lru list.
2588b555749aSAndrew Morton 	 */
25896168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2590556adecbSRik van Riel 
2591a222f341SKirill Tkhai 	nr_activate = move_pages_to_lru(lruvec, &l_active);
2592a222f341SKirill Tkhai 	nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
259307f67a8dSMatthew Wilcox (Oracle) 	/* Keep all free folios in l_active list */
2594f372d89eSKirill Tkhai 	list_splice(&l_inactive, &l_active);
25959851ac13SKirill Tkhai 
25969851ac13SKirill Tkhai 	__count_vm_events(PGDEACTIVATE, nr_deactivate);
25979851ac13SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
25989851ac13SKirill Tkhai 
2599599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
26006168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
26012bcf8879SHugh Dickins 
2602f372d89eSKirill Tkhai 	mem_cgroup_uncharge_list(&l_active);
2603f372d89eSKirill Tkhai 	free_unref_page_list(&l_active);
26049d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
26059d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
26061da177e4SLinus Torvalds }
26071da177e4SLinus Torvalds 
26081fe47c0bSMiaohe Lin static unsigned int reclaim_page_list(struct list_head *page_list,
26091fe47c0bSMiaohe Lin 				      struct pglist_data *pgdat)
26101a4e58ccSMinchan Kim {
26111a4e58ccSMinchan Kim 	struct reclaim_stat dummy_stat;
26121fe47c0bSMiaohe Lin 	unsigned int nr_reclaimed;
26131fe47c0bSMiaohe Lin 	struct folio *folio;
26141a4e58ccSMinchan Kim 	struct scan_control sc = {
26151a4e58ccSMinchan Kim 		.gfp_mask = GFP_KERNEL,
26161a4e58ccSMinchan Kim 		.may_writepage = 1,
26171a4e58ccSMinchan Kim 		.may_unmap = 1,
26181a4e58ccSMinchan Kim 		.may_swap = 1,
261926aa2d19SDave Hansen 		.no_demotion = 1,
26201a4e58ccSMinchan Kim 	};
26211a4e58ccSMinchan Kim 
26221fe47c0bSMiaohe Lin 	nr_reclaimed = shrink_page_list(page_list, pgdat, &sc, &dummy_stat, false);
26231fe47c0bSMiaohe Lin 	while (!list_empty(page_list)) {
26241fe47c0bSMiaohe Lin 		folio = lru_to_folio(page_list);
26251fe47c0bSMiaohe Lin 		list_del(&folio->lru);
26261fe47c0bSMiaohe Lin 		folio_putback_lru(folio);
26271fe47c0bSMiaohe Lin 	}
26281fe47c0bSMiaohe Lin 
26291fe47c0bSMiaohe Lin 	return nr_reclaimed;
26301fe47c0bSMiaohe Lin }
26311fe47c0bSMiaohe Lin 
2632a83f0551SMatthew Wilcox (Oracle) unsigned long reclaim_pages(struct list_head *folio_list)
26331fe47c0bSMiaohe Lin {
2634ed657e55SWei Yang 	int nid;
26351fe47c0bSMiaohe Lin 	unsigned int nr_reclaimed = 0;
2636a83f0551SMatthew Wilcox (Oracle) 	LIST_HEAD(node_folio_list);
26371fe47c0bSMiaohe Lin 	unsigned int noreclaim_flag;
26381fe47c0bSMiaohe Lin 
2639a83f0551SMatthew Wilcox (Oracle) 	if (list_empty(folio_list))
26401ae65e27SWei Yang 		return nr_reclaimed;
26411ae65e27SWei Yang 
26422d2b8d2bSYu Zhao 	noreclaim_flag = memalloc_noreclaim_save();
26432d2b8d2bSYu Zhao 
2644a83f0551SMatthew Wilcox (Oracle) 	nid = folio_nid(lru_to_folio(folio_list));
26451ae65e27SWei Yang 	do {
2646a83f0551SMatthew Wilcox (Oracle) 		struct folio *folio = lru_to_folio(folio_list);
26471a4e58ccSMinchan Kim 
2648a83f0551SMatthew Wilcox (Oracle) 		if (nid == folio_nid(folio)) {
2649a83f0551SMatthew Wilcox (Oracle) 			folio_clear_active(folio);
2650a83f0551SMatthew Wilcox (Oracle) 			list_move(&folio->lru, &node_folio_list);
26511a4e58ccSMinchan Kim 			continue;
26521a4e58ccSMinchan Kim 		}
26531a4e58ccSMinchan Kim 
2654a83f0551SMatthew Wilcox (Oracle) 		nr_reclaimed += reclaim_page_list(&node_folio_list, NODE_DATA(nid));
2655a83f0551SMatthew Wilcox (Oracle) 		nid = folio_nid(lru_to_folio(folio_list));
2656a83f0551SMatthew Wilcox (Oracle) 	} while (!list_empty(folio_list));
26571a4e58ccSMinchan Kim 
2658a83f0551SMatthew Wilcox (Oracle) 	nr_reclaimed += reclaim_page_list(&node_folio_list, NODE_DATA(nid));
26591a4e58ccSMinchan Kim 
26602d2b8d2bSYu Zhao 	memalloc_noreclaim_restore(noreclaim_flag);
26612d2b8d2bSYu Zhao 
26621a4e58ccSMinchan Kim 	return nr_reclaimed;
26631a4e58ccSMinchan Kim }
26641a4e58ccSMinchan Kim 
2665b91ac374SJohannes Weiner static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2666b91ac374SJohannes Weiner 				 struct lruvec *lruvec, struct scan_control *sc)
2667b91ac374SJohannes Weiner {
2668b91ac374SJohannes Weiner 	if (is_active_lru(lru)) {
2669b91ac374SJohannes Weiner 		if (sc->may_deactivate & (1 << is_file_lru(lru)))
2670b91ac374SJohannes Weiner 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2671b91ac374SJohannes Weiner 		else
2672b91ac374SJohannes Weiner 			sc->skipped_deactivate = 1;
2673b91ac374SJohannes Weiner 		return 0;
2674b91ac374SJohannes Weiner 	}
2675b91ac374SJohannes Weiner 
2676b91ac374SJohannes Weiner 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2677b91ac374SJohannes Weiner }
2678b91ac374SJohannes Weiner 
267959dc76b0SRik van Riel /*
268059dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
268159dc76b0SRik van Riel  * to do too much work.
268214797e23SKOSAKI Motohiro  *
268359dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
268459dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
268559dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
268659dc76b0SRik van Riel  *
268759dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
268859dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
268959dc76b0SRik van Riel  *
26902a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
26912a2e4885SJohannes Weiner  *
269259dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
26933a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
269459dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
269559dc76b0SRik van Riel  *
269659dc76b0SRik van Riel  * total     target    max
269759dc76b0SRik van Riel  * memory    ratio     inactive
269859dc76b0SRik van Riel  * -------------------------------------
269959dc76b0SRik van Riel  *   10MB       1         5MB
270059dc76b0SRik van Riel  *  100MB       1        50MB
270159dc76b0SRik van Riel  *    1GB       3       250MB
270259dc76b0SRik van Riel  *   10GB      10       0.9GB
270359dc76b0SRik van Riel  *  100GB      31         3GB
270459dc76b0SRik van Riel  *    1TB     101        10GB
270559dc76b0SRik van Riel  *   10TB     320        32GB
270614797e23SKOSAKI Motohiro  */
2707b91ac374SJohannes Weiner static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
270814797e23SKOSAKI Motohiro {
2709b91ac374SJohannes Weiner 	enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
27102a2e4885SJohannes Weiner 	unsigned long inactive, active;
27112a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
271259dc76b0SRik van Riel 	unsigned long gb;
271359dc76b0SRik van Riel 
2714b91ac374SJohannes Weiner 	inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2715b91ac374SJohannes Weiner 	active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2716f8d1a311SMel Gorman 
271759dc76b0SRik van Riel 	gb = (inactive + active) >> (30 - PAGE_SHIFT);
27184002570cSJoonsoo Kim 	if (gb)
271959dc76b0SRik van Riel 		inactive_ratio = int_sqrt(10 * gb);
2720b39415b2SRik van Riel 	else
272159dc76b0SRik van Riel 		inactive_ratio = 1;
2722fd538803SMichal Hocko 
272359dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2724b39415b2SRik van Riel }
2725b39415b2SRik van Riel 
27269a265114SJohannes Weiner enum scan_balance {
27279a265114SJohannes Weiner 	SCAN_EQUAL,
27289a265114SJohannes Weiner 	SCAN_FRACT,
27299a265114SJohannes Weiner 	SCAN_ANON,
27309a265114SJohannes Weiner 	SCAN_FILE,
27319a265114SJohannes Weiner };
27329a265114SJohannes Weiner 
2733f1e1a7beSYu Zhao static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2734f1e1a7beSYu Zhao {
2735f1e1a7beSYu Zhao 	unsigned long file;
2736f1e1a7beSYu Zhao 	struct lruvec *target_lruvec;
2737f1e1a7beSYu Zhao 
2738*ac35a490SYu Zhao 	if (lru_gen_enabled())
2739*ac35a490SYu Zhao 		return;
2740*ac35a490SYu Zhao 
2741f1e1a7beSYu Zhao 	target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2742f1e1a7beSYu Zhao 
2743f1e1a7beSYu Zhao 	/*
2744f1e1a7beSYu Zhao 	 * Flush the memory cgroup stats, so that we read accurate per-memcg
2745f1e1a7beSYu Zhao 	 * lruvec stats for heuristics.
2746f1e1a7beSYu Zhao 	 */
2747f1e1a7beSYu Zhao 	mem_cgroup_flush_stats();
2748f1e1a7beSYu Zhao 
2749f1e1a7beSYu Zhao 	/*
2750f1e1a7beSYu Zhao 	 * Determine the scan balance between anon and file LRUs.
2751f1e1a7beSYu Zhao 	 */
2752f1e1a7beSYu Zhao 	spin_lock_irq(&target_lruvec->lru_lock);
2753f1e1a7beSYu Zhao 	sc->anon_cost = target_lruvec->anon_cost;
2754f1e1a7beSYu Zhao 	sc->file_cost = target_lruvec->file_cost;
2755f1e1a7beSYu Zhao 	spin_unlock_irq(&target_lruvec->lru_lock);
2756f1e1a7beSYu Zhao 
2757f1e1a7beSYu Zhao 	/*
2758f1e1a7beSYu Zhao 	 * Target desirable inactive:active list ratios for the anon
2759f1e1a7beSYu Zhao 	 * and file LRU lists.
2760f1e1a7beSYu Zhao 	 */
2761f1e1a7beSYu Zhao 	if (!sc->force_deactivate) {
2762f1e1a7beSYu Zhao 		unsigned long refaults;
2763f1e1a7beSYu Zhao 
2764f1e1a7beSYu Zhao 		/*
2765f1e1a7beSYu Zhao 		 * When refaults are being observed, it means a new
2766f1e1a7beSYu Zhao 		 * workingset is being established. Deactivate to get
2767f1e1a7beSYu Zhao 		 * rid of any stale active pages quickly.
2768f1e1a7beSYu Zhao 		 */
2769f1e1a7beSYu Zhao 		refaults = lruvec_page_state(target_lruvec,
2770f1e1a7beSYu Zhao 				WORKINGSET_ACTIVATE_ANON);
2771f1e1a7beSYu Zhao 		if (refaults != target_lruvec->refaults[WORKINGSET_ANON] ||
2772f1e1a7beSYu Zhao 			inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2773f1e1a7beSYu Zhao 			sc->may_deactivate |= DEACTIVATE_ANON;
2774f1e1a7beSYu Zhao 		else
2775f1e1a7beSYu Zhao 			sc->may_deactivate &= ~DEACTIVATE_ANON;
2776f1e1a7beSYu Zhao 
2777f1e1a7beSYu Zhao 		refaults = lruvec_page_state(target_lruvec,
2778f1e1a7beSYu Zhao 				WORKINGSET_ACTIVATE_FILE);
2779f1e1a7beSYu Zhao 		if (refaults != target_lruvec->refaults[WORKINGSET_FILE] ||
2780f1e1a7beSYu Zhao 		    inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2781f1e1a7beSYu Zhao 			sc->may_deactivate |= DEACTIVATE_FILE;
2782f1e1a7beSYu Zhao 		else
2783f1e1a7beSYu Zhao 			sc->may_deactivate &= ~DEACTIVATE_FILE;
2784f1e1a7beSYu Zhao 	} else
2785f1e1a7beSYu Zhao 		sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2786f1e1a7beSYu Zhao 
2787f1e1a7beSYu Zhao 	/*
2788f1e1a7beSYu Zhao 	 * If we have plenty of inactive file pages that aren't
2789f1e1a7beSYu Zhao 	 * thrashing, try to reclaim those first before touching
2790f1e1a7beSYu Zhao 	 * anonymous pages.
2791f1e1a7beSYu Zhao 	 */
2792f1e1a7beSYu Zhao 	file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2793f1e1a7beSYu Zhao 	if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2794f1e1a7beSYu Zhao 		sc->cache_trim_mode = 1;
2795f1e1a7beSYu Zhao 	else
2796f1e1a7beSYu Zhao 		sc->cache_trim_mode = 0;
2797f1e1a7beSYu Zhao 
2798f1e1a7beSYu Zhao 	/*
2799f1e1a7beSYu Zhao 	 * Prevent the reclaimer from falling into the cache trap: as
2800f1e1a7beSYu Zhao 	 * cache pages start out inactive, every cache fault will tip
2801f1e1a7beSYu Zhao 	 * the scan balance towards the file LRU.  And as the file LRU
2802f1e1a7beSYu Zhao 	 * shrinks, so does the window for rotation from references.
2803f1e1a7beSYu Zhao 	 * This means we have a runaway feedback loop where a tiny
2804f1e1a7beSYu Zhao 	 * thrashing file LRU becomes infinitely more attractive than
2805f1e1a7beSYu Zhao 	 * anon pages.  Try to detect this based on file LRU size.
2806f1e1a7beSYu Zhao 	 */
2807f1e1a7beSYu Zhao 	if (!cgroup_reclaim(sc)) {
2808f1e1a7beSYu Zhao 		unsigned long total_high_wmark = 0;
2809f1e1a7beSYu Zhao 		unsigned long free, anon;
2810f1e1a7beSYu Zhao 		int z;
2811f1e1a7beSYu Zhao 
2812f1e1a7beSYu Zhao 		free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2813f1e1a7beSYu Zhao 		file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2814f1e1a7beSYu Zhao 			   node_page_state(pgdat, NR_INACTIVE_FILE);
2815f1e1a7beSYu Zhao 
2816f1e1a7beSYu Zhao 		for (z = 0; z < MAX_NR_ZONES; z++) {
2817f1e1a7beSYu Zhao 			struct zone *zone = &pgdat->node_zones[z];
2818f1e1a7beSYu Zhao 
2819f1e1a7beSYu Zhao 			if (!managed_zone(zone))
2820f1e1a7beSYu Zhao 				continue;
2821f1e1a7beSYu Zhao 
2822f1e1a7beSYu Zhao 			total_high_wmark += high_wmark_pages(zone);
2823f1e1a7beSYu Zhao 		}
2824f1e1a7beSYu Zhao 
2825f1e1a7beSYu Zhao 		/*
2826f1e1a7beSYu Zhao 		 * Consider anon: if that's low too, this isn't a
2827f1e1a7beSYu Zhao 		 * runaway file reclaim problem, but rather just
2828f1e1a7beSYu Zhao 		 * extreme pressure. Reclaim as per usual then.
2829f1e1a7beSYu Zhao 		 */
2830f1e1a7beSYu Zhao 		anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2831f1e1a7beSYu Zhao 
2832f1e1a7beSYu Zhao 		sc->file_is_tiny =
2833f1e1a7beSYu Zhao 			file + free <= total_high_wmark &&
2834f1e1a7beSYu Zhao 			!(sc->may_deactivate & DEACTIVATE_ANON) &&
2835f1e1a7beSYu Zhao 			anon >> sc->priority;
2836f1e1a7beSYu Zhao 	}
2837f1e1a7beSYu Zhao }
2838f1e1a7beSYu Zhao 
28391da177e4SLinus Torvalds /*
28404f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
284102e458d8SMiaohe Lin  * scanned.
28424f98a2feSRik van Riel  *
2843be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2844be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
28454f98a2feSRik van Riel  */
2846afaf07a6SJohannes Weiner static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2847afaf07a6SJohannes Weiner 			   unsigned long *nr)
28484f98a2feSRik van Riel {
2849a2a36488SKeith Busch 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2850afaf07a6SJohannes Weiner 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2851d483a5ddSJohannes Weiner 	unsigned long anon_cost, file_cost, total_cost;
285233377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
2853ed017373SYu Zhao 	u64 fraction[ANON_AND_FILE];
28549a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
28559a265114SJohannes Weiner 	enum scan_balance scan_balance;
28569a265114SJohannes Weiner 	unsigned long ap, fp;
28579a265114SJohannes Weiner 	enum lru_list lru;
285876a33fc3SShaohua Li 
285976a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2860a2a36488SKeith Busch 	if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
28619a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
286276a33fc3SShaohua Li 		goto out;
286376a33fc3SShaohua Li 	}
28644f98a2feSRik van Riel 
286510316b31SJohannes Weiner 	/*
286610316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
286710316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
286810316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
286910316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
287010316b31SJohannes Weiner 	 * too expensive.
287110316b31SJohannes Weiner 	 */
2872b5ead35eSJohannes Weiner 	if (cgroup_reclaim(sc) && !swappiness) {
28739a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
287410316b31SJohannes Weiner 		goto out;
287510316b31SJohannes Weiner 	}
287610316b31SJohannes Weiner 
287710316b31SJohannes Weiner 	/*
287810316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
287910316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
288010316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
288110316b31SJohannes Weiner 	 */
288202695175SJohannes Weiner 	if (!sc->priority && swappiness) {
28839a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
288410316b31SJohannes Weiner 		goto out;
288510316b31SJohannes Weiner 	}
288610316b31SJohannes Weiner 
288711d16c25SJohannes Weiner 	/*
288853138ceaSJohannes Weiner 	 * If the system is almost out of file pages, force-scan anon.
288962376251SJohannes Weiner 	 */
2890b91ac374SJohannes Weiner 	if (sc->file_is_tiny) {
289162376251SJohannes Weiner 		scan_balance = SCAN_ANON;
289262376251SJohannes Weiner 		goto out;
289362376251SJohannes Weiner 	}
289462376251SJohannes Weiner 
289562376251SJohannes Weiner 	/*
2896b91ac374SJohannes Weiner 	 * If there is enough inactive page cache, we do not reclaim
2897b91ac374SJohannes Weiner 	 * anything from the anonymous working right now.
2898e9868505SRik van Riel 	 */
2899b91ac374SJohannes Weiner 	if (sc->cache_trim_mode) {
29009a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2901e9868505SRik van Riel 		goto out;
29024f98a2feSRik van Riel 	}
29034f98a2feSRik van Riel 
29049a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
29054f98a2feSRik van Riel 	/*
2906314b57fbSJohannes Weiner 	 * Calculate the pressure balance between anon and file pages.
2907314b57fbSJohannes Weiner 	 *
2908314b57fbSJohannes Weiner 	 * The amount of pressure we put on each LRU is inversely
2909314b57fbSJohannes Weiner 	 * proportional to the cost of reclaiming each list, as
2910314b57fbSJohannes Weiner 	 * determined by the share of pages that are refaulting, times
2911314b57fbSJohannes Weiner 	 * the relative IO cost of bringing back a swapped out
2912314b57fbSJohannes Weiner 	 * anonymous page vs reloading a filesystem page (swappiness).
2913314b57fbSJohannes Weiner 	 *
2914d483a5ddSJohannes Weiner 	 * Although we limit that influence to ensure no list gets
2915d483a5ddSJohannes Weiner 	 * left behind completely: at least a third of the pressure is
2916d483a5ddSJohannes Weiner 	 * applied, before swappiness.
2917d483a5ddSJohannes Weiner 	 *
2918314b57fbSJohannes Weiner 	 * With swappiness at 100, anon and file have equal IO cost.
291958c37f6eSKOSAKI Motohiro 	 */
2920d483a5ddSJohannes Weiner 	total_cost = sc->anon_cost + sc->file_cost;
2921d483a5ddSJohannes Weiner 	anon_cost = total_cost + sc->anon_cost;
2922d483a5ddSJohannes Weiner 	file_cost = total_cost + sc->file_cost;
2923d483a5ddSJohannes Weiner 	total_cost = anon_cost + file_cost;
292458c37f6eSKOSAKI Motohiro 
2925d483a5ddSJohannes Weiner 	ap = swappiness * (total_cost + 1);
2926d483a5ddSJohannes Weiner 	ap /= anon_cost + 1;
29274f98a2feSRik van Riel 
2928d483a5ddSJohannes Weiner 	fp = (200 - swappiness) * (total_cost + 1);
2929d483a5ddSJohannes Weiner 	fp /= file_cost + 1;
29304f98a2feSRik van Riel 
293176a33fc3SShaohua Li 	fraction[0] = ap;
293276a33fc3SShaohua Li 	fraction[1] = fp;
2933a4fe1631SJohannes Weiner 	denominator = ap + fp;
293476a33fc3SShaohua Li out:
29354111304dSHugh Dickins 	for_each_evictable_lru(lru) {
29364111304dSHugh Dickins 		int file = is_file_lru(lru);
29379783aa99SChris Down 		unsigned long lruvec_size;
2938f56ce412SJohannes Weiner 		unsigned long low, min;
293976a33fc3SShaohua Li 		unsigned long scan;
294076a33fc3SShaohua Li 
29419783aa99SChris Down 		lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2942f56ce412SJohannes Weiner 		mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2943f56ce412SJohannes Weiner 				      &min, &low);
29449783aa99SChris Down 
2945f56ce412SJohannes Weiner 		if (min || low) {
29469783aa99SChris Down 			/*
29479783aa99SChris Down 			 * Scale a cgroup's reclaim pressure by proportioning
29489783aa99SChris Down 			 * its current usage to its memory.low or memory.min
29499783aa99SChris Down 			 * setting.
29509783aa99SChris Down 			 *
29519783aa99SChris Down 			 * This is important, as otherwise scanning aggression
29529783aa99SChris Down 			 * becomes extremely binary -- from nothing as we
29539783aa99SChris Down 			 * approach the memory protection threshold, to totally
29549783aa99SChris Down 			 * nominal as we exceed it.  This results in requiring
29559783aa99SChris Down 			 * setting extremely liberal protection thresholds. It
29569783aa99SChris Down 			 * also means we simply get no protection at all if we
29579783aa99SChris Down 			 * set it too low, which is not ideal.
29581bc63fb1SChris Down 			 *
29591bc63fb1SChris Down 			 * If there is any protection in place, we reduce scan
29601bc63fb1SChris Down 			 * pressure by how much of the total memory used is
29611bc63fb1SChris Down 			 * within protection thresholds.
29629783aa99SChris Down 			 *
29639de7ca46SChris Down 			 * There is one special case: in the first reclaim pass,
29649de7ca46SChris Down 			 * we skip over all groups that are within their low
29659de7ca46SChris Down 			 * protection. If that fails to reclaim enough pages to
29669de7ca46SChris Down 			 * satisfy the reclaim goal, we come back and override
29679de7ca46SChris Down 			 * the best-effort low protection. However, we still
29689de7ca46SChris Down 			 * ideally want to honor how well-behaved groups are in
29699de7ca46SChris Down 			 * that case instead of simply punishing them all
29709de7ca46SChris Down 			 * equally. As such, we reclaim them based on how much
29711bc63fb1SChris Down 			 * memory they are using, reducing the scan pressure
29721bc63fb1SChris Down 			 * again by how much of the total memory used is under
29731bc63fb1SChris Down 			 * hard protection.
29749783aa99SChris Down 			 */
29751bc63fb1SChris Down 			unsigned long cgroup_size = mem_cgroup_size(memcg);
2976f56ce412SJohannes Weiner 			unsigned long protection;
2977f56ce412SJohannes Weiner 
2978f56ce412SJohannes Weiner 			/* memory.low scaling, make sure we retry before OOM */
2979f56ce412SJohannes Weiner 			if (!sc->memcg_low_reclaim && low > min) {
2980f56ce412SJohannes Weiner 				protection = low;
2981f56ce412SJohannes Weiner 				sc->memcg_low_skipped = 1;
2982f56ce412SJohannes Weiner 			} else {
2983f56ce412SJohannes Weiner 				protection = min;
2984f56ce412SJohannes Weiner 			}
29851bc63fb1SChris Down 
29861bc63fb1SChris Down 			/* Avoid TOCTOU with earlier protection check */
29871bc63fb1SChris Down 			cgroup_size = max(cgroup_size, protection);
29881bc63fb1SChris Down 
29891bc63fb1SChris Down 			scan = lruvec_size - lruvec_size * protection /
299032d4f4b7SRik van Riel 				(cgroup_size + 1);
29919783aa99SChris Down 
29929783aa99SChris Down 			/*
29931bc63fb1SChris Down 			 * Minimally target SWAP_CLUSTER_MAX pages to keep
299455b65a57SEthon Paul 			 * reclaim moving forwards, avoiding decrementing
29959de7ca46SChris Down 			 * sc->priority further than desirable.
29969783aa99SChris Down 			 */
29971bc63fb1SChris Down 			scan = max(scan, SWAP_CLUSTER_MAX);
29989783aa99SChris Down 		} else {
29999783aa99SChris Down 			scan = lruvec_size;
30009783aa99SChris Down 		}
30019783aa99SChris Down 
30029783aa99SChris Down 		scan >>= sc->priority;
30039783aa99SChris Down 
3004688035f7SJohannes Weiner 		/*
3005688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
3006688035f7SJohannes Weiner 		 * scrape out the remaining cache.
3007688035f7SJohannes Weiner 		 */
3008688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
30099783aa99SChris Down 			scan = min(lruvec_size, SWAP_CLUSTER_MAX);
30109a265114SJohannes Weiner 
30119a265114SJohannes Weiner 		switch (scan_balance) {
30129a265114SJohannes Weiner 		case SCAN_EQUAL:
30139a265114SJohannes Weiner 			/* Scan lists relative to size */
30149a265114SJohannes Weiner 			break;
30159a265114SJohannes Weiner 		case SCAN_FRACT:
30169a265114SJohannes Weiner 			/*
30179a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
30189a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
301976073c64SGavin Shan 			 * Make sure we don't miss the last page on
302076073c64SGavin Shan 			 * the offlined memory cgroups because of a
302176073c64SGavin Shan 			 * round-off error.
30229a265114SJohannes Weiner 			 */
302376073c64SGavin Shan 			scan = mem_cgroup_online(memcg) ?
302476073c64SGavin Shan 			       div64_u64(scan * fraction[file], denominator) :
302576073c64SGavin Shan 			       DIV64_U64_ROUND_UP(scan * fraction[file],
30266f04f48dSSuleiman Souhlal 						  denominator);
30279a265114SJohannes Weiner 			break;
30289a265114SJohannes Weiner 		case SCAN_FILE:
30299a265114SJohannes Weiner 		case SCAN_ANON:
30309a265114SJohannes Weiner 			/* Scan one type exclusively */
3031e072bff6SMateusz Nosek 			if ((scan_balance == SCAN_FILE) != file)
30329a265114SJohannes Weiner 				scan = 0;
30339a265114SJohannes Weiner 			break;
30349a265114SJohannes Weiner 		default:
30359a265114SJohannes Weiner 			/* Look ma, no brain */
30369a265114SJohannes Weiner 			BUG();
30379a265114SJohannes Weiner 		}
30386b4f7799SJohannes Weiner 
30394111304dSHugh Dickins 		nr[lru] = scan;
304076a33fc3SShaohua Li 	}
30416e08a369SWu Fengguang }
30424f98a2feSRik van Riel 
30432f368a9fSDave Hansen /*
30442f368a9fSDave Hansen  * Anonymous LRU management is a waste if there is
30452f368a9fSDave Hansen  * ultimately no way to reclaim the memory.
30462f368a9fSDave Hansen  */
30472f368a9fSDave Hansen static bool can_age_anon_pages(struct pglist_data *pgdat,
30482f368a9fSDave Hansen 			       struct scan_control *sc)
30492f368a9fSDave Hansen {
30502f368a9fSDave Hansen 	/* Aging the anon LRU is valuable if swap is present: */
30512f368a9fSDave Hansen 	if (total_swap_pages > 0)
30522f368a9fSDave Hansen 		return true;
30532f368a9fSDave Hansen 
30542f368a9fSDave Hansen 	/* Also valuable if anon pages can be demoted: */
30552f368a9fSDave Hansen 	return can_demote(pgdat->node_id, sc);
30562f368a9fSDave Hansen }
30572f368a9fSDave Hansen 
3058ec1c86b2SYu Zhao #ifdef CONFIG_LRU_GEN
3059ec1c86b2SYu Zhao 
3060ec1c86b2SYu Zhao /******************************************************************************
3061ec1c86b2SYu Zhao  *                          shorthand helpers
3062ec1c86b2SYu Zhao  ******************************************************************************/
3063ec1c86b2SYu Zhao 
3064*ac35a490SYu Zhao #define LRU_REFS_FLAGS	(BIT(PG_referenced) | BIT(PG_workingset))
3065*ac35a490SYu Zhao 
3066*ac35a490SYu Zhao #define DEFINE_MAX_SEQ(lruvec)						\
3067*ac35a490SYu Zhao 	unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
3068*ac35a490SYu Zhao 
3069*ac35a490SYu Zhao #define DEFINE_MIN_SEQ(lruvec)						\
3070*ac35a490SYu Zhao 	unsigned long min_seq[ANON_AND_FILE] = {			\
3071*ac35a490SYu Zhao 		READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]),	\
3072*ac35a490SYu Zhao 		READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]),	\
3073*ac35a490SYu Zhao 	}
3074*ac35a490SYu Zhao 
3075ec1c86b2SYu Zhao #define for_each_gen_type_zone(gen, type, zone)				\
3076ec1c86b2SYu Zhao 	for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++)			\
3077ec1c86b2SYu Zhao 		for ((type) = 0; (type) < ANON_AND_FILE; (type)++)	\
3078ec1c86b2SYu Zhao 			for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
3079ec1c86b2SYu Zhao 
3080ec1c86b2SYu Zhao static struct lruvec __maybe_unused *get_lruvec(struct mem_cgroup *memcg, int nid)
3081ec1c86b2SYu Zhao {
3082ec1c86b2SYu Zhao 	struct pglist_data *pgdat = NODE_DATA(nid);
3083ec1c86b2SYu Zhao 
3084ec1c86b2SYu Zhao #ifdef CONFIG_MEMCG
3085ec1c86b2SYu Zhao 	if (memcg) {
3086ec1c86b2SYu Zhao 		struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
3087ec1c86b2SYu Zhao 
3088ec1c86b2SYu Zhao 		/* for hotadd_new_pgdat() */
3089ec1c86b2SYu Zhao 		if (!lruvec->pgdat)
3090ec1c86b2SYu Zhao 			lruvec->pgdat = pgdat;
3091ec1c86b2SYu Zhao 
3092ec1c86b2SYu Zhao 		return lruvec;
3093ec1c86b2SYu Zhao 	}
3094ec1c86b2SYu Zhao #endif
3095ec1c86b2SYu Zhao 	VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3096ec1c86b2SYu Zhao 
3097ec1c86b2SYu Zhao 	return pgdat ? &pgdat->__lruvec : NULL;
3098ec1c86b2SYu Zhao }
3099ec1c86b2SYu Zhao 
3100*ac35a490SYu Zhao static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
3101*ac35a490SYu Zhao {
3102*ac35a490SYu Zhao 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3103*ac35a490SYu Zhao 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
3104*ac35a490SYu Zhao 
3105*ac35a490SYu Zhao 	if (!can_demote(pgdat->node_id, sc) &&
3106*ac35a490SYu Zhao 	    mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
3107*ac35a490SYu Zhao 		return 0;
3108*ac35a490SYu Zhao 
3109*ac35a490SYu Zhao 	return mem_cgroup_swappiness(memcg);
3110*ac35a490SYu Zhao }
3111*ac35a490SYu Zhao 
3112*ac35a490SYu Zhao static int get_nr_gens(struct lruvec *lruvec, int type)
3113*ac35a490SYu Zhao {
3114*ac35a490SYu Zhao 	return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
3115*ac35a490SYu Zhao }
3116*ac35a490SYu Zhao 
3117*ac35a490SYu Zhao static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
3118*ac35a490SYu Zhao {
3119*ac35a490SYu Zhao 	/* see the comment on lru_gen_struct */
3120*ac35a490SYu Zhao 	return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
3121*ac35a490SYu Zhao 	       get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3122*ac35a490SYu Zhao 	       get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3123*ac35a490SYu Zhao }
3124*ac35a490SYu Zhao 
3125*ac35a490SYu Zhao /******************************************************************************
3126*ac35a490SYu Zhao  *                          refault feedback loop
3127*ac35a490SYu Zhao  ******************************************************************************/
3128*ac35a490SYu Zhao 
3129*ac35a490SYu Zhao /*
3130*ac35a490SYu Zhao  * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3131*ac35a490SYu Zhao  *
3132*ac35a490SYu Zhao  * The P term is refaulted/(evicted+protected) from a tier in the generation
3133*ac35a490SYu Zhao  * currently being evicted; the I term is the exponential moving average of the
3134*ac35a490SYu Zhao  * P term over the generations previously evicted, using the smoothing factor
3135*ac35a490SYu Zhao  * 1/2; the D term isn't supported.
3136*ac35a490SYu Zhao  *
3137*ac35a490SYu Zhao  * The setpoint (SP) is always the first tier of one type; the process variable
3138*ac35a490SYu Zhao  * (PV) is either any tier of the other type or any other tier of the same
3139*ac35a490SYu Zhao  * type.
3140*ac35a490SYu Zhao  *
3141*ac35a490SYu Zhao  * The error is the difference between the SP and the PV; the correction is to
3142*ac35a490SYu Zhao  * turn off protection when SP>PV or turn on protection when SP<PV.
3143*ac35a490SYu Zhao  *
3144*ac35a490SYu Zhao  * For future optimizations:
3145*ac35a490SYu Zhao  * 1. The D term may discount the other two terms over time so that long-lived
3146*ac35a490SYu Zhao  *    generations can resist stale information.
3147*ac35a490SYu Zhao  */
3148*ac35a490SYu Zhao struct ctrl_pos {
3149*ac35a490SYu Zhao 	unsigned long refaulted;
3150*ac35a490SYu Zhao 	unsigned long total;
3151*ac35a490SYu Zhao 	int gain;
3152*ac35a490SYu Zhao };
3153*ac35a490SYu Zhao 
3154*ac35a490SYu Zhao static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3155*ac35a490SYu Zhao 			  struct ctrl_pos *pos)
3156*ac35a490SYu Zhao {
3157*ac35a490SYu Zhao 	struct lru_gen_struct *lrugen = &lruvec->lrugen;
3158*ac35a490SYu Zhao 	int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3159*ac35a490SYu Zhao 
3160*ac35a490SYu Zhao 	pos->refaulted = lrugen->avg_refaulted[type][tier] +
3161*ac35a490SYu Zhao 			 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3162*ac35a490SYu Zhao 	pos->total = lrugen->avg_total[type][tier] +
3163*ac35a490SYu Zhao 		     atomic_long_read(&lrugen->evicted[hist][type][tier]);
3164*ac35a490SYu Zhao 	if (tier)
3165*ac35a490SYu Zhao 		pos->total += lrugen->protected[hist][type][tier - 1];
3166*ac35a490SYu Zhao 	pos->gain = gain;
3167*ac35a490SYu Zhao }
3168*ac35a490SYu Zhao 
3169*ac35a490SYu Zhao static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3170*ac35a490SYu Zhao {
3171*ac35a490SYu Zhao 	int hist, tier;
3172*ac35a490SYu Zhao 	struct lru_gen_struct *lrugen = &lruvec->lrugen;
3173*ac35a490SYu Zhao 	bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3174*ac35a490SYu Zhao 	unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3175*ac35a490SYu Zhao 
3176*ac35a490SYu Zhao 	lockdep_assert_held(&lruvec->lru_lock);
3177*ac35a490SYu Zhao 
3178*ac35a490SYu Zhao 	if (!carryover && !clear)
3179*ac35a490SYu Zhao 		return;
3180*ac35a490SYu Zhao 
3181*ac35a490SYu Zhao 	hist = lru_hist_from_seq(seq);
3182*ac35a490SYu Zhao 
3183*ac35a490SYu Zhao 	for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3184*ac35a490SYu Zhao 		if (carryover) {
3185*ac35a490SYu Zhao 			unsigned long sum;
3186*ac35a490SYu Zhao 
3187*ac35a490SYu Zhao 			sum = lrugen->avg_refaulted[type][tier] +
3188*ac35a490SYu Zhao 			      atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3189*ac35a490SYu Zhao 			WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3190*ac35a490SYu Zhao 
3191*ac35a490SYu Zhao 			sum = lrugen->avg_total[type][tier] +
3192*ac35a490SYu Zhao 			      atomic_long_read(&lrugen->evicted[hist][type][tier]);
3193*ac35a490SYu Zhao 			if (tier)
3194*ac35a490SYu Zhao 				sum += lrugen->protected[hist][type][tier - 1];
3195*ac35a490SYu Zhao 			WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3196*ac35a490SYu Zhao 		}
3197*ac35a490SYu Zhao 
3198*ac35a490SYu Zhao 		if (clear) {
3199*ac35a490SYu Zhao 			atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3200*ac35a490SYu Zhao 			atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3201*ac35a490SYu Zhao 			if (tier)
3202*ac35a490SYu Zhao 				WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3203*ac35a490SYu Zhao 		}
3204*ac35a490SYu Zhao 	}
3205*ac35a490SYu Zhao }
3206*ac35a490SYu Zhao 
3207*ac35a490SYu Zhao static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3208*ac35a490SYu Zhao {
3209*ac35a490SYu Zhao 	/*
3210*ac35a490SYu Zhao 	 * Return true if the PV has a limited number of refaults or a lower
3211*ac35a490SYu Zhao 	 * refaulted/total than the SP.
3212*ac35a490SYu Zhao 	 */
3213*ac35a490SYu Zhao 	return pv->refaulted < MIN_LRU_BATCH ||
3214*ac35a490SYu Zhao 	       pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3215*ac35a490SYu Zhao 	       (sp->refaulted + 1) * pv->total * pv->gain;
3216*ac35a490SYu Zhao }
3217*ac35a490SYu Zhao 
3218*ac35a490SYu Zhao /******************************************************************************
3219*ac35a490SYu Zhao  *                          the aging
3220*ac35a490SYu Zhao  ******************************************************************************/
3221*ac35a490SYu Zhao 
3222*ac35a490SYu Zhao /* protect pages accessed multiple times through file descriptors */
3223*ac35a490SYu Zhao static int folio_inc_gen(struct lruvec *lruvec, struct folio *folio, bool reclaiming)
3224*ac35a490SYu Zhao {
3225*ac35a490SYu Zhao 	int type = folio_is_file_lru(folio);
3226*ac35a490SYu Zhao 	struct lru_gen_struct *lrugen = &lruvec->lrugen;
3227*ac35a490SYu Zhao 	int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3228*ac35a490SYu Zhao 	unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3229*ac35a490SYu Zhao 
3230*ac35a490SYu Zhao 	VM_WARN_ON_ONCE_FOLIO(!(old_flags & LRU_GEN_MASK), folio);
3231*ac35a490SYu Zhao 
3232*ac35a490SYu Zhao 	do {
3233*ac35a490SYu Zhao 		new_gen = (old_gen + 1) % MAX_NR_GENS;
3234*ac35a490SYu Zhao 
3235*ac35a490SYu Zhao 		new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3236*ac35a490SYu Zhao 		new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3237*ac35a490SYu Zhao 		/* for folio_end_writeback() */
3238*ac35a490SYu Zhao 		if (reclaiming)
3239*ac35a490SYu Zhao 			new_flags |= BIT(PG_reclaim);
3240*ac35a490SYu Zhao 	} while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3241*ac35a490SYu Zhao 
3242*ac35a490SYu Zhao 	lru_gen_update_size(lruvec, folio, old_gen, new_gen);
3243*ac35a490SYu Zhao 
3244*ac35a490SYu Zhao 	return new_gen;
3245*ac35a490SYu Zhao }
3246*ac35a490SYu Zhao 
3247*ac35a490SYu Zhao static void inc_min_seq(struct lruvec *lruvec, int type)
3248*ac35a490SYu Zhao {
3249*ac35a490SYu Zhao 	struct lru_gen_struct *lrugen = &lruvec->lrugen;
3250*ac35a490SYu Zhao 
3251*ac35a490SYu Zhao 	reset_ctrl_pos(lruvec, type, true);
3252*ac35a490SYu Zhao 	WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
3253*ac35a490SYu Zhao }
3254*ac35a490SYu Zhao 
3255*ac35a490SYu Zhao static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
3256*ac35a490SYu Zhao {
3257*ac35a490SYu Zhao 	int gen, type, zone;
3258*ac35a490SYu Zhao 	bool success = false;
3259*ac35a490SYu Zhao 	struct lru_gen_struct *lrugen = &lruvec->lrugen;
3260*ac35a490SYu Zhao 	DEFINE_MIN_SEQ(lruvec);
3261*ac35a490SYu Zhao 
3262*ac35a490SYu Zhao 	VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
3263*ac35a490SYu Zhao 
3264*ac35a490SYu Zhao 	/* find the oldest populated generation */
3265*ac35a490SYu Zhao 	for (type = !can_swap; type < ANON_AND_FILE; type++) {
3266*ac35a490SYu Zhao 		while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
3267*ac35a490SYu Zhao 			gen = lru_gen_from_seq(min_seq[type]);
3268*ac35a490SYu Zhao 
3269*ac35a490SYu Zhao 			for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3270*ac35a490SYu Zhao 				if (!list_empty(&lrugen->lists[gen][type][zone]))
3271*ac35a490SYu Zhao 					goto next;
3272*ac35a490SYu Zhao 			}
3273*ac35a490SYu Zhao 
3274*ac35a490SYu Zhao 			min_seq[type]++;
3275*ac35a490SYu Zhao 		}
3276*ac35a490SYu Zhao next:
3277*ac35a490SYu Zhao 		;
3278*ac35a490SYu Zhao 	}
3279*ac35a490SYu Zhao 
3280*ac35a490SYu Zhao 	/* see the comment on lru_gen_struct */
3281*ac35a490SYu Zhao 	if (can_swap) {
3282*ac35a490SYu Zhao 		min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
3283*ac35a490SYu Zhao 		min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
3284*ac35a490SYu Zhao 	}
3285*ac35a490SYu Zhao 
3286*ac35a490SYu Zhao 	for (type = !can_swap; type < ANON_AND_FILE; type++) {
3287*ac35a490SYu Zhao 		if (min_seq[type] == lrugen->min_seq[type])
3288*ac35a490SYu Zhao 			continue;
3289*ac35a490SYu Zhao 
3290*ac35a490SYu Zhao 		reset_ctrl_pos(lruvec, type, true);
3291*ac35a490SYu Zhao 		WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
3292*ac35a490SYu Zhao 		success = true;
3293*ac35a490SYu Zhao 	}
3294*ac35a490SYu Zhao 
3295*ac35a490SYu Zhao 	return success;
3296*ac35a490SYu Zhao }
3297*ac35a490SYu Zhao 
3298*ac35a490SYu Zhao static void inc_max_seq(struct lruvec *lruvec, unsigned long max_seq, bool can_swap)
3299*ac35a490SYu Zhao {
3300*ac35a490SYu Zhao 	int prev, next;
3301*ac35a490SYu Zhao 	int type, zone;
3302*ac35a490SYu Zhao 	struct lru_gen_struct *lrugen = &lruvec->lrugen;
3303*ac35a490SYu Zhao 
3304*ac35a490SYu Zhao 	spin_lock_irq(&lruvec->lru_lock);
3305*ac35a490SYu Zhao 
3306*ac35a490SYu Zhao 	VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
3307*ac35a490SYu Zhao 
3308*ac35a490SYu Zhao 	if (max_seq != lrugen->max_seq)
3309*ac35a490SYu Zhao 		goto unlock;
3310*ac35a490SYu Zhao 
3311*ac35a490SYu Zhao 	for (type = ANON_AND_FILE - 1; type >= 0; type--) {
3312*ac35a490SYu Zhao 		if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
3313*ac35a490SYu Zhao 			continue;
3314*ac35a490SYu Zhao 
3315*ac35a490SYu Zhao 		VM_WARN_ON_ONCE(type == LRU_GEN_FILE || can_swap);
3316*ac35a490SYu Zhao 
3317*ac35a490SYu Zhao 		inc_min_seq(lruvec, type);
3318*ac35a490SYu Zhao 	}
3319*ac35a490SYu Zhao 
3320*ac35a490SYu Zhao 	/*
3321*ac35a490SYu Zhao 	 * Update the active/inactive LRU sizes for compatibility. Both sides of
3322*ac35a490SYu Zhao 	 * the current max_seq need to be covered, since max_seq+1 can overlap
3323*ac35a490SYu Zhao 	 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
3324*ac35a490SYu Zhao 	 * overlap, cold/hot inversion happens.
3325*ac35a490SYu Zhao 	 */
3326*ac35a490SYu Zhao 	prev = lru_gen_from_seq(lrugen->max_seq - 1);
3327*ac35a490SYu Zhao 	next = lru_gen_from_seq(lrugen->max_seq + 1);
3328*ac35a490SYu Zhao 
3329*ac35a490SYu Zhao 	for (type = 0; type < ANON_AND_FILE; type++) {
3330*ac35a490SYu Zhao 		for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3331*ac35a490SYu Zhao 			enum lru_list lru = type * LRU_INACTIVE_FILE;
3332*ac35a490SYu Zhao 			long delta = lrugen->nr_pages[prev][type][zone] -
3333*ac35a490SYu Zhao 				     lrugen->nr_pages[next][type][zone];
3334*ac35a490SYu Zhao 
3335*ac35a490SYu Zhao 			if (!delta)
3336*ac35a490SYu Zhao 				continue;
3337*ac35a490SYu Zhao 
3338*ac35a490SYu Zhao 			__update_lru_size(lruvec, lru, zone, delta);
3339*ac35a490SYu Zhao 			__update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
3340*ac35a490SYu Zhao 		}
3341*ac35a490SYu Zhao 	}
3342*ac35a490SYu Zhao 
3343*ac35a490SYu Zhao 	for (type = 0; type < ANON_AND_FILE; type++)
3344*ac35a490SYu Zhao 		reset_ctrl_pos(lruvec, type, false);
3345*ac35a490SYu Zhao 
3346*ac35a490SYu Zhao 	/* make sure preceding modifications appear */
3347*ac35a490SYu Zhao 	smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
3348*ac35a490SYu Zhao unlock:
3349*ac35a490SYu Zhao 	spin_unlock_irq(&lruvec->lru_lock);
3350*ac35a490SYu Zhao }
3351*ac35a490SYu Zhao 
3352*ac35a490SYu Zhao static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, unsigned long *min_seq,
3353*ac35a490SYu Zhao 			     struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
3354*ac35a490SYu Zhao {
3355*ac35a490SYu Zhao 	int gen, type, zone;
3356*ac35a490SYu Zhao 	unsigned long old = 0;
3357*ac35a490SYu Zhao 	unsigned long young = 0;
3358*ac35a490SYu Zhao 	unsigned long total = 0;
3359*ac35a490SYu Zhao 	struct lru_gen_struct *lrugen = &lruvec->lrugen;
3360*ac35a490SYu Zhao 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3361*ac35a490SYu Zhao 
3362*ac35a490SYu Zhao 	for (type = !can_swap; type < ANON_AND_FILE; type++) {
3363*ac35a490SYu Zhao 		unsigned long seq;
3364*ac35a490SYu Zhao 
3365*ac35a490SYu Zhao 		for (seq = min_seq[type]; seq <= max_seq; seq++) {
3366*ac35a490SYu Zhao 			unsigned long size = 0;
3367*ac35a490SYu Zhao 
3368*ac35a490SYu Zhao 			gen = lru_gen_from_seq(seq);
3369*ac35a490SYu Zhao 
3370*ac35a490SYu Zhao 			for (zone = 0; zone < MAX_NR_ZONES; zone++)
3371*ac35a490SYu Zhao 				size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
3372*ac35a490SYu Zhao 
3373*ac35a490SYu Zhao 			total += size;
3374*ac35a490SYu Zhao 			if (seq == max_seq)
3375*ac35a490SYu Zhao 				young += size;
3376*ac35a490SYu Zhao 			else if (seq + MIN_NR_GENS == max_seq)
3377*ac35a490SYu Zhao 				old += size;
3378*ac35a490SYu Zhao 		}
3379*ac35a490SYu Zhao 	}
3380*ac35a490SYu Zhao 
3381*ac35a490SYu Zhao 	/* try to scrape all its memory if this memcg was deleted */
3382*ac35a490SYu Zhao 	*nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
3383*ac35a490SYu Zhao 
3384*ac35a490SYu Zhao 	/*
3385*ac35a490SYu Zhao 	 * The aging tries to be lazy to reduce the overhead, while the eviction
3386*ac35a490SYu Zhao 	 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
3387*ac35a490SYu Zhao 	 * ideal number of generations is MIN_NR_GENS+1.
3388*ac35a490SYu Zhao 	 */
3389*ac35a490SYu Zhao 	if (min_seq[!can_swap] + MIN_NR_GENS > max_seq)
3390*ac35a490SYu Zhao 		return true;
3391*ac35a490SYu Zhao 	if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
3392*ac35a490SYu Zhao 		return false;
3393*ac35a490SYu Zhao 
3394*ac35a490SYu Zhao 	/*
3395*ac35a490SYu Zhao 	 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
3396*ac35a490SYu Zhao 	 * of the total number of pages for each generation. A reasonable range
3397*ac35a490SYu Zhao 	 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
3398*ac35a490SYu Zhao 	 * aging cares about the upper bound of hot pages, while the eviction
3399*ac35a490SYu Zhao 	 * cares about the lower bound of cold pages.
3400*ac35a490SYu Zhao 	 */
3401*ac35a490SYu Zhao 	if (young * MIN_NR_GENS > total)
3402*ac35a490SYu Zhao 		return true;
3403*ac35a490SYu Zhao 	if (old * (MIN_NR_GENS + 2) < total)
3404*ac35a490SYu Zhao 		return true;
3405*ac35a490SYu Zhao 
3406*ac35a490SYu Zhao 	return false;
3407*ac35a490SYu Zhao }
3408*ac35a490SYu Zhao 
3409*ac35a490SYu Zhao static void age_lruvec(struct lruvec *lruvec, struct scan_control *sc)
3410*ac35a490SYu Zhao {
3411*ac35a490SYu Zhao 	bool need_aging;
3412*ac35a490SYu Zhao 	unsigned long nr_to_scan;
3413*ac35a490SYu Zhao 	int swappiness = get_swappiness(lruvec, sc);
3414*ac35a490SYu Zhao 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3415*ac35a490SYu Zhao 	DEFINE_MAX_SEQ(lruvec);
3416*ac35a490SYu Zhao 	DEFINE_MIN_SEQ(lruvec);
3417*ac35a490SYu Zhao 
3418*ac35a490SYu Zhao 	VM_WARN_ON_ONCE(sc->memcg_low_reclaim);
3419*ac35a490SYu Zhao 
3420*ac35a490SYu Zhao 	mem_cgroup_calculate_protection(NULL, memcg);
3421*ac35a490SYu Zhao 
3422*ac35a490SYu Zhao 	if (mem_cgroup_below_min(memcg))
3423*ac35a490SYu Zhao 		return;
3424*ac35a490SYu Zhao 
3425*ac35a490SYu Zhao 	need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, swappiness, &nr_to_scan);
3426*ac35a490SYu Zhao 	if (need_aging)
3427*ac35a490SYu Zhao 		inc_max_seq(lruvec, max_seq, swappiness);
3428*ac35a490SYu Zhao }
3429*ac35a490SYu Zhao 
3430*ac35a490SYu Zhao static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
3431*ac35a490SYu Zhao {
3432*ac35a490SYu Zhao 	struct mem_cgroup *memcg;
3433*ac35a490SYu Zhao 
3434*ac35a490SYu Zhao 	VM_WARN_ON_ONCE(!current_is_kswapd());
3435*ac35a490SYu Zhao 
3436*ac35a490SYu Zhao 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3437*ac35a490SYu Zhao 	do {
3438*ac35a490SYu Zhao 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3439*ac35a490SYu Zhao 
3440*ac35a490SYu Zhao 		age_lruvec(lruvec, sc);
3441*ac35a490SYu Zhao 
3442*ac35a490SYu Zhao 		cond_resched();
3443*ac35a490SYu Zhao 	} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
3444*ac35a490SYu Zhao }
3445*ac35a490SYu Zhao 
3446*ac35a490SYu Zhao /******************************************************************************
3447*ac35a490SYu Zhao  *                          the eviction
3448*ac35a490SYu Zhao  ******************************************************************************/
3449*ac35a490SYu Zhao 
3450*ac35a490SYu Zhao static bool sort_folio(struct lruvec *lruvec, struct folio *folio, int tier_idx)
3451*ac35a490SYu Zhao {
3452*ac35a490SYu Zhao 	bool success;
3453*ac35a490SYu Zhao 	int gen = folio_lru_gen(folio);
3454*ac35a490SYu Zhao 	int type = folio_is_file_lru(folio);
3455*ac35a490SYu Zhao 	int zone = folio_zonenum(folio);
3456*ac35a490SYu Zhao 	int delta = folio_nr_pages(folio);
3457*ac35a490SYu Zhao 	int refs = folio_lru_refs(folio);
3458*ac35a490SYu Zhao 	int tier = lru_tier_from_refs(refs);
3459*ac35a490SYu Zhao 	struct lru_gen_struct *lrugen = &lruvec->lrugen;
3460*ac35a490SYu Zhao 
3461*ac35a490SYu Zhao 	VM_WARN_ON_ONCE_FOLIO(gen >= MAX_NR_GENS, folio);
3462*ac35a490SYu Zhao 
3463*ac35a490SYu Zhao 	/* unevictable */
3464*ac35a490SYu Zhao 	if (!folio_evictable(folio)) {
3465*ac35a490SYu Zhao 		success = lru_gen_del_folio(lruvec, folio, true);
3466*ac35a490SYu Zhao 		VM_WARN_ON_ONCE_FOLIO(!success, folio);
3467*ac35a490SYu Zhao 		folio_set_unevictable(folio);
3468*ac35a490SYu Zhao 		lruvec_add_folio(lruvec, folio);
3469*ac35a490SYu Zhao 		__count_vm_events(UNEVICTABLE_PGCULLED, delta);
3470*ac35a490SYu Zhao 		return true;
3471*ac35a490SYu Zhao 	}
3472*ac35a490SYu Zhao 
3473*ac35a490SYu Zhao 	/* dirty lazyfree */
3474*ac35a490SYu Zhao 	if (type == LRU_GEN_FILE && folio_test_anon(folio) && folio_test_dirty(folio)) {
3475*ac35a490SYu Zhao 		success = lru_gen_del_folio(lruvec, folio, true);
3476*ac35a490SYu Zhao 		VM_WARN_ON_ONCE_FOLIO(!success, folio);
3477*ac35a490SYu Zhao 		folio_set_swapbacked(folio);
3478*ac35a490SYu Zhao 		lruvec_add_folio_tail(lruvec, folio);
3479*ac35a490SYu Zhao 		return true;
3480*ac35a490SYu Zhao 	}
3481*ac35a490SYu Zhao 
3482*ac35a490SYu Zhao 	/* protected */
3483*ac35a490SYu Zhao 	if (tier > tier_idx) {
3484*ac35a490SYu Zhao 		int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3485*ac35a490SYu Zhao 
3486*ac35a490SYu Zhao 		gen = folio_inc_gen(lruvec, folio, false);
3487*ac35a490SYu Zhao 		list_move_tail(&folio->lru, &lrugen->lists[gen][type][zone]);
3488*ac35a490SYu Zhao 
3489*ac35a490SYu Zhao 		WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
3490*ac35a490SYu Zhao 			   lrugen->protected[hist][type][tier - 1] + delta);
3491*ac35a490SYu Zhao 		__mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
3492*ac35a490SYu Zhao 		return true;
3493*ac35a490SYu Zhao 	}
3494*ac35a490SYu Zhao 
3495*ac35a490SYu Zhao 	/* waiting for writeback */
3496*ac35a490SYu Zhao 	if (folio_test_locked(folio) || folio_test_writeback(folio) ||
3497*ac35a490SYu Zhao 	    (type == LRU_GEN_FILE && folio_test_dirty(folio))) {
3498*ac35a490SYu Zhao 		gen = folio_inc_gen(lruvec, folio, true);
3499*ac35a490SYu Zhao 		list_move(&folio->lru, &lrugen->lists[gen][type][zone]);
3500*ac35a490SYu Zhao 		return true;
3501*ac35a490SYu Zhao 	}
3502*ac35a490SYu Zhao 
3503*ac35a490SYu Zhao 	return false;
3504*ac35a490SYu Zhao }
3505*ac35a490SYu Zhao 
3506*ac35a490SYu Zhao static bool isolate_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc)
3507*ac35a490SYu Zhao {
3508*ac35a490SYu Zhao 	bool success;
3509*ac35a490SYu Zhao 
3510*ac35a490SYu Zhao 	/* unmapping inhibited */
3511*ac35a490SYu Zhao 	if (!sc->may_unmap && folio_mapped(folio))
3512*ac35a490SYu Zhao 		return false;
3513*ac35a490SYu Zhao 
3514*ac35a490SYu Zhao 	/* swapping inhibited */
3515*ac35a490SYu Zhao 	if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
3516*ac35a490SYu Zhao 	    (folio_test_dirty(folio) ||
3517*ac35a490SYu Zhao 	     (folio_test_anon(folio) && !folio_test_swapcache(folio))))
3518*ac35a490SYu Zhao 		return false;
3519*ac35a490SYu Zhao 
3520*ac35a490SYu Zhao 	/* raced with release_pages() */
3521*ac35a490SYu Zhao 	if (!folio_try_get(folio))
3522*ac35a490SYu Zhao 		return false;
3523*ac35a490SYu Zhao 
3524*ac35a490SYu Zhao 	/* raced with another isolation */
3525*ac35a490SYu Zhao 	if (!folio_test_clear_lru(folio)) {
3526*ac35a490SYu Zhao 		folio_put(folio);
3527*ac35a490SYu Zhao 		return false;
3528*ac35a490SYu Zhao 	}
3529*ac35a490SYu Zhao 
3530*ac35a490SYu Zhao 	/* see the comment on MAX_NR_TIERS */
3531*ac35a490SYu Zhao 	if (!folio_test_referenced(folio))
3532*ac35a490SYu Zhao 		set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
3533*ac35a490SYu Zhao 
3534*ac35a490SYu Zhao 	/* for shrink_page_list() */
3535*ac35a490SYu Zhao 	folio_clear_reclaim(folio);
3536*ac35a490SYu Zhao 	folio_clear_referenced(folio);
3537*ac35a490SYu Zhao 
3538*ac35a490SYu Zhao 	success = lru_gen_del_folio(lruvec, folio, true);
3539*ac35a490SYu Zhao 	VM_WARN_ON_ONCE_FOLIO(!success, folio);
3540*ac35a490SYu Zhao 
3541*ac35a490SYu Zhao 	return true;
3542*ac35a490SYu Zhao }
3543*ac35a490SYu Zhao 
3544*ac35a490SYu Zhao static int scan_folios(struct lruvec *lruvec, struct scan_control *sc,
3545*ac35a490SYu Zhao 		       int type, int tier, struct list_head *list)
3546*ac35a490SYu Zhao {
3547*ac35a490SYu Zhao 	int gen, zone;
3548*ac35a490SYu Zhao 	enum vm_event_item item;
3549*ac35a490SYu Zhao 	int sorted = 0;
3550*ac35a490SYu Zhao 	int scanned = 0;
3551*ac35a490SYu Zhao 	int isolated = 0;
3552*ac35a490SYu Zhao 	int remaining = MAX_LRU_BATCH;
3553*ac35a490SYu Zhao 	struct lru_gen_struct *lrugen = &lruvec->lrugen;
3554*ac35a490SYu Zhao 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3555*ac35a490SYu Zhao 
3556*ac35a490SYu Zhao 	VM_WARN_ON_ONCE(!list_empty(list));
3557*ac35a490SYu Zhao 
3558*ac35a490SYu Zhao 	if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
3559*ac35a490SYu Zhao 		return 0;
3560*ac35a490SYu Zhao 
3561*ac35a490SYu Zhao 	gen = lru_gen_from_seq(lrugen->min_seq[type]);
3562*ac35a490SYu Zhao 
3563*ac35a490SYu Zhao 	for (zone = sc->reclaim_idx; zone >= 0; zone--) {
3564*ac35a490SYu Zhao 		LIST_HEAD(moved);
3565*ac35a490SYu Zhao 		int skipped = 0;
3566*ac35a490SYu Zhao 		struct list_head *head = &lrugen->lists[gen][type][zone];
3567*ac35a490SYu Zhao 
3568*ac35a490SYu Zhao 		while (!list_empty(head)) {
3569*ac35a490SYu Zhao 			struct folio *folio = lru_to_folio(head);
3570*ac35a490SYu Zhao 			int delta = folio_nr_pages(folio);
3571*ac35a490SYu Zhao 
3572*ac35a490SYu Zhao 			VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
3573*ac35a490SYu Zhao 			VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
3574*ac35a490SYu Zhao 			VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
3575*ac35a490SYu Zhao 			VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
3576*ac35a490SYu Zhao 
3577*ac35a490SYu Zhao 			scanned += delta;
3578*ac35a490SYu Zhao 
3579*ac35a490SYu Zhao 			if (sort_folio(lruvec, folio, tier))
3580*ac35a490SYu Zhao 				sorted += delta;
3581*ac35a490SYu Zhao 			else if (isolate_folio(lruvec, folio, sc)) {
3582*ac35a490SYu Zhao 				list_add(&folio->lru, list);
3583*ac35a490SYu Zhao 				isolated += delta;
3584*ac35a490SYu Zhao 			} else {
3585*ac35a490SYu Zhao 				list_move(&folio->lru, &moved);
3586*ac35a490SYu Zhao 				skipped += delta;
3587*ac35a490SYu Zhao 			}
3588*ac35a490SYu Zhao 
3589*ac35a490SYu Zhao 			if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
3590*ac35a490SYu Zhao 				break;
3591*ac35a490SYu Zhao 		}
3592*ac35a490SYu Zhao 
3593*ac35a490SYu Zhao 		if (skipped) {
3594*ac35a490SYu Zhao 			list_splice(&moved, head);
3595*ac35a490SYu Zhao 			__count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
3596*ac35a490SYu Zhao 		}
3597*ac35a490SYu Zhao 
3598*ac35a490SYu Zhao 		if (!remaining || isolated >= MIN_LRU_BATCH)
3599*ac35a490SYu Zhao 			break;
3600*ac35a490SYu Zhao 	}
3601*ac35a490SYu Zhao 
3602*ac35a490SYu Zhao 	item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
3603*ac35a490SYu Zhao 	if (!cgroup_reclaim(sc)) {
3604*ac35a490SYu Zhao 		__count_vm_events(item, isolated);
3605*ac35a490SYu Zhao 		__count_vm_events(PGREFILL, sorted);
3606*ac35a490SYu Zhao 	}
3607*ac35a490SYu Zhao 	__count_memcg_events(memcg, item, isolated);
3608*ac35a490SYu Zhao 	__count_memcg_events(memcg, PGREFILL, sorted);
3609*ac35a490SYu Zhao 	__count_vm_events(PGSCAN_ANON + type, isolated);
3610*ac35a490SYu Zhao 
3611*ac35a490SYu Zhao 	/*
3612*ac35a490SYu Zhao 	 * There might not be eligible pages due to reclaim_idx, may_unmap and
3613*ac35a490SYu Zhao 	 * may_writepage. Check the remaining to prevent livelock if it's not
3614*ac35a490SYu Zhao 	 * making progress.
3615*ac35a490SYu Zhao 	 */
3616*ac35a490SYu Zhao 	return isolated || !remaining ? scanned : 0;
3617*ac35a490SYu Zhao }
3618*ac35a490SYu Zhao 
3619*ac35a490SYu Zhao static int get_tier_idx(struct lruvec *lruvec, int type)
3620*ac35a490SYu Zhao {
3621*ac35a490SYu Zhao 	int tier;
3622*ac35a490SYu Zhao 	struct ctrl_pos sp, pv;
3623*ac35a490SYu Zhao 
3624*ac35a490SYu Zhao 	/*
3625*ac35a490SYu Zhao 	 * To leave a margin for fluctuations, use a larger gain factor (1:2).
3626*ac35a490SYu Zhao 	 * This value is chosen because any other tier would have at least twice
3627*ac35a490SYu Zhao 	 * as many refaults as the first tier.
3628*ac35a490SYu Zhao 	 */
3629*ac35a490SYu Zhao 	read_ctrl_pos(lruvec, type, 0, 1, &sp);
3630*ac35a490SYu Zhao 	for (tier = 1; tier < MAX_NR_TIERS; tier++) {
3631*ac35a490SYu Zhao 		read_ctrl_pos(lruvec, type, tier, 2, &pv);
3632*ac35a490SYu Zhao 		if (!positive_ctrl_err(&sp, &pv))
3633*ac35a490SYu Zhao 			break;
3634*ac35a490SYu Zhao 	}
3635*ac35a490SYu Zhao 
3636*ac35a490SYu Zhao 	return tier - 1;
3637*ac35a490SYu Zhao }
3638*ac35a490SYu Zhao 
3639*ac35a490SYu Zhao static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
3640*ac35a490SYu Zhao {
3641*ac35a490SYu Zhao 	int type, tier;
3642*ac35a490SYu Zhao 	struct ctrl_pos sp, pv;
3643*ac35a490SYu Zhao 	int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
3644*ac35a490SYu Zhao 
3645*ac35a490SYu Zhao 	/*
3646*ac35a490SYu Zhao 	 * Compare the first tier of anon with that of file to determine which
3647*ac35a490SYu Zhao 	 * type to scan. Also need to compare other tiers of the selected type
3648*ac35a490SYu Zhao 	 * with the first tier of the other type to determine the last tier (of
3649*ac35a490SYu Zhao 	 * the selected type) to evict.
3650*ac35a490SYu Zhao 	 */
3651*ac35a490SYu Zhao 	read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
3652*ac35a490SYu Zhao 	read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
3653*ac35a490SYu Zhao 	type = positive_ctrl_err(&sp, &pv);
3654*ac35a490SYu Zhao 
3655*ac35a490SYu Zhao 	read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
3656*ac35a490SYu Zhao 	for (tier = 1; tier < MAX_NR_TIERS; tier++) {
3657*ac35a490SYu Zhao 		read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
3658*ac35a490SYu Zhao 		if (!positive_ctrl_err(&sp, &pv))
3659*ac35a490SYu Zhao 			break;
3660*ac35a490SYu Zhao 	}
3661*ac35a490SYu Zhao 
3662*ac35a490SYu Zhao 	*tier_idx = tier - 1;
3663*ac35a490SYu Zhao 
3664*ac35a490SYu Zhao 	return type;
3665*ac35a490SYu Zhao }
3666*ac35a490SYu Zhao 
3667*ac35a490SYu Zhao static int isolate_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
3668*ac35a490SYu Zhao 			  int *type_scanned, struct list_head *list)
3669*ac35a490SYu Zhao {
3670*ac35a490SYu Zhao 	int i;
3671*ac35a490SYu Zhao 	int type;
3672*ac35a490SYu Zhao 	int scanned;
3673*ac35a490SYu Zhao 	int tier = -1;
3674*ac35a490SYu Zhao 	DEFINE_MIN_SEQ(lruvec);
3675*ac35a490SYu Zhao 
3676*ac35a490SYu Zhao 	/*
3677*ac35a490SYu Zhao 	 * Try to make the obvious choice first. When anon and file are both
3678*ac35a490SYu Zhao 	 * available from the same generation, interpret swappiness 1 as file
3679*ac35a490SYu Zhao 	 * first and 200 as anon first.
3680*ac35a490SYu Zhao 	 */
3681*ac35a490SYu Zhao 	if (!swappiness)
3682*ac35a490SYu Zhao 		type = LRU_GEN_FILE;
3683*ac35a490SYu Zhao 	else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
3684*ac35a490SYu Zhao 		type = LRU_GEN_ANON;
3685*ac35a490SYu Zhao 	else if (swappiness == 1)
3686*ac35a490SYu Zhao 		type = LRU_GEN_FILE;
3687*ac35a490SYu Zhao 	else if (swappiness == 200)
3688*ac35a490SYu Zhao 		type = LRU_GEN_ANON;
3689*ac35a490SYu Zhao 	else
3690*ac35a490SYu Zhao 		type = get_type_to_scan(lruvec, swappiness, &tier);
3691*ac35a490SYu Zhao 
3692*ac35a490SYu Zhao 	for (i = !swappiness; i < ANON_AND_FILE; i++) {
3693*ac35a490SYu Zhao 		if (tier < 0)
3694*ac35a490SYu Zhao 			tier = get_tier_idx(lruvec, type);
3695*ac35a490SYu Zhao 
3696*ac35a490SYu Zhao 		scanned = scan_folios(lruvec, sc, type, tier, list);
3697*ac35a490SYu Zhao 		if (scanned)
3698*ac35a490SYu Zhao 			break;
3699*ac35a490SYu Zhao 
3700*ac35a490SYu Zhao 		type = !type;
3701*ac35a490SYu Zhao 		tier = -1;
3702*ac35a490SYu Zhao 	}
3703*ac35a490SYu Zhao 
3704*ac35a490SYu Zhao 	*type_scanned = type;
3705*ac35a490SYu Zhao 
3706*ac35a490SYu Zhao 	return scanned;
3707*ac35a490SYu Zhao }
3708*ac35a490SYu Zhao 
3709*ac35a490SYu Zhao static int evict_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
3710*ac35a490SYu Zhao {
3711*ac35a490SYu Zhao 	int type;
3712*ac35a490SYu Zhao 	int scanned;
3713*ac35a490SYu Zhao 	int reclaimed;
3714*ac35a490SYu Zhao 	LIST_HEAD(list);
3715*ac35a490SYu Zhao 	struct folio *folio;
3716*ac35a490SYu Zhao 	enum vm_event_item item;
3717*ac35a490SYu Zhao 	struct reclaim_stat stat;
3718*ac35a490SYu Zhao 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3719*ac35a490SYu Zhao 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
3720*ac35a490SYu Zhao 
3721*ac35a490SYu Zhao 	spin_lock_irq(&lruvec->lru_lock);
3722*ac35a490SYu Zhao 
3723*ac35a490SYu Zhao 	scanned = isolate_folios(lruvec, sc, swappiness, &type, &list);
3724*ac35a490SYu Zhao 
3725*ac35a490SYu Zhao 	scanned += try_to_inc_min_seq(lruvec, swappiness);
3726*ac35a490SYu Zhao 
3727*ac35a490SYu Zhao 	if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
3728*ac35a490SYu Zhao 		scanned = 0;
3729*ac35a490SYu Zhao 
3730*ac35a490SYu Zhao 	spin_unlock_irq(&lruvec->lru_lock);
3731*ac35a490SYu Zhao 
3732*ac35a490SYu Zhao 	if (list_empty(&list))
3733*ac35a490SYu Zhao 		return scanned;
3734*ac35a490SYu Zhao 
3735*ac35a490SYu Zhao 	reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
3736*ac35a490SYu Zhao 
3737*ac35a490SYu Zhao 	list_for_each_entry(folio, &list, lru) {
3738*ac35a490SYu Zhao 		/* restore LRU_REFS_FLAGS cleared by isolate_folio() */
3739*ac35a490SYu Zhao 		if (folio_test_workingset(folio))
3740*ac35a490SYu Zhao 			folio_set_referenced(folio);
3741*ac35a490SYu Zhao 
3742*ac35a490SYu Zhao 		/* don't add rejected pages to the oldest generation */
3743*ac35a490SYu Zhao 		if (folio_test_reclaim(folio) &&
3744*ac35a490SYu Zhao 		    (folio_test_dirty(folio) || folio_test_writeback(folio)))
3745*ac35a490SYu Zhao 			folio_clear_active(folio);
3746*ac35a490SYu Zhao 		else
3747*ac35a490SYu Zhao 			folio_set_active(folio);
3748*ac35a490SYu Zhao 	}
3749*ac35a490SYu Zhao 
3750*ac35a490SYu Zhao 	spin_lock_irq(&lruvec->lru_lock);
3751*ac35a490SYu Zhao 
3752*ac35a490SYu Zhao 	move_pages_to_lru(lruvec, &list);
3753*ac35a490SYu Zhao 
3754*ac35a490SYu Zhao 	item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
3755*ac35a490SYu Zhao 	if (!cgroup_reclaim(sc))
3756*ac35a490SYu Zhao 		__count_vm_events(item, reclaimed);
3757*ac35a490SYu Zhao 	__count_memcg_events(memcg, item, reclaimed);
3758*ac35a490SYu Zhao 	__count_vm_events(PGSTEAL_ANON + type, reclaimed);
3759*ac35a490SYu Zhao 
3760*ac35a490SYu Zhao 	spin_unlock_irq(&lruvec->lru_lock);
3761*ac35a490SYu Zhao 
3762*ac35a490SYu Zhao 	mem_cgroup_uncharge_list(&list);
3763*ac35a490SYu Zhao 	free_unref_page_list(&list);
3764*ac35a490SYu Zhao 
3765*ac35a490SYu Zhao 	sc->nr_reclaimed += reclaimed;
3766*ac35a490SYu Zhao 
3767*ac35a490SYu Zhao 	return scanned;
3768*ac35a490SYu Zhao }
3769*ac35a490SYu Zhao 
3770*ac35a490SYu Zhao static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc,
3771*ac35a490SYu Zhao 				    bool can_swap)
3772*ac35a490SYu Zhao {
3773*ac35a490SYu Zhao 	bool need_aging;
3774*ac35a490SYu Zhao 	unsigned long nr_to_scan;
3775*ac35a490SYu Zhao 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3776*ac35a490SYu Zhao 	DEFINE_MAX_SEQ(lruvec);
3777*ac35a490SYu Zhao 	DEFINE_MIN_SEQ(lruvec);
3778*ac35a490SYu Zhao 
3779*ac35a490SYu Zhao 	if (mem_cgroup_below_min(memcg) ||
3780*ac35a490SYu Zhao 	    (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
3781*ac35a490SYu Zhao 		return 0;
3782*ac35a490SYu Zhao 
3783*ac35a490SYu Zhao 	need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, can_swap, &nr_to_scan);
3784*ac35a490SYu Zhao 	if (!need_aging)
3785*ac35a490SYu Zhao 		return nr_to_scan;
3786*ac35a490SYu Zhao 
3787*ac35a490SYu Zhao 	/* skip the aging path at the default priority */
3788*ac35a490SYu Zhao 	if (sc->priority == DEF_PRIORITY)
3789*ac35a490SYu Zhao 		goto done;
3790*ac35a490SYu Zhao 
3791*ac35a490SYu Zhao 	/* leave the work to lru_gen_age_node() */
3792*ac35a490SYu Zhao 	if (current_is_kswapd())
3793*ac35a490SYu Zhao 		return 0;
3794*ac35a490SYu Zhao 
3795*ac35a490SYu Zhao 	inc_max_seq(lruvec, max_seq, can_swap);
3796*ac35a490SYu Zhao done:
3797*ac35a490SYu Zhao 	return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
3798*ac35a490SYu Zhao }
3799*ac35a490SYu Zhao 
3800*ac35a490SYu Zhao static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
3801*ac35a490SYu Zhao {
3802*ac35a490SYu Zhao 	struct blk_plug plug;
3803*ac35a490SYu Zhao 	unsigned long scanned = 0;
3804*ac35a490SYu Zhao 
3805*ac35a490SYu Zhao 	lru_add_drain();
3806*ac35a490SYu Zhao 
3807*ac35a490SYu Zhao 	blk_start_plug(&plug);
3808*ac35a490SYu Zhao 
3809*ac35a490SYu Zhao 	while (true) {
3810*ac35a490SYu Zhao 		int delta;
3811*ac35a490SYu Zhao 		int swappiness;
3812*ac35a490SYu Zhao 		unsigned long nr_to_scan;
3813*ac35a490SYu Zhao 
3814*ac35a490SYu Zhao 		if (sc->may_swap)
3815*ac35a490SYu Zhao 			swappiness = get_swappiness(lruvec, sc);
3816*ac35a490SYu Zhao 		else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
3817*ac35a490SYu Zhao 			swappiness = 1;
3818*ac35a490SYu Zhao 		else
3819*ac35a490SYu Zhao 			swappiness = 0;
3820*ac35a490SYu Zhao 
3821*ac35a490SYu Zhao 		nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
3822*ac35a490SYu Zhao 		if (!nr_to_scan)
3823*ac35a490SYu Zhao 			break;
3824*ac35a490SYu Zhao 
3825*ac35a490SYu Zhao 		delta = evict_folios(lruvec, sc, swappiness);
3826*ac35a490SYu Zhao 		if (!delta)
3827*ac35a490SYu Zhao 			break;
3828*ac35a490SYu Zhao 
3829*ac35a490SYu Zhao 		scanned += delta;
3830*ac35a490SYu Zhao 		if (scanned >= nr_to_scan)
3831*ac35a490SYu Zhao 			break;
3832*ac35a490SYu Zhao 
3833*ac35a490SYu Zhao 		cond_resched();
3834*ac35a490SYu Zhao 	}
3835*ac35a490SYu Zhao 
3836*ac35a490SYu Zhao 	blk_finish_plug(&plug);
3837*ac35a490SYu Zhao }
3838*ac35a490SYu Zhao 
3839ec1c86b2SYu Zhao /******************************************************************************
3840ec1c86b2SYu Zhao  *                          initialization
3841ec1c86b2SYu Zhao  ******************************************************************************/
3842ec1c86b2SYu Zhao 
3843ec1c86b2SYu Zhao void lru_gen_init_lruvec(struct lruvec *lruvec)
3844ec1c86b2SYu Zhao {
3845ec1c86b2SYu Zhao 	int gen, type, zone;
3846ec1c86b2SYu Zhao 	struct lru_gen_struct *lrugen = &lruvec->lrugen;
3847ec1c86b2SYu Zhao 
3848ec1c86b2SYu Zhao 	lrugen->max_seq = MIN_NR_GENS + 1;
3849ec1c86b2SYu Zhao 
3850ec1c86b2SYu Zhao 	for_each_gen_type_zone(gen, type, zone)
3851ec1c86b2SYu Zhao 		INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
3852ec1c86b2SYu Zhao }
3853ec1c86b2SYu Zhao 
3854ec1c86b2SYu Zhao #ifdef CONFIG_MEMCG
3855ec1c86b2SYu Zhao void lru_gen_init_memcg(struct mem_cgroup *memcg)
3856ec1c86b2SYu Zhao {
3857ec1c86b2SYu Zhao }
3858ec1c86b2SYu Zhao 
3859ec1c86b2SYu Zhao void lru_gen_exit_memcg(struct mem_cgroup *memcg)
3860ec1c86b2SYu Zhao {
3861ec1c86b2SYu Zhao 	int nid;
3862ec1c86b2SYu Zhao 
3863ec1c86b2SYu Zhao 	for_each_node(nid) {
3864ec1c86b2SYu Zhao 		struct lruvec *lruvec = get_lruvec(memcg, nid);
3865ec1c86b2SYu Zhao 
3866ec1c86b2SYu Zhao 		VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
3867ec1c86b2SYu Zhao 					   sizeof(lruvec->lrugen.nr_pages)));
3868ec1c86b2SYu Zhao 	}
3869ec1c86b2SYu Zhao }
3870ec1c86b2SYu Zhao #endif
3871ec1c86b2SYu Zhao 
3872ec1c86b2SYu Zhao static int __init init_lru_gen(void)
3873ec1c86b2SYu Zhao {
3874ec1c86b2SYu Zhao 	BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
3875ec1c86b2SYu Zhao 	BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
3876ec1c86b2SYu Zhao 
3877ec1c86b2SYu Zhao 	return 0;
3878ec1c86b2SYu Zhao };
3879ec1c86b2SYu Zhao late_initcall(init_lru_gen);
3880ec1c86b2SYu Zhao 
3881*ac35a490SYu Zhao #else /* !CONFIG_LRU_GEN */
3882*ac35a490SYu Zhao 
3883*ac35a490SYu Zhao static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
3884*ac35a490SYu Zhao {
3885*ac35a490SYu Zhao }
3886*ac35a490SYu Zhao 
3887*ac35a490SYu Zhao static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
3888*ac35a490SYu Zhao {
3889*ac35a490SYu Zhao }
3890*ac35a490SYu Zhao 
3891ec1c86b2SYu Zhao #endif /* CONFIG_LRU_GEN */
3892ec1c86b2SYu Zhao 
3893afaf07a6SJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
38949b4f98cdSJohannes Weiner {
38959b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
3896e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
38979b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
38989b4f98cdSJohannes Weiner 	enum lru_list lru;
38999b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
39009b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
39019b4f98cdSJohannes Weiner 	struct blk_plug plug;
39021a501907SMel Gorman 	bool scan_adjusted;
39039b4f98cdSJohannes Weiner 
3904*ac35a490SYu Zhao 	if (lru_gen_enabled()) {
3905*ac35a490SYu Zhao 		lru_gen_shrink_lruvec(lruvec, sc);
3906*ac35a490SYu Zhao 		return;
3907*ac35a490SYu Zhao 	}
3908*ac35a490SYu Zhao 
3909afaf07a6SJohannes Weiner 	get_scan_count(lruvec, sc, nr);
39109b4f98cdSJohannes Weiner 
3911e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
3912e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
3913e82e0561SMel Gorman 
39141a501907SMel Gorman 	/*
39151a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
39161a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
39171a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
39181a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
39191a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
39201a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
39211a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
39221a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
39231a501907SMel Gorman 	 * dropped to zero at the first pass.
39241a501907SMel Gorman 	 */
3925b5ead35eSJohannes Weiner 	scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
39261a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
39271a501907SMel Gorman 
39289b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
39299b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
39309b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
3931e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
3932e82e0561SMel Gorman 		unsigned long nr_scanned;
3933e82e0561SMel Gorman 
39349b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
39359b4f98cdSJohannes Weiner 			if (nr[lru]) {
39369b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
39379b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
39389b4f98cdSJohannes Weiner 
39399b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
39403b991208SJohannes Weiner 							    lruvec, sc);
39419b4f98cdSJohannes Weiner 			}
39429b4f98cdSJohannes Weiner 		}
3943e82e0561SMel Gorman 
3944bd041733SMichal Hocko 		cond_resched();
3945bd041733SMichal Hocko 
3946e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
3947e82e0561SMel Gorman 			continue;
3948e82e0561SMel Gorman 
39499b4f98cdSJohannes Weiner 		/*
3950e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
39511a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
3952e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
3953e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
3954e82e0561SMel Gorman 		 * proportional to the original scan target.
3955e82e0561SMel Gorman 		 */
3956e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
3957e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
3958e82e0561SMel Gorman 
39591a501907SMel Gorman 		/*
39601a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
39611a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
39621a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
39631a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
39641a501907SMel Gorman 		 */
39651a501907SMel Gorman 		if (!nr_file || !nr_anon)
39661a501907SMel Gorman 			break;
39671a501907SMel Gorman 
3968e82e0561SMel Gorman 		if (nr_file > nr_anon) {
3969e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
3970e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
3971e82e0561SMel Gorman 			lru = LRU_BASE;
3972e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
3973e82e0561SMel Gorman 		} else {
3974e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
3975e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
3976e82e0561SMel Gorman 			lru = LRU_FILE;
3977e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
3978e82e0561SMel Gorman 		}
3979e82e0561SMel Gorman 
3980e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
3981e82e0561SMel Gorman 		nr[lru] = 0;
3982e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
3983e82e0561SMel Gorman 
3984e82e0561SMel Gorman 		/*
3985e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
3986e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
3987e82e0561SMel Gorman 		 */
3988e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
3989e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
3990e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
3991e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
3992e82e0561SMel Gorman 
3993e82e0561SMel Gorman 		lru += LRU_ACTIVE;
3994e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
3995e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
3996e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
3997e82e0561SMel Gorman 
3998e82e0561SMel Gorman 		scan_adjusted = true;
39999b4f98cdSJohannes Weiner 	}
40009b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
40019b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
40029b4f98cdSJohannes Weiner 
40039b4f98cdSJohannes Weiner 	/*
40049b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
40059b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
40069b4f98cdSJohannes Weiner 	 */
40072f368a9fSDave Hansen 	if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
40082f368a9fSDave Hansen 	    inactive_is_low(lruvec, LRU_INACTIVE_ANON))
40099b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
40109b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
40119b4f98cdSJohannes Weiner }
40129b4f98cdSJohannes Weiner 
401323b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
40149e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
401523b9da55SMel Gorman {
4016d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
401723b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
40189e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
401923b9da55SMel Gorman 		return true;
402023b9da55SMel Gorman 
402123b9da55SMel Gorman 	return false;
402223b9da55SMel Gorman }
402323b9da55SMel Gorman 
40244f98a2feSRik van Riel /*
402523b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
402623b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
402723b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
4028df3a45f9SQiwu Chen  * calls try_to_compact_pages() that it will have enough free pages to succeed.
402923b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
40303e7d3449SMel Gorman  */
4031a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
40323e7d3449SMel Gorman 					unsigned long nr_reclaimed,
40333e7d3449SMel Gorman 					struct scan_control *sc)
40343e7d3449SMel Gorman {
40353e7d3449SMel Gorman 	unsigned long pages_for_compaction;
40363e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
4037a9dd0a83SMel Gorman 	int z;
40383e7d3449SMel Gorman 
40393e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
40409e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
40413e7d3449SMel Gorman 		return false;
40423e7d3449SMel Gorman 
40433e7d3449SMel Gorman 	/*
40445ee04716SVlastimil Babka 	 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
40455ee04716SVlastimil Babka 	 * number of pages that were scanned. This will return to the caller
40465ee04716SVlastimil Babka 	 * with the risk reclaim/compaction and the resulting allocation attempt
40475ee04716SVlastimil Babka 	 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
40485ee04716SVlastimil Babka 	 * allocations through requiring that the full LRU list has been scanned
40495ee04716SVlastimil Babka 	 * first, by assuming that zero delta of sc->nr_scanned means full LRU
40505ee04716SVlastimil Babka 	 * scan, but that approximation was wrong, and there were corner cases
40515ee04716SVlastimil Babka 	 * where always a non-zero amount of pages were scanned.
40522876592fSMel Gorman 	 */
40532876592fSMel Gorman 	if (!nr_reclaimed)
40542876592fSMel Gorman 		return false;
40553e7d3449SMel Gorman 
40563e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
4057a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
4058a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
40596aa303deSMel Gorman 		if (!managed_zone(zone))
4060a9dd0a83SMel Gorman 			continue;
4061a9dd0a83SMel Gorman 
4062a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
4063cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
40643e7d3449SMel Gorman 		case COMPACT_CONTINUE:
40653e7d3449SMel Gorman 			return false;
40663e7d3449SMel Gorman 		default:
4067a9dd0a83SMel Gorman 			/* check next zone */
4068a9dd0a83SMel Gorman 			;
40693e7d3449SMel Gorman 		}
40703e7d3449SMel Gorman 	}
40711c6c1597SHillf Danton 
40721c6c1597SHillf Danton 	/*
40731c6c1597SHillf Danton 	 * If we have not reclaimed enough pages for compaction and the
40741c6c1597SHillf Danton 	 * inactive lists are large enough, continue reclaiming
40751c6c1597SHillf Danton 	 */
40761c6c1597SHillf Danton 	pages_for_compaction = compact_gap(sc->order);
40771c6c1597SHillf Danton 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
4078a2a36488SKeith Busch 	if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
40791c6c1597SHillf Danton 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
40801c6c1597SHillf Danton 
40815ee04716SVlastimil Babka 	return inactive_lru_pages > pages_for_compaction;
4082a9dd0a83SMel Gorman }
40833e7d3449SMel Gorman 
40840f6a5cffSJohannes Weiner static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
4085f16015fbSJohannes Weiner {
40860f6a5cffSJohannes Weiner 	struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
4087694fbc0fSAndrew Morton 	struct mem_cgroup *memcg;
4088d108c772SAndrey Ryabinin 
40890f6a5cffSJohannes Weiner 	memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
4090694fbc0fSAndrew Morton 	do {
4091afaf07a6SJohannes Weiner 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
40928e8ae645SJohannes Weiner 		unsigned long reclaimed;
4093cb731d6cSVladimir Davydov 		unsigned long scanned;
40949b4f98cdSJohannes Weiner 
4095e3336cabSXunlei Pang 		/*
4096e3336cabSXunlei Pang 		 * This loop can become CPU-bound when target memcgs
4097e3336cabSXunlei Pang 		 * aren't eligible for reclaim - either because they
4098e3336cabSXunlei Pang 		 * don't have any reclaimable pages, or because their
4099e3336cabSXunlei Pang 		 * memory is explicitly protected. Avoid soft lockups.
4100e3336cabSXunlei Pang 		 */
4101e3336cabSXunlei Pang 		cond_resched();
4102e3336cabSXunlei Pang 
410345c7f7e1SChris Down 		mem_cgroup_calculate_protection(target_memcg, memcg);
410445c7f7e1SChris Down 
410545c7f7e1SChris Down 		if (mem_cgroup_below_min(memcg)) {
4106bf8d5d52SRoman Gushchin 			/*
4107bf8d5d52SRoman Gushchin 			 * Hard protection.
4108bf8d5d52SRoman Gushchin 			 * If there is no reclaimable memory, OOM.
4109bf8d5d52SRoman Gushchin 			 */
4110bf8d5d52SRoman Gushchin 			continue;
411145c7f7e1SChris Down 		} else if (mem_cgroup_below_low(memcg)) {
4112bf8d5d52SRoman Gushchin 			/*
4113bf8d5d52SRoman Gushchin 			 * Soft protection.
4114bf8d5d52SRoman Gushchin 			 * Respect the protection only as long as
4115bf8d5d52SRoman Gushchin 			 * there is an unprotected supply
4116bf8d5d52SRoman Gushchin 			 * of reclaimable memory from other cgroups.
4117bf8d5d52SRoman Gushchin 			 */
4118d6622f63SYisheng Xie 			if (!sc->memcg_low_reclaim) {
4119d6622f63SYisheng Xie 				sc->memcg_low_skipped = 1;
4120241994edSJohannes Weiner 				continue;
4121d6622f63SYisheng Xie 			}
4122e27be240SJohannes Weiner 			memcg_memory_event(memcg, MEMCG_LOW);
4123241994edSJohannes Weiner 		}
4124241994edSJohannes Weiner 
41258e8ae645SJohannes Weiner 		reclaimed = sc->nr_reclaimed;
4126cb731d6cSVladimir Davydov 		scanned = sc->nr_scanned;
4127afaf07a6SJohannes Weiner 
4128afaf07a6SJohannes Weiner 		shrink_lruvec(lruvec, sc);
4129f9be23d6SKonstantin Khlebnikov 
413028360f39SMel Gorman 		shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
413128360f39SMel Gorman 			    sc->priority);
4132cb731d6cSVladimir Davydov 
41338e8ae645SJohannes Weiner 		/* Record the group's reclaim efficiency */
413473b73bacSYosry Ahmed 		if (!sc->proactive)
41358e8ae645SJohannes Weiner 			vmpressure(sc->gfp_mask, memcg, false,
41368e8ae645SJohannes Weiner 				   sc->nr_scanned - scanned,
41378e8ae645SJohannes Weiner 				   sc->nr_reclaimed - reclaimed);
41388e8ae645SJohannes Weiner 
41390f6a5cffSJohannes Weiner 	} while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
41400f6a5cffSJohannes Weiner }
41410f6a5cffSJohannes Weiner 
41426c9e0907SLiu Song static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
41430f6a5cffSJohannes Weiner {
41440f6a5cffSJohannes Weiner 	struct reclaim_state *reclaim_state = current->reclaim_state;
41450f6a5cffSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
41461b05117dSJohannes Weiner 	struct lruvec *target_lruvec;
41470f6a5cffSJohannes Weiner 	bool reclaimable = false;
41480f6a5cffSJohannes Weiner 
41491b05117dSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
41501b05117dSJohannes Weiner 
41510f6a5cffSJohannes Weiner again:
41520f6a5cffSJohannes Weiner 	memset(&sc->nr, 0, sizeof(sc->nr));
41530f6a5cffSJohannes Weiner 
41540f6a5cffSJohannes Weiner 	nr_reclaimed = sc->nr_reclaimed;
41550f6a5cffSJohannes Weiner 	nr_scanned = sc->nr_scanned;
41560f6a5cffSJohannes Weiner 
4157f1e1a7beSYu Zhao 	prepare_scan_count(pgdat, sc);
415853138ceaSJohannes Weiner 
41590f6a5cffSJohannes Weiner 	shrink_node_memcgs(pgdat, sc);
416070ddf637SAnton Vorontsov 
41616b4f7799SJohannes Weiner 	if (reclaim_state) {
4162cb731d6cSVladimir Davydov 		sc->nr_reclaimed += reclaim_state->reclaimed_slab;
41636b4f7799SJohannes Weiner 		reclaim_state->reclaimed_slab = 0;
41646b4f7799SJohannes Weiner 	}
41656b4f7799SJohannes Weiner 
41668e8ae645SJohannes Weiner 	/* Record the subtree's reclaim efficiency */
416773b73bacSYosry Ahmed 	if (!sc->proactive)
41681b05117dSJohannes Weiner 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
416970ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
417070ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
417170ddf637SAnton Vorontsov 
41722344d7e4SJohannes Weiner 	if (sc->nr_reclaimed - nr_reclaimed)
41732344d7e4SJohannes Weiner 		reclaimable = true;
41742344d7e4SJohannes Weiner 
4175e3c1ac58SAndrey Ryabinin 	if (current_is_kswapd()) {
4176d108c772SAndrey Ryabinin 		/*
4177e3c1ac58SAndrey Ryabinin 		 * If reclaim is isolating dirty pages under writeback,
4178e3c1ac58SAndrey Ryabinin 		 * it implies that the long-lived page allocation rate
4179e3c1ac58SAndrey Ryabinin 		 * is exceeding the page laundering rate. Either the
4180e3c1ac58SAndrey Ryabinin 		 * global limits are not being effective at throttling
4181e3c1ac58SAndrey Ryabinin 		 * processes due to the page distribution throughout
4182e3c1ac58SAndrey Ryabinin 		 * zones or there is heavy usage of a slow backing
4183e3c1ac58SAndrey Ryabinin 		 * device. The only option is to throttle from reclaim
4184e3c1ac58SAndrey Ryabinin 		 * context which is not ideal as there is no guarantee
4185d108c772SAndrey Ryabinin 		 * the dirtying process is throttled in the same way
4186d108c772SAndrey Ryabinin 		 * balance_dirty_pages() manages.
4187d108c772SAndrey Ryabinin 		 *
4188e3c1ac58SAndrey Ryabinin 		 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
4189e3c1ac58SAndrey Ryabinin 		 * count the number of pages under pages flagged for
4190e3c1ac58SAndrey Ryabinin 		 * immediate reclaim and stall if any are encountered
4191e3c1ac58SAndrey Ryabinin 		 * in the nr_immediate check below.
4192d108c772SAndrey Ryabinin 		 */
4193d108c772SAndrey Ryabinin 		if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
4194d108c772SAndrey Ryabinin 			set_bit(PGDAT_WRITEBACK, &pgdat->flags);
4195d108c772SAndrey Ryabinin 
4196d108c772SAndrey Ryabinin 		/* Allow kswapd to start writing pages during reclaim.*/
4197d108c772SAndrey Ryabinin 		if (sc->nr.unqueued_dirty == sc->nr.file_taken)
4198d108c772SAndrey Ryabinin 			set_bit(PGDAT_DIRTY, &pgdat->flags);
4199d108c772SAndrey Ryabinin 
4200d108c772SAndrey Ryabinin 		/*
42011eba09c1SRandy Dunlap 		 * If kswapd scans pages marked for immediate
4202d108c772SAndrey Ryabinin 		 * reclaim and under writeback (nr_immediate), it
4203d108c772SAndrey Ryabinin 		 * implies that pages are cycling through the LRU
42048cd7c588SMel Gorman 		 * faster than they are written so forcibly stall
42058cd7c588SMel Gorman 		 * until some pages complete writeback.
4206d108c772SAndrey Ryabinin 		 */
4207d108c772SAndrey Ryabinin 		if (sc->nr.immediate)
4208c3f4a9a2SMel Gorman 			reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
4209d108c772SAndrey Ryabinin 	}
4210d108c772SAndrey Ryabinin 
4211d108c772SAndrey Ryabinin 	/*
42128cd7c588SMel Gorman 	 * Tag a node/memcg as congested if all the dirty pages were marked
42138cd7c588SMel Gorman 	 * for writeback and immediate reclaim (counted in nr.congested).
42141b05117dSJohannes Weiner 	 *
4215e3c1ac58SAndrey Ryabinin 	 * Legacy memcg will stall in page writeback so avoid forcibly
42168cd7c588SMel Gorman 	 * stalling in reclaim_throttle().
4217e3c1ac58SAndrey Ryabinin 	 */
42181b05117dSJohannes Weiner 	if ((current_is_kswapd() ||
42191b05117dSJohannes Weiner 	     (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
4220e3c1ac58SAndrey Ryabinin 	    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
42211b05117dSJohannes Weiner 		set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
4222e3c1ac58SAndrey Ryabinin 
4223e3c1ac58SAndrey Ryabinin 	/*
42248cd7c588SMel Gorman 	 * Stall direct reclaim for IO completions if the lruvec is
42258cd7c588SMel Gorman 	 * node is congested. Allow kswapd to continue until it
4226d108c772SAndrey Ryabinin 	 * starts encountering unqueued dirty pages or cycling through
4227d108c772SAndrey Ryabinin 	 * the LRU too quickly.
4228d108c772SAndrey Ryabinin 	 */
42291b05117dSJohannes Weiner 	if (!current_is_kswapd() && current_may_throttle() &&
42301b05117dSJohannes Weiner 	    !sc->hibernation_mode &&
42311b05117dSJohannes Weiner 	    test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
42321b4e3f26SMel Gorman 		reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED);
4233d108c772SAndrey Ryabinin 
4234d2af3397SJohannes Weiner 	if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
4235d2af3397SJohannes Weiner 				    sc))
4236d2af3397SJohannes Weiner 		goto again;
42372344d7e4SJohannes Weiner 
4238c73322d0SJohannes Weiner 	/*
4239c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
4240c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
4241c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
4242c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
4243c73322d0SJohannes Weiner 	 */
4244c73322d0SJohannes Weiner 	if (reclaimable)
4245c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
4246f16015fbSJohannes Weiner }
4247f16015fbSJohannes Weiner 
424853853e2dSVlastimil Babka /*
4249fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
4250fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
4251fdd4c614SVlastimil Babka  * should reclaim first.
425253853e2dSVlastimil Babka  */
42534f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
4254fe4b1b24SMel Gorman {
425531483b6aSMel Gorman 	unsigned long watermark;
4256fdd4c614SVlastimil Babka 	enum compact_result suitable;
4257fe4b1b24SMel Gorman 
4258fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
4259fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
4260fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
4261fdd4c614SVlastimil Babka 		return true;
4262fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
4263fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
4264fe4b1b24SMel Gorman 		return false;
4265fe4b1b24SMel Gorman 
4266fdd4c614SVlastimil Babka 	/*
4267fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
4268fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
4269fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
4270fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
4271fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
4272fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
4273fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
4274fdd4c614SVlastimil Babka 	 */
4275fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
4276fdd4c614SVlastimil Babka 
4277fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
4278fe4b1b24SMel Gorman }
4279fe4b1b24SMel Gorman 
428069392a40SMel Gorman static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc)
428169392a40SMel Gorman {
428266ce520bSMel Gorman 	/*
428366ce520bSMel Gorman 	 * If reclaim is making progress greater than 12% efficiency then
428466ce520bSMel Gorman 	 * wake all the NOPROGRESS throttled tasks.
428566ce520bSMel Gorman 	 */
428666ce520bSMel Gorman 	if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) {
428769392a40SMel Gorman 		wait_queue_head_t *wqh;
428869392a40SMel Gorman 
428969392a40SMel Gorman 		wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS];
429069392a40SMel Gorman 		if (waitqueue_active(wqh))
429169392a40SMel Gorman 			wake_up(wqh);
429269392a40SMel Gorman 
429369392a40SMel Gorman 		return;
429469392a40SMel Gorman 	}
429569392a40SMel Gorman 
429669392a40SMel Gorman 	/*
42971b4e3f26SMel Gorman 	 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will
42981b4e3f26SMel Gorman 	 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages
42991b4e3f26SMel Gorman 	 * under writeback and marked for immediate reclaim at the tail of the
43001b4e3f26SMel Gorman 	 * LRU.
430169392a40SMel Gorman 	 */
43021b4e3f26SMel Gorman 	if (current_is_kswapd() || cgroup_reclaim(sc))
430369392a40SMel Gorman 		return;
430469392a40SMel Gorman 
430569392a40SMel Gorman 	/* Throttle if making no progress at high prioities. */
43061b4e3f26SMel Gorman 	if (sc->priority == 1 && !sc->nr_reclaimed)
4307c3f4a9a2SMel Gorman 		reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS);
430869392a40SMel Gorman }
430969392a40SMel Gorman 
43101da177e4SLinus Torvalds /*
43111da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
43121da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
43131da177e4SLinus Torvalds  * request.
43141da177e4SLinus Torvalds  *
43151da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
43161da177e4SLinus Torvalds  * scan then give up on it.
43171da177e4SLinus Torvalds  */
43180a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
43191da177e4SLinus Torvalds {
4320dd1a239fSMel Gorman 	struct zoneref *z;
432154a6eb5cSMel Gorman 	struct zone *zone;
43220608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
43230608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
4324619d0d76SWeijie Yang 	gfp_t orig_mask;
432579dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
43261b4e3f26SMel Gorman 	pg_data_t *first_pgdat = NULL;
43271cfb419bSKAMEZAWA Hiroyuki 
4328cc715d99SMel Gorman 	/*
4329cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
4330cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
4331cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
4332cc715d99SMel Gorman 	 */
4333619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
4334b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
4335cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
43364f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
4337b2e18757SMel Gorman 	}
4338cc715d99SMel Gorman 
4339d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
4340b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
4341b2e18757SMel Gorman 		/*
43421cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
43431cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
43441cfb419bSKAMEZAWA Hiroyuki 		 */
4345b5ead35eSJohannes Weiner 		if (!cgroup_reclaim(sc)) {
4346344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
4347344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
43481da177e4SLinus Torvalds 				continue;
434965ec02cbSVladimir Davydov 
4350e0887c19SRik van Riel 			/*
4351e0c23279SMel Gorman 			 * If we already have plenty of memory free for
4352e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
4353e0c23279SMel Gorman 			 * Even though compaction is invoked for any
4354e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
4355e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
4356c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
4357c7cfa37bSCopot Alexandru 			 * page allocations.
4358e0887c19SRik van Riel 			 */
43590b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
43600b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
43614f588331SMel Gorman 			    compaction_ready(zone, sc)) {
43620b06496aSJohannes Weiner 				sc->compaction_ready = true;
4363e0887c19SRik van Riel 				continue;
4364e0887c19SRik van Riel 			}
43650b06496aSJohannes Weiner 
43660608f43dSAndrew Morton 			/*
436779dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
436879dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
436979dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
437079dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
437179dafcdcSMel Gorman 			 */
437279dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
437379dafcdcSMel Gorman 				continue;
437479dafcdcSMel Gorman 
437579dafcdcSMel Gorman 			/*
43760608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
43770608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
43780608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
43790608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
43800608f43dSAndrew Morton 			 */
43810608f43dSAndrew Morton 			nr_soft_scanned = 0;
4382ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
43830608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
43840608f43dSAndrew Morton 						&nr_soft_scanned);
43850608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
43860608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
4387ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
4388ac34a1a3SKAMEZAWA Hiroyuki 		}
4389d149e3b2SYing Han 
43901b4e3f26SMel Gorman 		if (!first_pgdat)
43911b4e3f26SMel Gorman 			first_pgdat = zone->zone_pgdat;
43921b4e3f26SMel Gorman 
439379dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
439479dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
439579dafcdcSMel Gorman 			continue;
439679dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
4397970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
43981da177e4SLinus Torvalds 	}
4399e0c23279SMel Gorman 
440080082938SMel Gorman 	if (first_pgdat)
44011b4e3f26SMel Gorman 		consider_reclaim_throttle(first_pgdat, sc);
44021b4e3f26SMel Gorman 
440365ec02cbSVladimir Davydov 	/*
4404619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
4405619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
4406619d0d76SWeijie Yang 	 */
4407619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
44081da177e4SLinus Torvalds }
44091da177e4SLinus Torvalds 
4410b910718aSJohannes Weiner static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
44112a2e4885SJohannes Weiner {
4412b910718aSJohannes Weiner 	struct lruvec *target_lruvec;
44132a2e4885SJohannes Weiner 	unsigned long refaults;
44142a2e4885SJohannes Weiner 
4415*ac35a490SYu Zhao 	if (lru_gen_enabled())
4416*ac35a490SYu Zhao 		return;
4417*ac35a490SYu Zhao 
4418b910718aSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
4419170b04b7SJoonsoo Kim 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
4420e9c2dbc8SYang Yang 	target_lruvec->refaults[WORKINGSET_ANON] = refaults;
4421170b04b7SJoonsoo Kim 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
4422e9c2dbc8SYang Yang 	target_lruvec->refaults[WORKINGSET_FILE] = refaults;
44232a2e4885SJohannes Weiner }
44242a2e4885SJohannes Weiner 
44251da177e4SLinus Torvalds /*
44261da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
44271da177e4SLinus Torvalds  *
44281da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
44291da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
44301da177e4SLinus Torvalds  *
44311da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
44321da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
44335b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
44345b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
44355b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
44365b0830cbSJens Axboe  * work, and the allocation attempt will fail.
4437a41f24eaSNishanth Aravamudan  *
4438a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
4439a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
44401da177e4SLinus Torvalds  */
4441dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
44423115cd91SVladimir Davydov 					  struct scan_control *sc)
44431da177e4SLinus Torvalds {
4444241994edSJohannes Weiner 	int initial_priority = sc->priority;
44452a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
44462a2e4885SJohannes Weiner 	struct zoneref *z;
44472a2e4885SJohannes Weiner 	struct zone *zone;
4448241994edSJohannes Weiner retry:
4449873b4771SKeika Kobayashi 	delayacct_freepages_start();
4450873b4771SKeika Kobayashi 
4451b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
44527cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
44531da177e4SLinus Torvalds 
44549e3b2f8cSKonstantin Khlebnikov 	do {
445573b73bacSYosry Ahmed 		if (!sc->proactive)
445670ddf637SAnton Vorontsov 			vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
445770ddf637SAnton Vorontsov 					sc->priority);
445866e1707bSBalbir Singh 		sc->nr_scanned = 0;
44590a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
4460e0c23279SMel Gorman 
4461bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
44620b06496aSJohannes Weiner 			break;
44630b06496aSJohannes Weiner 
44640b06496aSJohannes Weiner 		if (sc->compaction_ready)
44650b06496aSJohannes Weiner 			break;
44661da177e4SLinus Torvalds 
44671da177e4SLinus Torvalds 		/*
44680e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
44690e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
44700e50ce3bSMinchan Kim 		 */
44710e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
44720e50ce3bSMinchan Kim 			sc->may_writepage = 1;
44730b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
4474bb21c7ceSKOSAKI Motohiro 
44752a2e4885SJohannes Weiner 	last_pgdat = NULL;
44762a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
44772a2e4885SJohannes Weiner 					sc->nodemask) {
44782a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
44792a2e4885SJohannes Weiner 			continue;
44802a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
44811b05117dSJohannes Weiner 
44822a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
44831b05117dSJohannes Weiner 
44841b05117dSJohannes Weiner 		if (cgroup_reclaim(sc)) {
44851b05117dSJohannes Weiner 			struct lruvec *lruvec;
44861b05117dSJohannes Weiner 
44871b05117dSJohannes Weiner 			lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
44881b05117dSJohannes Weiner 						   zone->zone_pgdat);
44891b05117dSJohannes Weiner 			clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
44901b05117dSJohannes Weiner 		}
44912a2e4885SJohannes Weiner 	}
44922a2e4885SJohannes Weiner 
4493873b4771SKeika Kobayashi 	delayacct_freepages_end();
4494873b4771SKeika Kobayashi 
4495bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
4496bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
4497bb21c7ceSKOSAKI Motohiro 
44980cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
44990b06496aSJohannes Weiner 	if (sc->compaction_ready)
45007335084dSMel Gorman 		return 1;
45017335084dSMel Gorman 
4502b91ac374SJohannes Weiner 	/*
4503b91ac374SJohannes Weiner 	 * We make inactive:active ratio decisions based on the node's
4504b91ac374SJohannes Weiner 	 * composition of memory, but a restrictive reclaim_idx or a
4505b91ac374SJohannes Weiner 	 * memory.low cgroup setting can exempt large amounts of
4506b91ac374SJohannes Weiner 	 * memory from reclaim. Neither of which are very common, so
4507b91ac374SJohannes Weiner 	 * instead of doing costly eligibility calculations of the
4508b91ac374SJohannes Weiner 	 * entire cgroup subtree up front, we assume the estimates are
4509b91ac374SJohannes Weiner 	 * good, and retry with forcible deactivation if that fails.
4510b91ac374SJohannes Weiner 	 */
4511b91ac374SJohannes Weiner 	if (sc->skipped_deactivate) {
4512b91ac374SJohannes Weiner 		sc->priority = initial_priority;
4513b91ac374SJohannes Weiner 		sc->force_deactivate = 1;
4514b91ac374SJohannes Weiner 		sc->skipped_deactivate = 0;
4515b91ac374SJohannes Weiner 		goto retry;
4516b91ac374SJohannes Weiner 	}
4517b91ac374SJohannes Weiner 
4518241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
4519d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
4520241994edSJohannes Weiner 		sc->priority = initial_priority;
4521b91ac374SJohannes Weiner 		sc->force_deactivate = 0;
4522d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
4523d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
4524241994edSJohannes Weiner 		goto retry;
4525241994edSJohannes Weiner 	}
4526241994edSJohannes Weiner 
4527bb21c7ceSKOSAKI Motohiro 	return 0;
45281da177e4SLinus Torvalds }
45291da177e4SLinus Torvalds 
4530c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
45315515061dSMel Gorman {
45325515061dSMel Gorman 	struct zone *zone;
45335515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
45345515061dSMel Gorman 	unsigned long free_pages = 0;
45355515061dSMel Gorman 	int i;
45365515061dSMel Gorman 	bool wmark_ok;
45375515061dSMel Gorman 
4538c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
4539c73322d0SJohannes Weiner 		return true;
4540c73322d0SJohannes Weiner 
45415515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
45425515061dSMel Gorman 		zone = &pgdat->node_zones[i];
4543d450abd8SJohannes Weiner 		if (!managed_zone(zone))
4544d450abd8SJohannes Weiner 			continue;
4545d450abd8SJohannes Weiner 
4546d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
4547675becceSMel Gorman 			continue;
4548675becceSMel Gorman 
45495515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
45505515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
45515515061dSMel Gorman 	}
45525515061dSMel Gorman 
4553675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
4554675becceSMel Gorman 	if (!pfmemalloc_reserve)
4555675becceSMel Gorman 		return true;
4556675becceSMel Gorman 
45575515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
45585515061dSMel Gorman 
45595515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
45605515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
456197a225e6SJoonsoo Kim 		if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
456297a225e6SJoonsoo Kim 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
45635644e1fbSQian Cai 
45645515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
45655515061dSMel Gorman 	}
45665515061dSMel Gorman 
45675515061dSMel Gorman 	return wmark_ok;
45685515061dSMel Gorman }
45695515061dSMel Gorman 
45705515061dSMel Gorman /*
45715515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
45725515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
45735515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
457450694c28SMel Gorman  * when the low watermark is reached.
457550694c28SMel Gorman  *
457650694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
457750694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
45785515061dSMel Gorman  */
457950694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
45805515061dSMel Gorman 					nodemask_t *nodemask)
45815515061dSMel Gorman {
4582675becceSMel Gorman 	struct zoneref *z;
45835515061dSMel Gorman 	struct zone *zone;
4584675becceSMel Gorman 	pg_data_t *pgdat = NULL;
45855515061dSMel Gorman 
45865515061dSMel Gorman 	/*
45875515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
45885515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
45895515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
45905515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
45915515061dSMel Gorman 	 * processes to block on log_wait_commit().
45925515061dSMel Gorman 	 */
45935515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
459450694c28SMel Gorman 		goto out;
459550694c28SMel Gorman 
459650694c28SMel Gorman 	/*
459750694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
459850694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
459950694c28SMel Gorman 	 */
460050694c28SMel Gorman 	if (fatal_signal_pending(current))
460150694c28SMel Gorman 		goto out;
46025515061dSMel Gorman 
4603675becceSMel Gorman 	/*
4604675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
4605675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
4606675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
4607675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
4608675becceSMel Gorman 	 *
4609675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
4610675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
4611675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
4612675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
4613675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
4614675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
4615675becceSMel Gorman 	 * should make reasonable progress.
4616675becceSMel Gorman 	 */
4617675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
461817636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
4619675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
4620675becceSMel Gorman 			continue;
4621675becceSMel Gorman 
4622675becceSMel Gorman 		/* Throttle based on the first usable node */
46235515061dSMel Gorman 		pgdat = zone->zone_pgdat;
4624c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
462550694c28SMel Gorman 			goto out;
4626675becceSMel Gorman 		break;
4627675becceSMel Gorman 	}
4628675becceSMel Gorman 
4629675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
4630675becceSMel Gorman 	if (!pgdat)
4631675becceSMel Gorman 		goto out;
46325515061dSMel Gorman 
463368243e76SMel Gorman 	/* Account for the throttling */
463468243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
463568243e76SMel Gorman 
46365515061dSMel Gorman 	/*
46375515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
46385515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
46395515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
46405515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
46415515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
46425515061dSMel Gorman 	 * second before continuing.
46435515061dSMel Gorman 	 */
46442e786d9eSMiaohe Lin 	if (!(gfp_mask & __GFP_FS))
46455515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
4646c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
46472e786d9eSMiaohe Lin 	else
46485515061dSMel Gorman 		/* Throttle until kswapd wakes the process */
46495515061dSMel Gorman 		wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
4650c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat));
465150694c28SMel Gorman 
465250694c28SMel Gorman 	if (fatal_signal_pending(current))
465350694c28SMel Gorman 		return true;
465450694c28SMel Gorman 
465550694c28SMel Gorman out:
465650694c28SMel Gorman 	return false;
46575515061dSMel Gorman }
46585515061dSMel Gorman 
4659dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
4660327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
466166e1707bSBalbir Singh {
466233906bc5SMel Gorman 	unsigned long nr_reclaimed;
466366e1707bSBalbir Singh 	struct scan_control sc = {
466422fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
4665f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
4666b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
4667ee814fe2SJohannes Weiner 		.order = order,
4668ee814fe2SJohannes Weiner 		.nodemask = nodemask,
4669ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
4670ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
4671a6dc60f8SJohannes Weiner 		.may_unmap = 1,
46722e2e4259SKOSAKI Motohiro 		.may_swap = 1,
467366e1707bSBalbir Singh 	};
467466e1707bSBalbir Singh 
46755515061dSMel Gorman 	/*
4676bb451fdfSGreg Thelen 	 * scan_control uses s8 fields for order, priority, and reclaim_idx.
4677bb451fdfSGreg Thelen 	 * Confirm they are large enough for max values.
4678bb451fdfSGreg Thelen 	 */
4679bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_ORDER > S8_MAX);
4680bb451fdfSGreg Thelen 	BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
4681bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
4682bb451fdfSGreg Thelen 
4683bb451fdfSGreg Thelen 	/*
468450694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
468550694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
468650694c28SMel Gorman 	 * point.
46875515061dSMel Gorman 	 */
4688f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
46895515061dSMel Gorman 		return 1;
46905515061dSMel Gorman 
46911732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
46923481c37fSYafang Shao 	trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
469333906bc5SMel Gorman 
46943115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
469533906bc5SMel Gorman 
469633906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
46971732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
469833906bc5SMel Gorman 
469933906bc5SMel Gorman 	return nr_reclaimed;
470066e1707bSBalbir Singh }
470166e1707bSBalbir Singh 
4702c255a458SAndrew Morton #ifdef CONFIG_MEMCG
470366e1707bSBalbir Singh 
4704d2e5fb92SMichal Hocko /* Only used by soft limit reclaim. Do not reuse for anything else. */
4705a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
47064e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
4707ef8f2327SMel Gorman 						pg_data_t *pgdat,
47080ae5e89cSYing Han 						unsigned long *nr_scanned)
47094e416953SBalbir Singh {
4710afaf07a6SJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
47114e416953SBalbir Singh 	struct scan_control sc = {
4712b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
4713ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
47144e416953SBalbir Singh 		.may_writepage = !laptop_mode,
47154e416953SBalbir Singh 		.may_unmap = 1,
4716b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
47174e416953SBalbir Singh 		.may_swap = !noswap,
47184e416953SBalbir Singh 	};
47190ae5e89cSYing Han 
4720d2e5fb92SMichal Hocko 	WARN_ON_ONCE(!current->reclaim_state);
4721d2e5fb92SMichal Hocko 
47224e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
47234e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
4724bdce6d9eSKOSAKI Motohiro 
47259e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
47263481c37fSYafang Shao 						      sc.gfp_mask);
4727bdce6d9eSKOSAKI Motohiro 
47284e416953SBalbir Singh 	/*
47294e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
47304e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
4731a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
47324e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
47334e416953SBalbir Singh 	 * the priority and make it zero.
47344e416953SBalbir Singh 	 */
4735afaf07a6SJohannes Weiner 	shrink_lruvec(lruvec, &sc);
4736bdce6d9eSKOSAKI Motohiro 
4737bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
4738bdce6d9eSKOSAKI Motohiro 
47390ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
47400308f7cfSYafang Shao 
47414e416953SBalbir Singh 	return sc.nr_reclaimed;
47424e416953SBalbir Singh }
47434e416953SBalbir Singh 
474472835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
4745b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
47468c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
474773b73bacSYosry Ahmed 					   unsigned int reclaim_options)
474866e1707bSBalbir Singh {
4749bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
4750499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
475166e1707bSBalbir Singh 	struct scan_control sc = {
4752b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
47537dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
4754ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
4755b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
4756ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
4757ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
475866e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
4759a6dc60f8SJohannes Weiner 		.may_unmap = 1,
476073b73bacSYosry Ahmed 		.may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
476173b73bacSYosry Ahmed 		.proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
4762a09ed5e0SYing Han 	};
4763fa40d1eeSShakeel Butt 	/*
4764fa40d1eeSShakeel Butt 	 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
4765fa40d1eeSShakeel Butt 	 * equal pressure on all the nodes. This is based on the assumption that
4766fa40d1eeSShakeel Butt 	 * the reclaim does not bail out early.
4767fa40d1eeSShakeel Butt 	 */
4768fa40d1eeSShakeel Butt 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
476966e1707bSBalbir Singh 
47701732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
47713481c37fSYafang Shao 	trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
4772499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
4773eb414681SJohannes Weiner 
47743115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4775eb414681SJohannes Weiner 
4776499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
4777bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
47781732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
4779bdce6d9eSKOSAKI Motohiro 
4780bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
478166e1707bSBalbir Singh }
478266e1707bSBalbir Singh #endif
478366e1707bSBalbir Singh 
4784*ac35a490SYu Zhao static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4785f16015fbSJohannes Weiner {
4786b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
4787b91ac374SJohannes Weiner 	struct lruvec *lruvec;
4788b95a2f2dSJohannes Weiner 
4789*ac35a490SYu Zhao 	if (lru_gen_enabled()) {
4790*ac35a490SYu Zhao 		lru_gen_age_node(pgdat, sc);
4791*ac35a490SYu Zhao 		return;
4792*ac35a490SYu Zhao 	}
4793*ac35a490SYu Zhao 
47942f368a9fSDave Hansen 	if (!can_age_anon_pages(pgdat, sc))
4795b95a2f2dSJohannes Weiner 		return;
4796b95a2f2dSJohannes Weiner 
4797b91ac374SJohannes Weiner 	lruvec = mem_cgroup_lruvec(NULL, pgdat);
4798b91ac374SJohannes Weiner 	if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
4799b91ac374SJohannes Weiner 		return;
4800b91ac374SJohannes Weiner 
4801b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
4802b95a2f2dSJohannes Weiner 	do {
4803b91ac374SJohannes Weiner 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
48041a93be0eSKonstantin Khlebnikov 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
48059e3b2f8cSKonstantin Khlebnikov 				   sc, LRU_ACTIVE_ANON);
4806b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
4807b95a2f2dSJohannes Weiner 	} while (memcg);
4808f16015fbSJohannes Weiner }
4809f16015fbSJohannes Weiner 
481097a225e6SJoonsoo Kim static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
48111c30844dSMel Gorman {
48121c30844dSMel Gorman 	int i;
48131c30844dSMel Gorman 	struct zone *zone;
48141c30844dSMel Gorman 
48151c30844dSMel Gorman 	/*
48161c30844dSMel Gorman 	 * Check for watermark boosts top-down as the higher zones
48171c30844dSMel Gorman 	 * are more likely to be boosted. Both watermarks and boosts
48181eba09c1SRandy Dunlap 	 * should not be checked at the same time as reclaim would
48191c30844dSMel Gorman 	 * start prematurely when there is no boosting and a lower
48201c30844dSMel Gorman 	 * zone is balanced.
48211c30844dSMel Gorman 	 */
482297a225e6SJoonsoo Kim 	for (i = highest_zoneidx; i >= 0; i--) {
48231c30844dSMel Gorman 		zone = pgdat->node_zones + i;
48241c30844dSMel Gorman 		if (!managed_zone(zone))
48251c30844dSMel Gorman 			continue;
48261c30844dSMel Gorman 
48271c30844dSMel Gorman 		if (zone->watermark_boost)
48281c30844dSMel Gorman 			return true;
48291c30844dSMel Gorman 	}
48301c30844dSMel Gorman 
48311c30844dSMel Gorman 	return false;
48321c30844dSMel Gorman }
48331c30844dSMel Gorman 
4834e716f2ebSMel Gorman /*
4835e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
483697a225e6SJoonsoo Kim  * and highest_zoneidx
4837e716f2ebSMel Gorman  */
483897a225e6SJoonsoo Kim static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
483960cefed4SJohannes Weiner {
4840e716f2ebSMel Gorman 	int i;
4841e716f2ebSMel Gorman 	unsigned long mark = -1;
4842e716f2ebSMel Gorman 	struct zone *zone;
484360cefed4SJohannes Weiner 
48441c30844dSMel Gorman 	/*
48451c30844dSMel Gorman 	 * Check watermarks bottom-up as lower zones are more likely to
48461c30844dSMel Gorman 	 * meet watermarks.
48471c30844dSMel Gorman 	 */
484897a225e6SJoonsoo Kim 	for (i = 0; i <= highest_zoneidx; i++) {
4849e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
48506256c6b4SMel Gorman 
4851e716f2ebSMel Gorman 		if (!managed_zone(zone))
4852e716f2ebSMel Gorman 			continue;
4853e716f2ebSMel Gorman 
4854c574bbe9SHuang Ying 		if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
4855c574bbe9SHuang Ying 			mark = wmark_pages(zone, WMARK_PROMO);
4856c574bbe9SHuang Ying 		else
4857e716f2ebSMel Gorman 			mark = high_wmark_pages(zone);
485897a225e6SJoonsoo Kim 		if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
48596256c6b4SMel Gorman 			return true;
486060cefed4SJohannes Weiner 	}
486160cefed4SJohannes Weiner 
4862e716f2ebSMel Gorman 	/*
486336c26128SWei Yang 	 * If a node has no managed zone within highest_zoneidx, it does not
4864e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
4865e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
4866e716f2ebSMel Gorman 	 */
4867e716f2ebSMel Gorman 	if (mark == -1)
4868e716f2ebSMel Gorman 		return true;
4869e716f2ebSMel Gorman 
4870e716f2ebSMel Gorman 	return false;
4871e716f2ebSMel Gorman }
4872e716f2ebSMel Gorman 
4873631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
4874631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
4875631b6e08SMel Gorman {
48761b05117dSJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
48771b05117dSJohannes Weiner 
48781b05117dSJohannes Weiner 	clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
4879631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
4880631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
4881631b6e08SMel Gorman }
4882631b6e08SMel Gorman 
48831741c877SMel Gorman /*
48845515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
48855515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
48865515061dSMel Gorman  *
48875515061dSMel Gorman  * Returns true if kswapd is ready to sleep
48885515061dSMel Gorman  */
488997a225e6SJoonsoo Kim static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
489097a225e6SJoonsoo Kim 				int highest_zoneidx)
4891f50de2d3SMel Gorman {
48925515061dSMel Gorman 	/*
48939e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
4894c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
48959e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
48969e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
48979e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
48989e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
48999e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
49009e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
49019e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
49029e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
49039e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
49045515061dSMel Gorman 	 */
49059e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
49069e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
4907f50de2d3SMel Gorman 
4908c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
4909c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
4910c73322d0SJohannes Weiner 		return true;
4911c73322d0SJohannes Weiner 
491297a225e6SJoonsoo Kim 	if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
4913631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
4914333b0a45SShantanu Goel 		return true;
49151d82de61SMel Gorman 	}
49161d82de61SMel Gorman 
4917333b0a45SShantanu Goel 	return false;
4918f50de2d3SMel Gorman }
4919f50de2d3SMel Gorman 
49201da177e4SLinus Torvalds /*
49211d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
49221d82de61SMel Gorman  * zone that is currently unbalanced.
4923b8e83b94SMel Gorman  *
4924b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
4925283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
4926283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
492775485363SMel Gorman  */
49281d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
4929accf6242SVlastimil Babka 			       struct scan_control *sc)
493075485363SMel Gorman {
49311d82de61SMel Gorman 	struct zone *zone;
49321d82de61SMel Gorman 	int z;
493375485363SMel Gorman 
49341d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
49351d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
4936970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
49371d82de61SMel Gorman 		zone = pgdat->node_zones + z;
49386aa303deSMel Gorman 		if (!managed_zone(zone))
49391d82de61SMel Gorman 			continue;
49407c954f6dSMel Gorman 
49411d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
49427c954f6dSMel Gorman 	}
49437c954f6dSMel Gorman 
49441d82de61SMel Gorman 	/*
49451d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
49461d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
49471d82de61SMel Gorman 	 */
4948970a39a3SMel Gorman 	shrink_node(pgdat, sc);
49491d82de61SMel Gorman 
49501d82de61SMel Gorman 	/*
49511d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
49521d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
49531d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
49541d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
49551d82de61SMel Gorman 	 * can direct reclaim/compact.
49561d82de61SMel Gorman 	 */
49579861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
49581d82de61SMel Gorman 		sc->order = 0;
49591d82de61SMel Gorman 
4960b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
496175485363SMel Gorman }
496275485363SMel Gorman 
4963c49c2c47SMel Gorman /* Page allocator PCP high watermark is lowered if reclaim is active. */
4964c49c2c47SMel Gorman static inline void
4965c49c2c47SMel Gorman update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
4966c49c2c47SMel Gorman {
4967c49c2c47SMel Gorman 	int i;
4968c49c2c47SMel Gorman 	struct zone *zone;
4969c49c2c47SMel Gorman 
4970c49c2c47SMel Gorman 	for (i = 0; i <= highest_zoneidx; i++) {
4971c49c2c47SMel Gorman 		zone = pgdat->node_zones + i;
4972c49c2c47SMel Gorman 
4973c49c2c47SMel Gorman 		if (!managed_zone(zone))
4974c49c2c47SMel Gorman 			continue;
4975c49c2c47SMel Gorman 
4976c49c2c47SMel Gorman 		if (active)
4977c49c2c47SMel Gorman 			set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
4978c49c2c47SMel Gorman 		else
4979c49c2c47SMel Gorman 			clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
4980c49c2c47SMel Gorman 	}
4981c49c2c47SMel Gorman }
4982c49c2c47SMel Gorman 
4983c49c2c47SMel Gorman static inline void
4984c49c2c47SMel Gorman set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
4985c49c2c47SMel Gorman {
4986c49c2c47SMel Gorman 	update_reclaim_active(pgdat, highest_zoneidx, true);
4987c49c2c47SMel Gorman }
4988c49c2c47SMel Gorman 
4989c49c2c47SMel Gorman static inline void
4990c49c2c47SMel Gorman clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
4991c49c2c47SMel Gorman {
4992c49c2c47SMel Gorman 	update_reclaim_active(pgdat, highest_zoneidx, false);
4993c49c2c47SMel Gorman }
4994c49c2c47SMel Gorman 
499575485363SMel Gorman /*
49961d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
49971d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
49981d82de61SMel Gorman  * balanced.
49991da177e4SLinus Torvalds  *
50001d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
50011da177e4SLinus Torvalds  *
50021da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
500341858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
50048bb4e7a2SWei Yang  * found to have free_pages <= high_wmark_pages(zone), any page in that zone
50051d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
50061d82de61SMel Gorman  * balanced.
50071da177e4SLinus Torvalds  */
500897a225e6SJoonsoo Kim static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
50091da177e4SLinus Torvalds {
50101da177e4SLinus Torvalds 	int i;
50110608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
50120608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
5013eb414681SJohannes Weiner 	unsigned long pflags;
50141c30844dSMel Gorman 	unsigned long nr_boost_reclaim;
50151c30844dSMel Gorman 	unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
50161c30844dSMel Gorman 	bool boosted;
50171d82de61SMel Gorman 	struct zone *zone;
5018179e9639SAndrew Morton 	struct scan_control sc = {
5019179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
5020ee814fe2SJohannes Weiner 		.order = order,
5021a6dc60f8SJohannes Weiner 		.may_unmap = 1,
5022179e9639SAndrew Morton 	};
502393781325SOmar Sandoval 
50241732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
5025eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
50264f3eaf45SMatthew Wilcox (Oracle) 	__fs_reclaim_acquire(_THIS_IP_);
502793781325SOmar Sandoval 
5028f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
50291da177e4SLinus Torvalds 
50301c30844dSMel Gorman 	/*
50311c30844dSMel Gorman 	 * Account for the reclaim boost. Note that the zone boost is left in
50321c30844dSMel Gorman 	 * place so that parallel allocations that are near the watermark will
50331c30844dSMel Gorman 	 * stall or direct reclaim until kswapd is finished.
50341c30844dSMel Gorman 	 */
50351c30844dSMel Gorman 	nr_boost_reclaim = 0;
503697a225e6SJoonsoo Kim 	for (i = 0; i <= highest_zoneidx; i++) {
50371c30844dSMel Gorman 		zone = pgdat->node_zones + i;
50381c30844dSMel Gorman 		if (!managed_zone(zone))
50391c30844dSMel Gorman 			continue;
50401c30844dSMel Gorman 
50411c30844dSMel Gorman 		nr_boost_reclaim += zone->watermark_boost;
50421c30844dSMel Gorman 		zone_boosts[i] = zone->watermark_boost;
50431c30844dSMel Gorman 	}
50441c30844dSMel Gorman 	boosted = nr_boost_reclaim;
50451c30844dSMel Gorman 
50461c30844dSMel Gorman restart:
5047c49c2c47SMel Gorman 	set_reclaim_active(pgdat, highest_zoneidx);
50481c30844dSMel Gorman 	sc.priority = DEF_PRIORITY;
50499e3b2f8cSKonstantin Khlebnikov 	do {
5050c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
5051b8e83b94SMel Gorman 		bool raise_priority = true;
50521c30844dSMel Gorman 		bool balanced;
505393781325SOmar Sandoval 		bool ret;
5054b8e83b94SMel Gorman 
505597a225e6SJoonsoo Kim 		sc.reclaim_idx = highest_zoneidx;
50561da177e4SLinus Torvalds 
505786c79f6bSMel Gorman 		/*
505884c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
505984c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
506084c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
506184c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
506284c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
506384c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
506484c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
506584c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
506686c79f6bSMel Gorman 		 */
506786c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
506886c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
506986c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
50706aa303deSMel Gorman 				if (!managed_zone(zone))
507186c79f6bSMel Gorman 					continue;
507286c79f6bSMel Gorman 
5073970a39a3SMel Gorman 				sc.reclaim_idx = i;
507486c79f6bSMel Gorman 				break;
507586c79f6bSMel Gorman 			}
507686c79f6bSMel Gorman 		}
507786c79f6bSMel Gorman 
507886c79f6bSMel Gorman 		/*
50791c30844dSMel Gorman 		 * If the pgdat is imbalanced then ignore boosting and preserve
50801c30844dSMel Gorman 		 * the watermarks for a later time and restart. Note that the
50811c30844dSMel Gorman 		 * zone watermarks will be still reset at the end of balancing
50821c30844dSMel Gorman 		 * on the grounds that the normal reclaim should be enough to
50831c30844dSMel Gorman 		 * re-evaluate if boosting is required when kswapd next wakes.
508486c79f6bSMel Gorman 		 */
508597a225e6SJoonsoo Kim 		balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
50861c30844dSMel Gorman 		if (!balanced && nr_boost_reclaim) {
50871c30844dSMel Gorman 			nr_boost_reclaim = 0;
50881c30844dSMel Gorman 			goto restart;
50891c30844dSMel Gorman 		}
50901c30844dSMel Gorman 
50911c30844dSMel Gorman 		/*
50921c30844dSMel Gorman 		 * If boosting is not active then only reclaim if there are no
50931c30844dSMel Gorman 		 * eligible zones. Note that sc.reclaim_idx is not used as
50941c30844dSMel Gorman 		 * buffer_heads_over_limit may have adjusted it.
50951c30844dSMel Gorman 		 */
50961c30844dSMel Gorman 		if (!nr_boost_reclaim && balanced)
50971da177e4SLinus Torvalds 			goto out;
5098e1dbeda6SAndrew Morton 
50991c30844dSMel Gorman 		/* Limit the priority of boosting to avoid reclaim writeback */
51001c30844dSMel Gorman 		if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
51011c30844dSMel Gorman 			raise_priority = false;
51021c30844dSMel Gorman 
51031c30844dSMel Gorman 		/*
51041c30844dSMel Gorman 		 * Do not writeback or swap pages for boosted reclaim. The
51051c30844dSMel Gorman 		 * intent is to relieve pressure not issue sub-optimal IO
51061c30844dSMel Gorman 		 * from reclaim context. If no pages are reclaimed, the
51071c30844dSMel Gorman 		 * reclaim will be aborted.
51081c30844dSMel Gorman 		 */
51091c30844dSMel Gorman 		sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
51101c30844dSMel Gorman 		sc.may_swap = !nr_boost_reclaim;
51111c30844dSMel Gorman 
51121da177e4SLinus Torvalds 		/*
5113*ac35a490SYu Zhao 		 * Do some background aging, to give pages a chance to be
5114*ac35a490SYu Zhao 		 * referenced before reclaiming. All pages are rotated
5115*ac35a490SYu Zhao 		 * regardless of classzone as this is about consistent aging.
51161d82de61SMel Gorman 		 */
5117*ac35a490SYu Zhao 		kswapd_age_node(pgdat, &sc);
51181d82de61SMel Gorman 
51191d82de61SMel Gorman 		/*
5120b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
5121b7ea3c41SMel Gorman 		 * even in laptop mode.
5122b7ea3c41SMel Gorman 		 */
5123047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
5124b7ea3c41SMel Gorman 			sc.may_writepage = 1;
5125b7ea3c41SMel Gorman 
51261d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
51271da177e4SLinus Torvalds 		sc.nr_scanned = 0;
51280608f43dSAndrew Morton 		nr_soft_scanned = 0;
5129ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
51301d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
51310608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
51320608f43dSAndrew Morton 
513332a4330dSRik van Riel 		/*
51341d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
51351d82de61SMel Gorman 		 * enough pages are already being scanned that that high
51361d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
513732a4330dSRik van Riel 		 */
5138970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
5139b8e83b94SMel Gorman 			raise_priority = false;
5140d7868daeSMel Gorman 
51415515061dSMel Gorman 		/*
51425515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
51435515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
51445515061dSMel Gorman 		 * able to safely make forward progress. Wake them
51455515061dSMel Gorman 		 */
51465515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
5147c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
5148cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
51495515061dSMel Gorman 
5150b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
51514f3eaf45SMatthew Wilcox (Oracle) 		__fs_reclaim_release(_THIS_IP_);
515293781325SOmar Sandoval 		ret = try_to_freeze();
51534f3eaf45SMatthew Wilcox (Oracle) 		__fs_reclaim_acquire(_THIS_IP_);
515493781325SOmar Sandoval 		if (ret || kthread_should_stop())
5155b8e83b94SMel Gorman 			break;
5156b8e83b94SMel Gorman 
5157b8e83b94SMel Gorman 		/*
5158b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
5159b8e83b94SMel Gorman 		 * progress in reclaiming pages
5160b8e83b94SMel Gorman 		 */
5161c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
51621c30844dSMel Gorman 		nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
51631c30844dSMel Gorman 
51641c30844dSMel Gorman 		/*
51651c30844dSMel Gorman 		 * If reclaim made no progress for a boost, stop reclaim as
51661c30844dSMel Gorman 		 * IO cannot be queued and it could be an infinite loop in
51671c30844dSMel Gorman 		 * extreme circumstances.
51681c30844dSMel Gorman 		 */
51691c30844dSMel Gorman 		if (nr_boost_reclaim && !nr_reclaimed)
51701c30844dSMel Gorman 			break;
51711c30844dSMel Gorman 
5172c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
5173b8e83b94SMel Gorman 			sc.priority--;
51741d82de61SMel Gorman 	} while (sc.priority >= 1);
51751da177e4SLinus Torvalds 
5176c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
5177c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
5178c73322d0SJohannes Weiner 
5179b8e83b94SMel Gorman out:
5180c49c2c47SMel Gorman 	clear_reclaim_active(pgdat, highest_zoneidx);
5181c49c2c47SMel Gorman 
51821c30844dSMel Gorman 	/* If reclaim was boosted, account for the reclaim done in this pass */
51831c30844dSMel Gorman 	if (boosted) {
51841c30844dSMel Gorman 		unsigned long flags;
51851c30844dSMel Gorman 
518697a225e6SJoonsoo Kim 		for (i = 0; i <= highest_zoneidx; i++) {
51871c30844dSMel Gorman 			if (!zone_boosts[i])
51881c30844dSMel Gorman 				continue;
51891c30844dSMel Gorman 
51901c30844dSMel Gorman 			/* Increments are under the zone lock */
51911c30844dSMel Gorman 			zone = pgdat->node_zones + i;
51921c30844dSMel Gorman 			spin_lock_irqsave(&zone->lock, flags);
51931c30844dSMel Gorman 			zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
51941c30844dSMel Gorman 			spin_unlock_irqrestore(&zone->lock, flags);
51951c30844dSMel Gorman 		}
51961c30844dSMel Gorman 
51971c30844dSMel Gorman 		/*
51981c30844dSMel Gorman 		 * As there is now likely space, wakeup kcompact to defragment
51991c30844dSMel Gorman 		 * pageblocks.
52001c30844dSMel Gorman 		 */
520197a225e6SJoonsoo Kim 		wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
52021c30844dSMel Gorman 	}
52031c30844dSMel Gorman 
52042a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
52054f3eaf45SMatthew Wilcox (Oracle) 	__fs_reclaim_release(_THIS_IP_);
5206eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
52071732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
5208e5ca8071SYafang Shao 
52090abdee2bSMel Gorman 	/*
52101d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
52111d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
52121d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
52131d82de61SMel Gorman 	 * remain at the higher level.
52140abdee2bSMel Gorman 	 */
52151d82de61SMel Gorman 	return sc.order;
52161da177e4SLinus Torvalds }
52171da177e4SLinus Torvalds 
5218e716f2ebSMel Gorman /*
521997a225e6SJoonsoo Kim  * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
522097a225e6SJoonsoo Kim  * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
522197a225e6SJoonsoo Kim  * not a valid index then either kswapd runs for first time or kswapd couldn't
522297a225e6SJoonsoo Kim  * sleep after previous reclaim attempt (node is still unbalanced). In that
522397a225e6SJoonsoo Kim  * case return the zone index of the previous kswapd reclaim cycle.
5224e716f2ebSMel Gorman  */
522597a225e6SJoonsoo Kim static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
522697a225e6SJoonsoo Kim 					   enum zone_type prev_highest_zoneidx)
5227e716f2ebSMel Gorman {
522897a225e6SJoonsoo Kim 	enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
52295644e1fbSQian Cai 
523097a225e6SJoonsoo Kim 	return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
5231e716f2ebSMel Gorman }
5232e716f2ebSMel Gorman 
523338087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
523497a225e6SJoonsoo Kim 				unsigned int highest_zoneidx)
5235f0bc0a60SKOSAKI Motohiro {
5236f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
5237f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
5238f0bc0a60SKOSAKI Motohiro 
5239f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
5240f0bc0a60SKOSAKI Motohiro 		return;
5241f0bc0a60SKOSAKI Motohiro 
5242f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
5243f0bc0a60SKOSAKI Motohiro 
5244333b0a45SShantanu Goel 	/*
5245333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
5246333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
5247333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
5248333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
5249333b0a45SShantanu Goel 	 * succeed.
5250333b0a45SShantanu Goel 	 */
525197a225e6SJoonsoo Kim 	if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
5252fd901c95SVlastimil Babka 		/*
5253fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
5254fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
5255fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
5256fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
5257fd901c95SVlastimil Babka 		 */
5258fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
5259fd901c95SVlastimil Babka 
5260fd901c95SVlastimil Babka 		/*
5261fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
5262fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
5263fd901c95SVlastimil Babka 		 */
526497a225e6SJoonsoo Kim 		wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
5265fd901c95SVlastimil Babka 
5266f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
526738087d9bSMel Gorman 
526838087d9bSMel Gorman 		/*
526997a225e6SJoonsoo Kim 		 * If woken prematurely then reset kswapd_highest_zoneidx and
527038087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
527138087d9bSMel Gorman 		 * the previous request that slept prematurely.
527238087d9bSMel Gorman 		 */
527338087d9bSMel Gorman 		if (remaining) {
527497a225e6SJoonsoo Kim 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
527597a225e6SJoonsoo Kim 					kswapd_highest_zoneidx(pgdat,
527697a225e6SJoonsoo Kim 							highest_zoneidx));
52775644e1fbSQian Cai 
52785644e1fbSQian Cai 			if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
52795644e1fbSQian Cai 				WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
528038087d9bSMel Gorman 		}
528138087d9bSMel Gorman 
5282f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
5283f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
5284f0bc0a60SKOSAKI Motohiro 	}
5285f0bc0a60SKOSAKI Motohiro 
5286f0bc0a60SKOSAKI Motohiro 	/*
5287f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
5288f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
5289f0bc0a60SKOSAKI Motohiro 	 */
5290d9f21d42SMel Gorman 	if (!remaining &&
529197a225e6SJoonsoo Kim 	    prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
5292f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
5293f0bc0a60SKOSAKI Motohiro 
5294f0bc0a60SKOSAKI Motohiro 		/*
5295f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
5296f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
5297f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
5298f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
5299f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
5300f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
5301f0bc0a60SKOSAKI Motohiro 		 */
5302f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
53031c7e7f6cSAaditya Kumar 
53041c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
5305f0bc0a60SKOSAKI Motohiro 			schedule();
53061c7e7f6cSAaditya Kumar 
5307f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
5308f0bc0a60SKOSAKI Motohiro 	} else {
5309f0bc0a60SKOSAKI Motohiro 		if (remaining)
5310f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
5311f0bc0a60SKOSAKI Motohiro 		else
5312f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
5313f0bc0a60SKOSAKI Motohiro 	}
5314f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
5315f0bc0a60SKOSAKI Motohiro }
5316f0bc0a60SKOSAKI Motohiro 
53171da177e4SLinus Torvalds /*
53181da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
53191da177e4SLinus Torvalds  * from the init process.
53201da177e4SLinus Torvalds  *
53211da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
53221da177e4SLinus Torvalds  * free memory available even if there is no other activity
53231da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
53241da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
53251da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
53261da177e4SLinus Torvalds  *
53271da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
53281da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
53291da177e4SLinus Torvalds  */
53301da177e4SLinus Torvalds static int kswapd(void *p)
53311da177e4SLinus Torvalds {
5332e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
533397a225e6SJoonsoo Kim 	unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
53341da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t *)p;
53351da177e4SLinus Torvalds 	struct task_struct *tsk = current;
5336a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
53371da177e4SLinus Torvalds 
5338174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
5339c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
53401da177e4SLinus Torvalds 
53411da177e4SLinus Torvalds 	/*
53421da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
53431da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
53441da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
53451da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
53461da177e4SLinus Torvalds 	 *
53471da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
53481da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
53491da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
53501da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
53511da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
53521da177e4SLinus Torvalds 	 */
5353b698f0a1SHugh Dickins 	tsk->flags |= PF_MEMALLOC | PF_KSWAPD;
535483144186SRafael J. Wysocki 	set_freezable();
53551da177e4SLinus Torvalds 
53565644e1fbSQian Cai 	WRITE_ONCE(pgdat->kswapd_order, 0);
535797a225e6SJoonsoo Kim 	WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
53588cd7c588SMel Gorman 	atomic_set(&pgdat->nr_writeback_throttled, 0);
53591da177e4SLinus Torvalds 	for ( ; ; ) {
53606f6313d4SJeff Liu 		bool ret;
53613e1d1d28SChristoph Lameter 
53625644e1fbSQian Cai 		alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
536397a225e6SJoonsoo Kim 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
536497a225e6SJoonsoo Kim 							highest_zoneidx);
5365e716f2ebSMel Gorman 
536638087d9bSMel Gorman kswapd_try_sleep:
536738087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
536897a225e6SJoonsoo Kim 					highest_zoneidx);
5369215ddd66SMel Gorman 
537097a225e6SJoonsoo Kim 		/* Read the new order and highest_zoneidx */
53712b47a24cSLukas Bulwahn 		alloc_order = READ_ONCE(pgdat->kswapd_order);
537297a225e6SJoonsoo Kim 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
537397a225e6SJoonsoo Kim 							highest_zoneidx);
53745644e1fbSQian Cai 		WRITE_ONCE(pgdat->kswapd_order, 0);
537597a225e6SJoonsoo Kim 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
53761da177e4SLinus Torvalds 
53778fe23e05SDavid Rientjes 		ret = try_to_freeze();
53788fe23e05SDavid Rientjes 		if (kthread_should_stop())
53798fe23e05SDavid Rientjes 			break;
53808fe23e05SDavid Rientjes 
53818fe23e05SDavid Rientjes 		/*
53828fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
53838fe23e05SDavid Rientjes 		 * after returning from the refrigerator
5384b1296cc4SRafael J. Wysocki 		 */
538538087d9bSMel Gorman 		if (ret)
538638087d9bSMel Gorman 			continue;
53871d82de61SMel Gorman 
538838087d9bSMel Gorman 		/*
538938087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
539038087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
539138087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
539238087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
539338087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
539438087d9bSMel Gorman 		 * request (alloc_order).
539538087d9bSMel Gorman 		 */
539697a225e6SJoonsoo Kim 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
5397e5146b12SMel Gorman 						alloc_order);
539897a225e6SJoonsoo Kim 		reclaim_order = balance_pgdat(pgdat, alloc_order,
539997a225e6SJoonsoo Kim 						highest_zoneidx);
540038087d9bSMel Gorman 		if (reclaim_order < alloc_order)
540138087d9bSMel Gorman 			goto kswapd_try_sleep;
540233906bc5SMel Gorman 	}
5403b0a8cc58STakamori Yamaguchi 
5404b698f0a1SHugh Dickins 	tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD);
540571abdc15SJohannes Weiner 
54061da177e4SLinus Torvalds 	return 0;
54071da177e4SLinus Torvalds }
54081da177e4SLinus Torvalds 
54091da177e4SLinus Torvalds /*
54105ecd9d40SDavid Rientjes  * A zone is low on free memory or too fragmented for high-order memory.  If
54115ecd9d40SDavid Rientjes  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
54125ecd9d40SDavid Rientjes  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
54135ecd9d40SDavid Rientjes  * has failed or is not needed, still wake up kcompactd if only compaction is
54145ecd9d40SDavid Rientjes  * needed.
54151da177e4SLinus Torvalds  */
54165ecd9d40SDavid Rientjes void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
541797a225e6SJoonsoo Kim 		   enum zone_type highest_zoneidx)
54181da177e4SLinus Torvalds {
54191da177e4SLinus Torvalds 	pg_data_t *pgdat;
54205644e1fbSQian Cai 	enum zone_type curr_idx;
54211da177e4SLinus Torvalds 
54226aa303deSMel Gorman 	if (!managed_zone(zone))
54231da177e4SLinus Torvalds 		return;
54241da177e4SLinus Torvalds 
54255ecd9d40SDavid Rientjes 	if (!cpuset_zone_allowed(zone, gfp_flags))
54261da177e4SLinus Torvalds 		return;
5427dffcac2cSShakeel Butt 
54285644e1fbSQian Cai 	pgdat = zone->zone_pgdat;
542997a225e6SJoonsoo Kim 	curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
54305644e1fbSQian Cai 
543197a225e6SJoonsoo Kim 	if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
543297a225e6SJoonsoo Kim 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
54335644e1fbSQian Cai 
54345644e1fbSQian Cai 	if (READ_ONCE(pgdat->kswapd_order) < order)
54355644e1fbSQian Cai 		WRITE_ONCE(pgdat->kswapd_order, order);
54365644e1fbSQian Cai 
54378d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
54381da177e4SLinus Torvalds 		return;
5439e1a55637SMel Gorman 
54405ecd9d40SDavid Rientjes 	/* Hopeless node, leave it to direct reclaim if possible */
54415ecd9d40SDavid Rientjes 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
544297a225e6SJoonsoo Kim 	    (pgdat_balanced(pgdat, order, highest_zoneidx) &&
544397a225e6SJoonsoo Kim 	     !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
54445ecd9d40SDavid Rientjes 		/*
54455ecd9d40SDavid Rientjes 		 * There may be plenty of free memory available, but it's too
54465ecd9d40SDavid Rientjes 		 * fragmented for high-order allocations.  Wake up kcompactd
54475ecd9d40SDavid Rientjes 		 * and rely on compaction_suitable() to determine if it's
54485ecd9d40SDavid Rientjes 		 * needed.  If it fails, it will defer subsequent attempts to
54495ecd9d40SDavid Rientjes 		 * ratelimit its work.
54505ecd9d40SDavid Rientjes 		 */
54515ecd9d40SDavid Rientjes 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
545297a225e6SJoonsoo Kim 			wakeup_kcompactd(pgdat, order, highest_zoneidx);
5453c73322d0SJohannes Weiner 		return;
54545ecd9d40SDavid Rientjes 	}
5455c73322d0SJohannes Weiner 
545697a225e6SJoonsoo Kim 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
54575ecd9d40SDavid Rientjes 				      gfp_flags);
54588d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
54591da177e4SLinus Torvalds }
54601da177e4SLinus Torvalds 
5461c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
54621da177e4SLinus Torvalds /*
54637b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
5464d6277db4SRafael J. Wysocki  * freed pages.
5465d6277db4SRafael J. Wysocki  *
5466d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
5467d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
5468d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
54691da177e4SLinus Torvalds  */
54707b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
54711da177e4SLinus Torvalds {
5472d6277db4SRafael J. Wysocki 	struct scan_control sc = {
54737b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
5474ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
5475b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
54769e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
5477ee814fe2SJohannes Weiner 		.may_writepage = 1,
5478ee814fe2SJohannes Weiner 		.may_unmap = 1,
5479ee814fe2SJohannes Weiner 		.may_swap = 1,
5480ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
54811da177e4SLinus Torvalds 	};
54827b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
54837b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
5484499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
54851da177e4SLinus Torvalds 
5486d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
548793781325SOmar Sandoval 	noreclaim_flag = memalloc_noreclaim_save();
54881732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
5489d6277db4SRafael J. Wysocki 
54903115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
5491d6277db4SRafael J. Wysocki 
54921732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
5493499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
549493781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
5495d6277db4SRafael J. Wysocki 
54967b51755cSKOSAKI Motohiro 	return nr_reclaimed;
54971da177e4SLinus Torvalds }
5498c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
54991da177e4SLinus Torvalds 
55003218ae14SYasunori Goto /*
55013218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
55023218ae14SYasunori Goto  */
5503b87c517aSMiaohe Lin void kswapd_run(int nid)
55043218ae14SYasunori Goto {
55053218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
55063218ae14SYasunori Goto 
5507b4a0215eSKefeng Wang 	pgdat_kswapd_lock(pgdat);
5508b4a0215eSKefeng Wang 	if (!pgdat->kswapd) {
55093218ae14SYasunori Goto 		pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
55103218ae14SYasunori Goto 		if (IS_ERR(pgdat->kswapd)) {
55113218ae14SYasunori Goto 			/* failure at boot is fatal */
5512c6202adfSThomas Gleixner 			BUG_ON(system_state < SYSTEM_RUNNING);
5513d5dc0ad9SGavin Shan 			pr_err("Failed to start kswapd on node %d\n", nid);
5514d72515b8SXishi Qiu 			pgdat->kswapd = NULL;
55153218ae14SYasunori Goto 		}
55163218ae14SYasunori Goto 	}
5517b4a0215eSKefeng Wang 	pgdat_kswapd_unlock(pgdat);
5518b4a0215eSKefeng Wang }
55193218ae14SYasunori Goto 
55208fe23e05SDavid Rientjes /*
5521d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
5522e8da368aSYun-Ze Li  * be holding mem_hotplug_begin/done().
55238fe23e05SDavid Rientjes  */
55248fe23e05SDavid Rientjes void kswapd_stop(int nid)
55258fe23e05SDavid Rientjes {
5526b4a0215eSKefeng Wang 	pg_data_t *pgdat = NODE_DATA(nid);
5527b4a0215eSKefeng Wang 	struct task_struct *kswapd;
55288fe23e05SDavid Rientjes 
5529b4a0215eSKefeng Wang 	pgdat_kswapd_lock(pgdat);
5530b4a0215eSKefeng Wang 	kswapd = pgdat->kswapd;
5531d8adde17SJiang Liu 	if (kswapd) {
55328fe23e05SDavid Rientjes 		kthread_stop(kswapd);
5533b4a0215eSKefeng Wang 		pgdat->kswapd = NULL;
5534d8adde17SJiang Liu 	}
5535b4a0215eSKefeng Wang 	pgdat_kswapd_unlock(pgdat);
55368fe23e05SDavid Rientjes }
55378fe23e05SDavid Rientjes 
55381da177e4SLinus Torvalds static int __init kswapd_init(void)
55391da177e4SLinus Torvalds {
55406b700b5bSWei Yang 	int nid;
554169e05944SAndrew Morton 
55421da177e4SLinus Torvalds 	swap_setup();
554348fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
55443218ae14SYasunori Goto  		kswapd_run(nid);
55451da177e4SLinus Torvalds 	return 0;
55461da177e4SLinus Torvalds }
55471da177e4SLinus Torvalds 
55481da177e4SLinus Torvalds module_init(kswapd_init)
55499eeff239SChristoph Lameter 
55509eeff239SChristoph Lameter #ifdef CONFIG_NUMA
55519eeff239SChristoph Lameter /*
5552a5f5f91dSMel Gorman  * Node reclaim mode
55539eeff239SChristoph Lameter  *
5554a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
55559eeff239SChristoph Lameter  * the watermarks.
55569eeff239SChristoph Lameter  */
5557a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
55589eeff239SChristoph Lameter 
555951998364SDave Hansen /*
5560a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
5561a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
5562a92f7126SChristoph Lameter  * a zone.
5563a92f7126SChristoph Lameter  */
5564a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
5565a92f7126SChristoph Lameter 
55669eeff239SChristoph Lameter /*
5567a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
55689614634fSChristoph Lameter  * occur.
55699614634fSChristoph Lameter  */
55709614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
55719614634fSChristoph Lameter 
55729614634fSChristoph Lameter /*
55730ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
55740ff38490SChristoph Lameter  * slab reclaim needs to occur.
55750ff38490SChristoph Lameter  */
55760ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
55770ff38490SChristoph Lameter 
557811fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
557990afa5deSMel Gorman {
558011fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
558111fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
558211fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
558390afa5deSMel Gorman 
558490afa5deSMel Gorman 	/*
558590afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
558690afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
558790afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
558890afa5deSMel Gorman 	 */
558990afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
559090afa5deSMel Gorman }
559190afa5deSMel Gorman 
559290afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
5593a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
559490afa5deSMel Gorman {
5595d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
5596d031a157SAlexandru Moise 	unsigned long delta = 0;
559790afa5deSMel Gorman 
559890afa5deSMel Gorman 	/*
559995bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
560090afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
560111fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
560290afa5deSMel Gorman 	 * a better estimate
560390afa5deSMel Gorman 	 */
5604a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
5605a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
560690afa5deSMel Gorman 	else
5607a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
560890afa5deSMel Gorman 
560990afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
5610a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
5611a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
561290afa5deSMel Gorman 
561390afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
561490afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
561590afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
561690afa5deSMel Gorman 
561790afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
561890afa5deSMel Gorman }
561990afa5deSMel Gorman 
56200ff38490SChristoph Lameter /*
5621a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
56229eeff239SChristoph Lameter  */
5623a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
56249eeff239SChristoph Lameter {
56257fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
562669e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
56279eeff239SChristoph Lameter 	struct task_struct *p = current;
5628499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
5629179e9639SAndrew Morton 	struct scan_control sc = {
563062b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
5631f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
5632bd2f6199SJohannes Weiner 		.order = order,
5633a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
5634a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
5635a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
5636ee814fe2SJohannes Weiner 		.may_swap = 1,
5637f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
5638179e9639SAndrew Morton 	};
563957f29762SJohannes Weiner 	unsigned long pflags;
56409eeff239SChristoph Lameter 
5641132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
5642132bb8cfSYafang Shao 					   sc.gfp_mask);
5643132bb8cfSYafang Shao 
56449eeff239SChristoph Lameter 	cond_resched();
564557f29762SJohannes Weiner 	psi_memstall_enter(&pflags);
564693781325SOmar Sandoval 	fs_reclaim_acquire(sc.gfp_mask);
5647d4f7796eSChristoph Lameter 	/*
564895bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
5649d4f7796eSChristoph Lameter 	 */
5650499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
56511732d2b0SAndrew Morton 	set_task_reclaim_state(p, &sc.reclaim_state);
5652c84db23cSChristoph Lameter 
5653d8ff6fdeSMiaohe Lin 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages ||
5654d8ff6fdeSMiaohe Lin 	    node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) {
5655a92f7126SChristoph Lameter 		/*
5656894befecSAndrey Ryabinin 		 * Free memory by calling shrink node with increasing
56570ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
5658a92f7126SChristoph Lameter 		 */
5659a92f7126SChristoph Lameter 		do {
5660970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
56619e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
56620ff38490SChristoph Lameter 	}
5663a92f7126SChristoph Lameter 
56641732d2b0SAndrew Morton 	set_task_reclaim_state(p, NULL);
5665499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
566693781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
566757f29762SJohannes Weiner 	psi_memstall_leave(&pflags);
5668132bb8cfSYafang Shao 
5669132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
5670132bb8cfSYafang Shao 
5671a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
56729eeff239SChristoph Lameter }
5673179e9639SAndrew Morton 
5674a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
5675179e9639SAndrew Morton {
5676d773ed6bSDavid Rientjes 	int ret;
5677179e9639SAndrew Morton 
5678179e9639SAndrew Morton 	/*
5679a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
56800ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
568134aa1330SChristoph Lameter 	 *
56829614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
56839614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
5684a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
5685a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
56869614634fSChristoph Lameter 	 * unmapped file backed pages.
5687179e9639SAndrew Morton 	 */
5688a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
5689d42f3245SRoman Gushchin 	    node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
5690d42f3245SRoman Gushchin 	    pgdat->min_slab_pages)
5691a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
5692179e9639SAndrew Morton 
5693179e9639SAndrew Morton 	/*
5694d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
5695179e9639SAndrew Morton 	 */
5696d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
5697a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
5698179e9639SAndrew Morton 
5699179e9639SAndrew Morton 	/*
5700a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
5701179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
5702179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
5703179e9639SAndrew Morton 	 * as wide as possible.
5704179e9639SAndrew Morton 	 */
5705a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
5706a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
5707d773ed6bSDavid Rientjes 
5708a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
5709a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
5710fa5e084eSMel Gorman 
5711a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
5712a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
5713d773ed6bSDavid Rientjes 
571424cf7251SMel Gorman 	if (!ret)
571524cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
571624cf7251SMel Gorman 
5717d773ed6bSDavid Rientjes 	return ret;
5718179e9639SAndrew Morton }
57199eeff239SChristoph Lameter #endif
5720894bc310SLee Schermerhorn 
572164e3d12fSKuo-Hsin Yang void check_move_unevictable_pages(struct pagevec *pvec)
572289e004eaSLee Schermerhorn {
572377414d19SMatthew Wilcox (Oracle) 	struct folio_batch fbatch;
572477414d19SMatthew Wilcox (Oracle) 	unsigned i;
572577414d19SMatthew Wilcox (Oracle) 
572677414d19SMatthew Wilcox (Oracle) 	folio_batch_init(&fbatch);
572777414d19SMatthew Wilcox (Oracle) 	for (i = 0; i < pvec->nr; i++) {
572877414d19SMatthew Wilcox (Oracle) 		struct page *page = pvec->pages[i];
572977414d19SMatthew Wilcox (Oracle) 
573077414d19SMatthew Wilcox (Oracle) 		if (PageTransTail(page))
573177414d19SMatthew Wilcox (Oracle) 			continue;
573277414d19SMatthew Wilcox (Oracle) 		folio_batch_add(&fbatch, page_folio(page));
573377414d19SMatthew Wilcox (Oracle) 	}
573477414d19SMatthew Wilcox (Oracle) 	check_move_unevictable_folios(&fbatch);
573577414d19SMatthew Wilcox (Oracle) }
573677414d19SMatthew Wilcox (Oracle) EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
573777414d19SMatthew Wilcox (Oracle) 
573877414d19SMatthew Wilcox (Oracle) /**
573977414d19SMatthew Wilcox (Oracle)  * check_move_unevictable_folios - Move evictable folios to appropriate zone
574077414d19SMatthew Wilcox (Oracle)  * lru list
574177414d19SMatthew Wilcox (Oracle)  * @fbatch: Batch of lru folios to check.
574277414d19SMatthew Wilcox (Oracle)  *
574377414d19SMatthew Wilcox (Oracle)  * Checks folios for evictability, if an evictable folio is in the unevictable
574477414d19SMatthew Wilcox (Oracle)  * lru list, moves it to the appropriate evictable lru list. This function
574577414d19SMatthew Wilcox (Oracle)  * should be only used for lru folios.
574677414d19SMatthew Wilcox (Oracle)  */
574777414d19SMatthew Wilcox (Oracle) void check_move_unevictable_folios(struct folio_batch *fbatch)
574877414d19SMatthew Wilcox (Oracle) {
57496168d0daSAlex Shi 	struct lruvec *lruvec = NULL;
575024513264SHugh Dickins 	int pgscanned = 0;
575124513264SHugh Dickins 	int pgrescued = 0;
575289e004eaSLee Schermerhorn 	int i;
575389e004eaSLee Schermerhorn 
575477414d19SMatthew Wilcox (Oracle) 	for (i = 0; i < fbatch->nr; i++) {
575577414d19SMatthew Wilcox (Oracle) 		struct folio *folio = fbatch->folios[i];
575677414d19SMatthew Wilcox (Oracle) 		int nr_pages = folio_nr_pages(folio);
575789e004eaSLee Schermerhorn 
57588d8869caSHugh Dickins 		pgscanned += nr_pages;
57598d8869caSHugh Dickins 
576077414d19SMatthew Wilcox (Oracle) 		/* block memcg migration while the folio moves between lrus */
576177414d19SMatthew Wilcox (Oracle) 		if (!folio_test_clear_lru(folio))
5762d25b5bd8SAlex Shi 			continue;
5763d25b5bd8SAlex Shi 
57640de340cbSMatthew Wilcox (Oracle) 		lruvec = folio_lruvec_relock_irq(folio, lruvec);
576577414d19SMatthew Wilcox (Oracle) 		if (folio_evictable(folio) && folio_test_unevictable(folio)) {
576677414d19SMatthew Wilcox (Oracle) 			lruvec_del_folio(lruvec, folio);
576777414d19SMatthew Wilcox (Oracle) 			folio_clear_unevictable(folio);
576877414d19SMatthew Wilcox (Oracle) 			lruvec_add_folio(lruvec, folio);
57698d8869caSHugh Dickins 			pgrescued += nr_pages;
577089e004eaSLee Schermerhorn 		}
577177414d19SMatthew Wilcox (Oracle) 		folio_set_lru(folio);
577289e004eaSLee Schermerhorn 	}
577324513264SHugh Dickins 
57746168d0daSAlex Shi 	if (lruvec) {
577524513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
577624513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
57776168d0daSAlex Shi 		unlock_page_lruvec_irq(lruvec);
5778d25b5bd8SAlex Shi 	} else if (pgscanned) {
5779d25b5bd8SAlex Shi 		count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
578024513264SHugh Dickins 	}
578185046579SHugh Dickins }
578277414d19SMatthew Wilcox (Oracle) EXPORT_SYMBOL_GPL(check_move_unevictable_folios);
5783