xref: /openbmc/linux/mm/vmscan.c (revision 2d2b8d2b67713da5de333a8849342503a9f21c60)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  *  Swap reorganised 29.12.95, Stephen Tweedie.
61da177e4SLinus Torvalds  *  kswapd added: 7.1.96  sct
71da177e4SLinus Torvalds  *  Removed kswapd_ctl limits, and swap out as many pages as needed
81da177e4SLinus Torvalds  *  to bring the system back to freepages.high: 2.4.97, Rik van Riel.
91da177e4SLinus Torvalds  *  Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
101da177e4SLinus Torvalds  *  Multiqueue VM started 5.8.00, Rik van Riel.
111da177e4SLinus Torvalds  */
121da177e4SLinus Torvalds 
13b1de0d13SMitchel Humpherys #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14b1de0d13SMitchel Humpherys 
151da177e4SLinus Torvalds #include <linux/mm.h>
165b3cc15aSIngo Molnar #include <linux/sched/mm.h>
171da177e4SLinus Torvalds #include <linux/module.h>
185a0e3ad6STejun Heo #include <linux/gfp.h>
191da177e4SLinus Torvalds #include <linux/kernel_stat.h>
201da177e4SLinus Torvalds #include <linux/swap.h>
211da177e4SLinus Torvalds #include <linux/pagemap.h>
221da177e4SLinus Torvalds #include <linux/init.h>
231da177e4SLinus Torvalds #include <linux/highmem.h>
2470ddf637SAnton Vorontsov #include <linux/vmpressure.h>
25e129b5c2SAndrew Morton #include <linux/vmstat.h>
261da177e4SLinus Torvalds #include <linux/file.h>
271da177e4SLinus Torvalds #include <linux/writeback.h>
281da177e4SLinus Torvalds #include <linux/blkdev.h>
291da177e4SLinus Torvalds #include <linux/buffer_head.h>	/* for try_to_release_page(),
301da177e4SLinus Torvalds 					buffer_heads_over_limit */
311da177e4SLinus Torvalds #include <linux/mm_inline.h>
321da177e4SLinus Torvalds #include <linux/backing-dev.h>
331da177e4SLinus Torvalds #include <linux/rmap.h>
341da177e4SLinus Torvalds #include <linux/topology.h>
351da177e4SLinus Torvalds #include <linux/cpu.h>
361da177e4SLinus Torvalds #include <linux/cpuset.h>
373e7d3449SMel Gorman #include <linux/compaction.h>
381da177e4SLinus Torvalds #include <linux/notifier.h>
391da177e4SLinus Torvalds #include <linux/rwsem.h>
40248a0301SRafael J. Wysocki #include <linux/delay.h>
413218ae14SYasunori Goto #include <linux/kthread.h>
427dfb7103SNigel Cunningham #include <linux/freezer.h>
4366e1707bSBalbir Singh #include <linux/memcontrol.h>
44873b4771SKeika Kobayashi #include <linux/delayacct.h>
45af936a16SLee Schermerhorn #include <linux/sysctl.h>
46929bea7cSKOSAKI Motohiro #include <linux/oom.h>
4764e3d12fSKuo-Hsin Yang #include <linux/pagevec.h>
48268bb0ceSLinus Torvalds #include <linux/prefetch.h>
49b1de0d13SMitchel Humpherys #include <linux/printk.h>
50f9fe48beSRoss Zwisler #include <linux/dax.h>
51eb414681SJohannes Weiner #include <linux/psi.h>
521da177e4SLinus Torvalds 
531da177e4SLinus Torvalds #include <asm/tlbflush.h>
541da177e4SLinus Torvalds #include <asm/div64.h>
551da177e4SLinus Torvalds 
561da177e4SLinus Torvalds #include <linux/swapops.h>
57117aad1eSRafael Aquini #include <linux/balloon_compaction.h>
581da177e4SLinus Torvalds 
590f8053a5SNick Piggin #include "internal.h"
600f8053a5SNick Piggin 
6133906bc5SMel Gorman #define CREATE_TRACE_POINTS
6233906bc5SMel Gorman #include <trace/events/vmscan.h>
6333906bc5SMel Gorman 
641da177e4SLinus Torvalds struct scan_control {
6522fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6622fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
6722fba335SKOSAKI Motohiro 
68ee814fe2SJohannes Weiner 	/*
69ee814fe2SJohannes Weiner 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
70ee814fe2SJohannes Weiner 	 * are scanned.
71ee814fe2SJohannes Weiner 	 */
72ee814fe2SJohannes Weiner 	nodemask_t	*nodemask;
739e3b2f8cSKonstantin Khlebnikov 
745f53e762SKOSAKI Motohiro 	/*
75f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
76f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
77f16015fbSJohannes Weiner 	 */
78f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
7966e1707bSBalbir Singh 
807cf111bcSJohannes Weiner 	/*
817cf111bcSJohannes Weiner 	 * Scan pressure balancing between anon and file LRUs
827cf111bcSJohannes Weiner 	 */
837cf111bcSJohannes Weiner 	unsigned long	anon_cost;
847cf111bcSJohannes Weiner 	unsigned long	file_cost;
857cf111bcSJohannes Weiner 
86b91ac374SJohannes Weiner 	/* Can active pages be deactivated as part of reclaim? */
87b91ac374SJohannes Weiner #define DEACTIVATE_ANON 1
88b91ac374SJohannes Weiner #define DEACTIVATE_FILE 2
89b91ac374SJohannes Weiner 	unsigned int may_deactivate:2;
90b91ac374SJohannes Weiner 	unsigned int force_deactivate:1;
91b91ac374SJohannes Weiner 	unsigned int skipped_deactivate:1;
92b91ac374SJohannes Weiner 
931276ad68SJohannes Weiner 	/* Writepage batching in laptop mode; RECLAIM_WRITE */
94ee814fe2SJohannes Weiner 	unsigned int may_writepage:1;
95ee814fe2SJohannes Weiner 
96ee814fe2SJohannes Weiner 	/* Can mapped pages be reclaimed? */
97ee814fe2SJohannes Weiner 	unsigned int may_unmap:1;
98ee814fe2SJohannes Weiner 
99ee814fe2SJohannes Weiner 	/* Can pages be swapped as part of reclaim? */
100ee814fe2SJohannes Weiner 	unsigned int may_swap:1;
101ee814fe2SJohannes Weiner 
102d6622f63SYisheng Xie 	/*
103d6622f63SYisheng Xie 	 * Cgroups are not reclaimed below their configured memory.low,
104d6622f63SYisheng Xie 	 * unless we threaten to OOM. If any cgroups are skipped due to
105d6622f63SYisheng Xie 	 * memory.low and nothing was reclaimed, go back for memory.low.
106d6622f63SYisheng Xie 	 */
107d6622f63SYisheng Xie 	unsigned int memcg_low_reclaim:1;
108d6622f63SYisheng Xie 	unsigned int memcg_low_skipped:1;
109241994edSJohannes Weiner 
110ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
111ee814fe2SJohannes Weiner 
112ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
113ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
114ee814fe2SJohannes Weiner 
115b91ac374SJohannes Weiner 	/* There is easily reclaimable cold cache in the current node */
116b91ac374SJohannes Weiner 	unsigned int cache_trim_mode:1;
117b91ac374SJohannes Weiner 
11853138ceaSJohannes Weiner 	/* The file pages on the current node are dangerously low */
11953138ceaSJohannes Weiner 	unsigned int file_is_tiny:1;
12053138ceaSJohannes Weiner 
121bb451fdfSGreg Thelen 	/* Allocation order */
122bb451fdfSGreg Thelen 	s8 order;
123bb451fdfSGreg Thelen 
124bb451fdfSGreg Thelen 	/* Scan (total_size >> priority) pages at once */
125bb451fdfSGreg Thelen 	s8 priority;
126bb451fdfSGreg Thelen 
127bb451fdfSGreg Thelen 	/* The highest zone to isolate pages for reclaim from */
128bb451fdfSGreg Thelen 	s8 reclaim_idx;
129bb451fdfSGreg Thelen 
130bb451fdfSGreg Thelen 	/* This context's GFP mask */
131bb451fdfSGreg Thelen 	gfp_t gfp_mask;
132bb451fdfSGreg Thelen 
133ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
134ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
135ee814fe2SJohannes Weiner 
136ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
137ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
138d108c772SAndrey Ryabinin 
139d108c772SAndrey Ryabinin 	struct {
140d108c772SAndrey Ryabinin 		unsigned int dirty;
141d108c772SAndrey Ryabinin 		unsigned int unqueued_dirty;
142d108c772SAndrey Ryabinin 		unsigned int congested;
143d108c772SAndrey Ryabinin 		unsigned int writeback;
144d108c772SAndrey Ryabinin 		unsigned int immediate;
145d108c772SAndrey Ryabinin 		unsigned int file_taken;
146d108c772SAndrey Ryabinin 		unsigned int taken;
147d108c772SAndrey Ryabinin 	} nr;
148e5ca8071SYafang Shao 
149e5ca8071SYafang Shao 	/* for recording the reclaimed slab by now */
150e5ca8071SYafang Shao 	struct reclaim_state reclaim_state;
1511da177e4SLinus Torvalds };
1521da177e4SLinus Torvalds 
1531da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1541da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1551da177e4SLinus Torvalds 	do {								\
1561da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1571da177e4SLinus Torvalds 			struct page *prev;				\
1581da177e4SLinus Torvalds 									\
1591da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1601da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1611da177e4SLinus Torvalds 		}							\
1621da177e4SLinus Torvalds 	} while (0)
1631da177e4SLinus Torvalds #else
1641da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1651da177e4SLinus Torvalds #endif
1661da177e4SLinus Torvalds 
1671da177e4SLinus Torvalds /*
168c843966cSJohannes Weiner  * From 0 .. 200.  Higher means more swappy.
1691da177e4SLinus Torvalds  */
1701da177e4SLinus Torvalds int vm_swappiness = 60;
1711da177e4SLinus Torvalds 
1720a432dcbSYang Shi static void set_task_reclaim_state(struct task_struct *task,
1730a432dcbSYang Shi 				   struct reclaim_state *rs)
1740a432dcbSYang Shi {
1750a432dcbSYang Shi 	/* Check for an overwrite */
1760a432dcbSYang Shi 	WARN_ON_ONCE(rs && task->reclaim_state);
1770a432dcbSYang Shi 
1780a432dcbSYang Shi 	/* Check for the nulling of an already-nulled member */
1790a432dcbSYang Shi 	WARN_ON_ONCE(!rs && !task->reclaim_state);
1800a432dcbSYang Shi 
1810a432dcbSYang Shi 	task->reclaim_state = rs;
1820a432dcbSYang Shi }
1830a432dcbSYang Shi 
1841da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1851da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1861da177e4SLinus Torvalds 
1870a432dcbSYang Shi #ifdef CONFIG_MEMCG
188a2fb1261SYang Shi static int shrinker_nr_max;
1892bfd3637SYang Shi 
1903c6f17e6SYang Shi /* The shrinker_info is expanded in a batch of BITS_PER_LONG */
191a2fb1261SYang Shi static inline int shrinker_map_size(int nr_items)
192a2fb1261SYang Shi {
193a2fb1261SYang Shi 	return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
194a2fb1261SYang Shi }
1952bfd3637SYang Shi 
1963c6f17e6SYang Shi static inline int shrinker_defer_size(int nr_items)
1973c6f17e6SYang Shi {
1983c6f17e6SYang Shi 	return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
1993c6f17e6SYang Shi }
2003c6f17e6SYang Shi 
201468ab843SYang Shi static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
202468ab843SYang Shi 						     int nid)
203468ab843SYang Shi {
204468ab843SYang Shi 	return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
205468ab843SYang Shi 					 lockdep_is_held(&shrinker_rwsem));
206468ab843SYang Shi }
207468ab843SYang Shi 
208e4262c4fSYang Shi static int expand_one_shrinker_info(struct mem_cgroup *memcg,
2093c6f17e6SYang Shi 				    int map_size, int defer_size,
2103c6f17e6SYang Shi 				    int old_map_size, int old_defer_size)
2112bfd3637SYang Shi {
212e4262c4fSYang Shi 	struct shrinker_info *new, *old;
2132bfd3637SYang Shi 	struct mem_cgroup_per_node *pn;
2142bfd3637SYang Shi 	int nid;
2153c6f17e6SYang Shi 	int size = map_size + defer_size;
2162bfd3637SYang Shi 
2172bfd3637SYang Shi 	for_each_node(nid) {
2182bfd3637SYang Shi 		pn = memcg->nodeinfo[nid];
219468ab843SYang Shi 		old = shrinker_info_protected(memcg, nid);
2202bfd3637SYang Shi 		/* Not yet online memcg */
2212bfd3637SYang Shi 		if (!old)
2222bfd3637SYang Shi 			return 0;
2232bfd3637SYang Shi 
2242bfd3637SYang Shi 		new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
2252bfd3637SYang Shi 		if (!new)
2262bfd3637SYang Shi 			return -ENOMEM;
2272bfd3637SYang Shi 
2283c6f17e6SYang Shi 		new->nr_deferred = (atomic_long_t *)(new + 1);
2293c6f17e6SYang Shi 		new->map = (void *)new->nr_deferred + defer_size;
2303c6f17e6SYang Shi 
2313c6f17e6SYang Shi 		/* map: set all old bits, clear all new bits */
2323c6f17e6SYang Shi 		memset(new->map, (int)0xff, old_map_size);
2333c6f17e6SYang Shi 		memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
2343c6f17e6SYang Shi 		/* nr_deferred: copy old values, clear all new values */
2353c6f17e6SYang Shi 		memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
2363c6f17e6SYang Shi 		memset((void *)new->nr_deferred + old_defer_size, 0,
2373c6f17e6SYang Shi 		       defer_size - old_defer_size);
2382bfd3637SYang Shi 
239e4262c4fSYang Shi 		rcu_assign_pointer(pn->shrinker_info, new);
24072673e86SYang Shi 		kvfree_rcu(old, rcu);
2412bfd3637SYang Shi 	}
2422bfd3637SYang Shi 
2432bfd3637SYang Shi 	return 0;
2442bfd3637SYang Shi }
2452bfd3637SYang Shi 
246e4262c4fSYang Shi void free_shrinker_info(struct mem_cgroup *memcg)
2472bfd3637SYang Shi {
2482bfd3637SYang Shi 	struct mem_cgroup_per_node *pn;
249e4262c4fSYang Shi 	struct shrinker_info *info;
2502bfd3637SYang Shi 	int nid;
2512bfd3637SYang Shi 
2522bfd3637SYang Shi 	for_each_node(nid) {
2532bfd3637SYang Shi 		pn = memcg->nodeinfo[nid];
254e4262c4fSYang Shi 		info = rcu_dereference_protected(pn->shrinker_info, true);
255e4262c4fSYang Shi 		kvfree(info);
256e4262c4fSYang Shi 		rcu_assign_pointer(pn->shrinker_info, NULL);
2572bfd3637SYang Shi 	}
2582bfd3637SYang Shi }
2592bfd3637SYang Shi 
260e4262c4fSYang Shi int alloc_shrinker_info(struct mem_cgroup *memcg)
2612bfd3637SYang Shi {
262e4262c4fSYang Shi 	struct shrinker_info *info;
2632bfd3637SYang Shi 	int nid, size, ret = 0;
2643c6f17e6SYang Shi 	int map_size, defer_size = 0;
2652bfd3637SYang Shi 
266d27cf2aaSYang Shi 	down_write(&shrinker_rwsem);
2673c6f17e6SYang Shi 	map_size = shrinker_map_size(shrinker_nr_max);
2683c6f17e6SYang Shi 	defer_size = shrinker_defer_size(shrinker_nr_max);
2693c6f17e6SYang Shi 	size = map_size + defer_size;
2702bfd3637SYang Shi 	for_each_node(nid) {
271e4262c4fSYang Shi 		info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
272e4262c4fSYang Shi 		if (!info) {
273e4262c4fSYang Shi 			free_shrinker_info(memcg);
2742bfd3637SYang Shi 			ret = -ENOMEM;
2752bfd3637SYang Shi 			break;
2762bfd3637SYang Shi 		}
2773c6f17e6SYang Shi 		info->nr_deferred = (atomic_long_t *)(info + 1);
2783c6f17e6SYang Shi 		info->map = (void *)info->nr_deferred + defer_size;
279e4262c4fSYang Shi 		rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
2802bfd3637SYang Shi 	}
281d27cf2aaSYang Shi 	up_write(&shrinker_rwsem);
2822bfd3637SYang Shi 
2832bfd3637SYang Shi 	return ret;
2842bfd3637SYang Shi }
2852bfd3637SYang Shi 
2863c6f17e6SYang Shi static inline bool need_expand(int nr_max)
2873c6f17e6SYang Shi {
2883c6f17e6SYang Shi 	return round_up(nr_max, BITS_PER_LONG) >
2893c6f17e6SYang Shi 	       round_up(shrinker_nr_max, BITS_PER_LONG);
2903c6f17e6SYang Shi }
2913c6f17e6SYang Shi 
292e4262c4fSYang Shi static int expand_shrinker_info(int new_id)
2932bfd3637SYang Shi {
2943c6f17e6SYang Shi 	int ret = 0;
295a2fb1261SYang Shi 	int new_nr_max = new_id + 1;
2963c6f17e6SYang Shi 	int map_size, defer_size = 0;
2973c6f17e6SYang Shi 	int old_map_size, old_defer_size = 0;
2982bfd3637SYang Shi 	struct mem_cgroup *memcg;
2992bfd3637SYang Shi 
3003c6f17e6SYang Shi 	if (!need_expand(new_nr_max))
301a2fb1261SYang Shi 		goto out;
3022bfd3637SYang Shi 
3032bfd3637SYang Shi 	if (!root_mem_cgroup)
304d27cf2aaSYang Shi 		goto out;
305d27cf2aaSYang Shi 
306d27cf2aaSYang Shi 	lockdep_assert_held(&shrinker_rwsem);
3072bfd3637SYang Shi 
3083c6f17e6SYang Shi 	map_size = shrinker_map_size(new_nr_max);
3093c6f17e6SYang Shi 	defer_size = shrinker_defer_size(new_nr_max);
3103c6f17e6SYang Shi 	old_map_size = shrinker_map_size(shrinker_nr_max);
3113c6f17e6SYang Shi 	old_defer_size = shrinker_defer_size(shrinker_nr_max);
3123c6f17e6SYang Shi 
3132bfd3637SYang Shi 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3142bfd3637SYang Shi 	do {
3153c6f17e6SYang Shi 		ret = expand_one_shrinker_info(memcg, map_size, defer_size,
3163c6f17e6SYang Shi 					       old_map_size, old_defer_size);
3172bfd3637SYang Shi 		if (ret) {
3182bfd3637SYang Shi 			mem_cgroup_iter_break(NULL, memcg);
319d27cf2aaSYang Shi 			goto out;
3202bfd3637SYang Shi 		}
3212bfd3637SYang Shi 	} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
322d27cf2aaSYang Shi out:
3232bfd3637SYang Shi 	if (!ret)
324a2fb1261SYang Shi 		shrinker_nr_max = new_nr_max;
325d27cf2aaSYang Shi 
3262bfd3637SYang Shi 	return ret;
3272bfd3637SYang Shi }
3282bfd3637SYang Shi 
3292bfd3637SYang Shi void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
3302bfd3637SYang Shi {
3312bfd3637SYang Shi 	if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
332e4262c4fSYang Shi 		struct shrinker_info *info;
3332bfd3637SYang Shi 
3342bfd3637SYang Shi 		rcu_read_lock();
335e4262c4fSYang Shi 		info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
3362bfd3637SYang Shi 		/* Pairs with smp mb in shrink_slab() */
3372bfd3637SYang Shi 		smp_mb__before_atomic();
338e4262c4fSYang Shi 		set_bit(shrinker_id, info->map);
3392bfd3637SYang Shi 		rcu_read_unlock();
3402bfd3637SYang Shi 	}
3412bfd3637SYang Shi }
3422bfd3637SYang Shi 
343b4c2b231SKirill Tkhai static DEFINE_IDR(shrinker_idr);
344b4c2b231SKirill Tkhai 
345b4c2b231SKirill Tkhai static int prealloc_memcg_shrinker(struct shrinker *shrinker)
346b4c2b231SKirill Tkhai {
347b4c2b231SKirill Tkhai 	int id, ret = -ENOMEM;
348b4c2b231SKirill Tkhai 
349476b30a0SYang Shi 	if (mem_cgroup_disabled())
350476b30a0SYang Shi 		return -ENOSYS;
351476b30a0SYang Shi 
352b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
353b4c2b231SKirill Tkhai 	/* This may call shrinker, so it must use down_read_trylock() */
35441ca668aSYang Shi 	id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
355b4c2b231SKirill Tkhai 	if (id < 0)
356b4c2b231SKirill Tkhai 		goto unlock;
357b4c2b231SKirill Tkhai 
3580a4465d3SKirill Tkhai 	if (id >= shrinker_nr_max) {
359e4262c4fSYang Shi 		if (expand_shrinker_info(id)) {
3600a4465d3SKirill Tkhai 			idr_remove(&shrinker_idr, id);
3610a4465d3SKirill Tkhai 			goto unlock;
3620a4465d3SKirill Tkhai 		}
3630a4465d3SKirill Tkhai 	}
364b4c2b231SKirill Tkhai 	shrinker->id = id;
365b4c2b231SKirill Tkhai 	ret = 0;
366b4c2b231SKirill Tkhai unlock:
367b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
368b4c2b231SKirill Tkhai 	return ret;
369b4c2b231SKirill Tkhai }
370b4c2b231SKirill Tkhai 
371b4c2b231SKirill Tkhai static void unregister_memcg_shrinker(struct shrinker *shrinker)
372b4c2b231SKirill Tkhai {
373b4c2b231SKirill Tkhai 	int id = shrinker->id;
374b4c2b231SKirill Tkhai 
375b4c2b231SKirill Tkhai 	BUG_ON(id < 0);
376b4c2b231SKirill Tkhai 
37741ca668aSYang Shi 	lockdep_assert_held(&shrinker_rwsem);
37841ca668aSYang Shi 
379b4c2b231SKirill Tkhai 	idr_remove(&shrinker_idr, id);
380b4c2b231SKirill Tkhai }
381b4c2b231SKirill Tkhai 
38286750830SYang Shi static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
38386750830SYang Shi 				   struct mem_cgroup *memcg)
38486750830SYang Shi {
38586750830SYang Shi 	struct shrinker_info *info;
38686750830SYang Shi 
38786750830SYang Shi 	info = shrinker_info_protected(memcg, nid);
38886750830SYang Shi 	return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
38986750830SYang Shi }
39086750830SYang Shi 
39186750830SYang Shi static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
39286750830SYang Shi 				  struct mem_cgroup *memcg)
39386750830SYang Shi {
39486750830SYang Shi 	struct shrinker_info *info;
39586750830SYang Shi 
39686750830SYang Shi 	info = shrinker_info_protected(memcg, nid);
39786750830SYang Shi 	return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
39886750830SYang Shi }
39986750830SYang Shi 
400a178015cSYang Shi void reparent_shrinker_deferred(struct mem_cgroup *memcg)
401a178015cSYang Shi {
402a178015cSYang Shi 	int i, nid;
403a178015cSYang Shi 	long nr;
404a178015cSYang Shi 	struct mem_cgroup *parent;
405a178015cSYang Shi 	struct shrinker_info *child_info, *parent_info;
406a178015cSYang Shi 
407a178015cSYang Shi 	parent = parent_mem_cgroup(memcg);
408a178015cSYang Shi 	if (!parent)
409a178015cSYang Shi 		parent = root_mem_cgroup;
410a178015cSYang Shi 
411a178015cSYang Shi 	/* Prevent from concurrent shrinker_info expand */
412a178015cSYang Shi 	down_read(&shrinker_rwsem);
413a178015cSYang Shi 	for_each_node(nid) {
414a178015cSYang Shi 		child_info = shrinker_info_protected(memcg, nid);
415a178015cSYang Shi 		parent_info = shrinker_info_protected(parent, nid);
416a178015cSYang Shi 		for (i = 0; i < shrinker_nr_max; i++) {
417a178015cSYang Shi 			nr = atomic_long_read(&child_info->nr_deferred[i]);
418a178015cSYang Shi 			atomic_long_add(nr, &parent_info->nr_deferred[i]);
419a178015cSYang Shi 		}
420a178015cSYang Shi 	}
421a178015cSYang Shi 	up_read(&shrinker_rwsem);
422a178015cSYang Shi }
423a178015cSYang Shi 
424b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
42589b5fae5SJohannes Weiner {
426b5ead35eSJohannes Weiner 	return sc->target_mem_cgroup;
42789b5fae5SJohannes Weiner }
42897c9341fSTejun Heo 
42997c9341fSTejun Heo /**
430b5ead35eSJohannes Weiner  * writeback_throttling_sane - is the usual dirty throttling mechanism available?
43197c9341fSTejun Heo  * @sc: scan_control in question
43297c9341fSTejun Heo  *
43397c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
43497c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
43597c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
43697c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
43797c9341fSTejun Heo  * allocation and configurability.
43897c9341fSTejun Heo  *
43997c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
44097c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
44197c9341fSTejun Heo  */
442b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
44397c9341fSTejun Heo {
444b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
44597c9341fSTejun Heo 		return true;
44697c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
44769234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
44897c9341fSTejun Heo 		return true;
44997c9341fSTejun Heo #endif
45097c9341fSTejun Heo 	return false;
45197c9341fSTejun Heo }
45291a45470SKAMEZAWA Hiroyuki #else
4530a432dcbSYang Shi static int prealloc_memcg_shrinker(struct shrinker *shrinker)
4540a432dcbSYang Shi {
455476b30a0SYang Shi 	return -ENOSYS;
4560a432dcbSYang Shi }
4570a432dcbSYang Shi 
4580a432dcbSYang Shi static void unregister_memcg_shrinker(struct shrinker *shrinker)
4590a432dcbSYang Shi {
4600a432dcbSYang Shi }
4610a432dcbSYang Shi 
46286750830SYang Shi static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
46386750830SYang Shi 				   struct mem_cgroup *memcg)
46486750830SYang Shi {
46586750830SYang Shi 	return 0;
46686750830SYang Shi }
46786750830SYang Shi 
46886750830SYang Shi static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
46986750830SYang Shi 				  struct mem_cgroup *memcg)
47086750830SYang Shi {
47186750830SYang Shi 	return 0;
47286750830SYang Shi }
47386750830SYang Shi 
474b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
47589b5fae5SJohannes Weiner {
476b5ead35eSJohannes Weiner 	return false;
47789b5fae5SJohannes Weiner }
47897c9341fSTejun Heo 
479b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
48097c9341fSTejun Heo {
48197c9341fSTejun Heo 	return true;
48297c9341fSTejun Heo }
48391a45470SKAMEZAWA Hiroyuki #endif
48491a45470SKAMEZAWA Hiroyuki 
48586750830SYang Shi static long xchg_nr_deferred(struct shrinker *shrinker,
48686750830SYang Shi 			     struct shrink_control *sc)
48786750830SYang Shi {
48886750830SYang Shi 	int nid = sc->nid;
48986750830SYang Shi 
49086750830SYang Shi 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
49186750830SYang Shi 		nid = 0;
49286750830SYang Shi 
49386750830SYang Shi 	if (sc->memcg &&
49486750830SYang Shi 	    (shrinker->flags & SHRINKER_MEMCG_AWARE))
49586750830SYang Shi 		return xchg_nr_deferred_memcg(nid, shrinker,
49686750830SYang Shi 					      sc->memcg);
49786750830SYang Shi 
49886750830SYang Shi 	return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
49986750830SYang Shi }
50086750830SYang Shi 
50186750830SYang Shi 
50286750830SYang Shi static long add_nr_deferred(long nr, struct shrinker *shrinker,
50386750830SYang Shi 			    struct shrink_control *sc)
50486750830SYang Shi {
50586750830SYang Shi 	int nid = sc->nid;
50686750830SYang Shi 
50786750830SYang Shi 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
50886750830SYang Shi 		nid = 0;
50986750830SYang Shi 
51086750830SYang Shi 	if (sc->memcg &&
51186750830SYang Shi 	    (shrinker->flags & SHRINKER_MEMCG_AWARE))
51286750830SYang Shi 		return add_nr_deferred_memcg(nr, nid, shrinker,
51386750830SYang Shi 					     sc->memcg);
51486750830SYang Shi 
51586750830SYang Shi 	return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
51686750830SYang Shi }
51786750830SYang Shi 
5185a1c84b4SMel Gorman /*
5195a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
5205a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
5215a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
5225a1c84b4SMel Gorman  */
5235a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
5245a1c84b4SMel Gorman {
5255a1c84b4SMel Gorman 	unsigned long nr;
5265a1c84b4SMel Gorman 
5275a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
5285a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
5295a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
5305a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
5315a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
5325a1c84b4SMel Gorman 
5335a1c84b4SMel Gorman 	return nr;
5345a1c84b4SMel Gorman }
5355a1c84b4SMel Gorman 
536fd538803SMichal Hocko /**
537fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
538fd538803SMichal Hocko  * @lruvec: lru vector
539fd538803SMichal Hocko  * @lru: lru to use
540fd538803SMichal Hocko  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
541fd538803SMichal Hocko  */
5422091339dSYu Zhao static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
5432091339dSYu Zhao 				     int zone_idx)
544c9f299d9SKOSAKI Motohiro {
545de3b0150SJohannes Weiner 	unsigned long size = 0;
546fd538803SMichal Hocko 	int zid;
547a3d8e054SKOSAKI Motohiro 
548de3b0150SJohannes Weiner 	for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
549fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
550fd538803SMichal Hocko 
551fd538803SMichal Hocko 		if (!managed_zone(zone))
552fd538803SMichal Hocko 			continue;
553fd538803SMichal Hocko 
554fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
555de3b0150SJohannes Weiner 			size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
556fd538803SMichal Hocko 		else
557de3b0150SJohannes Weiner 			size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
558c9f299d9SKOSAKI Motohiro 	}
559de3b0150SJohannes Weiner 	return size;
560b4536f0cSMichal Hocko }
561b4536f0cSMichal Hocko 
5621da177e4SLinus Torvalds /*
5631d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
5641da177e4SLinus Torvalds  */
5658e04944fSTetsuo Handa int prealloc_shrinker(struct shrinker *shrinker)
5661da177e4SLinus Torvalds {
567476b30a0SYang Shi 	unsigned int size;
568476b30a0SYang Shi 	int err;
5691d3d4437SGlauber Costa 
570476b30a0SYang Shi 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
571476b30a0SYang Shi 		err = prealloc_memcg_shrinker(shrinker);
572476b30a0SYang Shi 		if (err != -ENOSYS)
573476b30a0SYang Shi 			return err;
574476b30a0SYang Shi 
575476b30a0SYang Shi 		shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
576476b30a0SYang Shi 	}
577476b30a0SYang Shi 
578476b30a0SYang Shi 	size = sizeof(*shrinker->nr_deferred);
5791d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
5801d3d4437SGlauber Costa 		size *= nr_node_ids;
5811d3d4437SGlauber Costa 
5821d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
5831d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
5841d3d4437SGlauber Costa 		return -ENOMEM;
585b4c2b231SKirill Tkhai 
5868e04944fSTetsuo Handa 	return 0;
5878e04944fSTetsuo Handa }
5881d3d4437SGlauber Costa 
5898e04944fSTetsuo Handa void free_prealloced_shrinker(struct shrinker *shrinker)
5908e04944fSTetsuo Handa {
59141ca668aSYang Shi 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
59241ca668aSYang Shi 		down_write(&shrinker_rwsem);
593b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
59441ca668aSYang Shi 		up_write(&shrinker_rwsem);
595476b30a0SYang Shi 		return;
59641ca668aSYang Shi 	}
597b4c2b231SKirill Tkhai 
5988e04944fSTetsuo Handa 	kfree(shrinker->nr_deferred);
5998e04944fSTetsuo Handa 	shrinker->nr_deferred = NULL;
6008e04944fSTetsuo Handa }
6018e04944fSTetsuo Handa 
6028e04944fSTetsuo Handa void register_shrinker_prepared(struct shrinker *shrinker)
6038e04944fSTetsuo Handa {
6041da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
6051da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
60641ca668aSYang Shi 	shrinker->flags |= SHRINKER_REGISTERED;
6071da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
6088e04944fSTetsuo Handa }
6098e04944fSTetsuo Handa 
6108e04944fSTetsuo Handa int register_shrinker(struct shrinker *shrinker)
6118e04944fSTetsuo Handa {
6128e04944fSTetsuo Handa 	int err = prealloc_shrinker(shrinker);
6138e04944fSTetsuo Handa 
6148e04944fSTetsuo Handa 	if (err)
6158e04944fSTetsuo Handa 		return err;
6168e04944fSTetsuo Handa 	register_shrinker_prepared(shrinker);
6171d3d4437SGlauber Costa 	return 0;
6181da177e4SLinus Torvalds }
6198e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
6201da177e4SLinus Torvalds 
6211da177e4SLinus Torvalds /*
6221da177e4SLinus Torvalds  * Remove one
6231da177e4SLinus Torvalds  */
6248e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
6251da177e4SLinus Torvalds {
62641ca668aSYang Shi 	if (!(shrinker->flags & SHRINKER_REGISTERED))
627bb422a73STetsuo Handa 		return;
62841ca668aSYang Shi 
6291da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
6301da177e4SLinus Torvalds 	list_del(&shrinker->list);
63141ca668aSYang Shi 	shrinker->flags &= ~SHRINKER_REGISTERED;
63241ca668aSYang Shi 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
63341ca668aSYang Shi 		unregister_memcg_shrinker(shrinker);
6341da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
63541ca668aSYang Shi 
636ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
637bb422a73STetsuo Handa 	shrinker->nr_deferred = NULL;
6381da177e4SLinus Torvalds }
6398e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
6401da177e4SLinus Torvalds 
6411da177e4SLinus Torvalds #define SHRINK_BATCH 128
6421d3d4437SGlauber Costa 
643cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
6449092c71bSJosef Bacik 				    struct shrinker *shrinker, int priority)
6451da177e4SLinus Torvalds {
64624f7c6b9SDave Chinner 	unsigned long freed = 0;
6471da177e4SLinus Torvalds 	unsigned long long delta;
648635697c6SKonstantin Khlebnikov 	long total_scan;
649d5bc5fd3SVladimir Davydov 	long freeable;
650acf92b48SDave Chinner 	long nr;
651acf92b48SDave Chinner 	long new_nr;
652e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
653e9299f50SDave Chinner 					  : SHRINK_BATCH;
6545f33a080SShaohua Li 	long scanned = 0, next_deferred;
6551da177e4SLinus Torvalds 
656d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
6579b996468SKirill Tkhai 	if (freeable == 0 || freeable == SHRINK_EMPTY)
6589b996468SKirill Tkhai 		return freeable;
659635697c6SKonstantin Khlebnikov 
660acf92b48SDave Chinner 	/*
661acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
662acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
663acf92b48SDave Chinner 	 * don't also do this scanning work.
664acf92b48SDave Chinner 	 */
66586750830SYang Shi 	nr = xchg_nr_deferred(shrinker, shrinkctl);
666acf92b48SDave Chinner 
6674b85afbdSJohannes Weiner 	if (shrinker->seeks) {
6689092c71bSJosef Bacik 		delta = freeable >> priority;
6699092c71bSJosef Bacik 		delta *= 4;
6709092c71bSJosef Bacik 		do_div(delta, shrinker->seeks);
6714b85afbdSJohannes Weiner 	} else {
6724b85afbdSJohannes Weiner 		/*
6734b85afbdSJohannes Weiner 		 * These objects don't require any IO to create. Trim
6744b85afbdSJohannes Weiner 		 * them aggressively under memory pressure to keep
6754b85afbdSJohannes Weiner 		 * them from causing refetches in the IO caches.
6764b85afbdSJohannes Weiner 		 */
6774b85afbdSJohannes Weiner 		delta = freeable / 2;
6784b85afbdSJohannes Weiner 	}
679172b06c3SRoman Gushchin 
68018bb473eSYang Shi 	total_scan = nr >> priority;
681acf92b48SDave Chinner 	total_scan += delta;
68218bb473eSYang Shi 	total_scan = min(total_scan, (2 * freeable));
6831da177e4SLinus Torvalds 
68424f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
6859092c71bSJosef Bacik 				   freeable, delta, total_scan, priority);
68609576073SDave Chinner 
6870b1fb40aSVladimir Davydov 	/*
6880b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
6890b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
6900b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
6910b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
6920b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
6930b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
6940b1fb40aSVladimir Davydov 	 * batch_size.
6950b1fb40aSVladimir Davydov 	 *
6960b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
6970b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
698d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
6990b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
7000b1fb40aSVladimir Davydov 	 * possible.
7010b1fb40aSVladimir Davydov 	 */
7020b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
703d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
70424f7c6b9SDave Chinner 		unsigned long ret;
7050b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
7061da177e4SLinus Torvalds 
7070b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
708d460acb5SChris Wilson 		shrinkctl->nr_scanned = nr_to_scan;
70924f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
71024f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
7111da177e4SLinus Torvalds 			break;
71224f7c6b9SDave Chinner 		freed += ret;
71324f7c6b9SDave Chinner 
714d460acb5SChris Wilson 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
715d460acb5SChris Wilson 		total_scan -= shrinkctl->nr_scanned;
716d460acb5SChris Wilson 		scanned += shrinkctl->nr_scanned;
7171da177e4SLinus Torvalds 
7181da177e4SLinus Torvalds 		cond_resched();
7191da177e4SLinus Torvalds 	}
7201da177e4SLinus Torvalds 
72118bb473eSYang Shi 	/*
72218bb473eSYang Shi 	 * The deferred work is increased by any new work (delta) that wasn't
72318bb473eSYang Shi 	 * done, decreased by old deferred work that was done now.
72418bb473eSYang Shi 	 *
72518bb473eSYang Shi 	 * And it is capped to two times of the freeable items.
72618bb473eSYang Shi 	 */
72718bb473eSYang Shi 	next_deferred = max_t(long, (nr + delta - scanned), 0);
72818bb473eSYang Shi 	next_deferred = min(next_deferred, (2 * freeable));
72918bb473eSYang Shi 
730acf92b48SDave Chinner 	/*
731acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
73286750830SYang Shi 	 * manner that handles concurrent updates.
733acf92b48SDave Chinner 	 */
73486750830SYang Shi 	new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
735acf92b48SDave Chinner 
7368efb4b59SYang Shi 	trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
7371d3d4437SGlauber Costa 	return freed;
7381d3d4437SGlauber Costa }
7391d3d4437SGlauber Costa 
7400a432dcbSYang Shi #ifdef CONFIG_MEMCG
741b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
742b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
743b0dedc49SKirill Tkhai {
744e4262c4fSYang Shi 	struct shrinker_info *info;
745b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
746b8e57efaSKirill Tkhai 	int i;
747b0dedc49SKirill Tkhai 
7480a432dcbSYang Shi 	if (!mem_cgroup_online(memcg))
749b0dedc49SKirill Tkhai 		return 0;
750b0dedc49SKirill Tkhai 
751b0dedc49SKirill Tkhai 	if (!down_read_trylock(&shrinker_rwsem))
752b0dedc49SKirill Tkhai 		return 0;
753b0dedc49SKirill Tkhai 
754468ab843SYang Shi 	info = shrinker_info_protected(memcg, nid);
755e4262c4fSYang Shi 	if (unlikely(!info))
756b0dedc49SKirill Tkhai 		goto unlock;
757b0dedc49SKirill Tkhai 
758e4262c4fSYang Shi 	for_each_set_bit(i, info->map, shrinker_nr_max) {
759b0dedc49SKirill Tkhai 		struct shrink_control sc = {
760b0dedc49SKirill Tkhai 			.gfp_mask = gfp_mask,
761b0dedc49SKirill Tkhai 			.nid = nid,
762b0dedc49SKirill Tkhai 			.memcg = memcg,
763b0dedc49SKirill Tkhai 		};
764b0dedc49SKirill Tkhai 		struct shrinker *shrinker;
765b0dedc49SKirill Tkhai 
766b0dedc49SKirill Tkhai 		shrinker = idr_find(&shrinker_idr, i);
76741ca668aSYang Shi 		if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
7687e010df5SKirill Tkhai 			if (!shrinker)
769e4262c4fSYang Shi 				clear_bit(i, info->map);
770b0dedc49SKirill Tkhai 			continue;
771b0dedc49SKirill Tkhai 		}
772b0dedc49SKirill Tkhai 
7730a432dcbSYang Shi 		/* Call non-slab shrinkers even though kmem is disabled */
7740a432dcbSYang Shi 		if (!memcg_kmem_enabled() &&
7750a432dcbSYang Shi 		    !(shrinker->flags & SHRINKER_NONSLAB))
7760a432dcbSYang Shi 			continue;
7770a432dcbSYang Shi 
778b0dedc49SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
779f90280d6SKirill Tkhai 		if (ret == SHRINK_EMPTY) {
780e4262c4fSYang Shi 			clear_bit(i, info->map);
781f90280d6SKirill Tkhai 			/*
782f90280d6SKirill Tkhai 			 * After the shrinker reported that it had no objects to
783f90280d6SKirill Tkhai 			 * free, but before we cleared the corresponding bit in
784f90280d6SKirill Tkhai 			 * the memcg shrinker map, a new object might have been
785f90280d6SKirill Tkhai 			 * added. To make sure, we have the bit set in this
786f90280d6SKirill Tkhai 			 * case, we invoke the shrinker one more time and reset
787f90280d6SKirill Tkhai 			 * the bit if it reports that it is not empty anymore.
788f90280d6SKirill Tkhai 			 * The memory barrier here pairs with the barrier in
7892bfd3637SYang Shi 			 * set_shrinker_bit():
790f90280d6SKirill Tkhai 			 *
791f90280d6SKirill Tkhai 			 * list_lru_add()     shrink_slab_memcg()
792f90280d6SKirill Tkhai 			 *   list_add_tail()    clear_bit()
793f90280d6SKirill Tkhai 			 *   <MB>               <MB>
794f90280d6SKirill Tkhai 			 *   set_bit()          do_shrink_slab()
795f90280d6SKirill Tkhai 			 */
796f90280d6SKirill Tkhai 			smp_mb__after_atomic();
797f90280d6SKirill Tkhai 			ret = do_shrink_slab(&sc, shrinker, priority);
7989b996468SKirill Tkhai 			if (ret == SHRINK_EMPTY)
7999b996468SKirill Tkhai 				ret = 0;
800f90280d6SKirill Tkhai 			else
8012bfd3637SYang Shi 				set_shrinker_bit(memcg, nid, i);
802f90280d6SKirill Tkhai 		}
803b0dedc49SKirill Tkhai 		freed += ret;
804b0dedc49SKirill Tkhai 
805b0dedc49SKirill Tkhai 		if (rwsem_is_contended(&shrinker_rwsem)) {
806b0dedc49SKirill Tkhai 			freed = freed ? : 1;
807b0dedc49SKirill Tkhai 			break;
808b0dedc49SKirill Tkhai 		}
809b0dedc49SKirill Tkhai 	}
810b0dedc49SKirill Tkhai unlock:
811b0dedc49SKirill Tkhai 	up_read(&shrinker_rwsem);
812b0dedc49SKirill Tkhai 	return freed;
813b0dedc49SKirill Tkhai }
8140a432dcbSYang Shi #else /* CONFIG_MEMCG */
815b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
816b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
817b0dedc49SKirill Tkhai {
818b0dedc49SKirill Tkhai 	return 0;
819b0dedc49SKirill Tkhai }
8200a432dcbSYang Shi #endif /* CONFIG_MEMCG */
821b0dedc49SKirill Tkhai 
8226b4f7799SJohannes Weiner /**
823cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
8246b4f7799SJohannes Weiner  * @gfp_mask: allocation context
8256b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
826cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
8279092c71bSJosef Bacik  * @priority: the reclaim priority
8281d3d4437SGlauber Costa  *
8296b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
8301d3d4437SGlauber Costa  *
8316b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
8326b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
8331d3d4437SGlauber Costa  *
834aeed1d32SVladimir Davydov  * @memcg specifies the memory cgroup to target. Unaware shrinkers
835aeed1d32SVladimir Davydov  * are called only if it is the root cgroup.
836cb731d6cSVladimir Davydov  *
8379092c71bSJosef Bacik  * @priority is sc->priority, we take the number of objects and >> by priority
8389092c71bSJosef Bacik  * in order to get the scan target.
8391d3d4437SGlauber Costa  *
8406b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
8411d3d4437SGlauber Costa  */
842cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
843cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
8449092c71bSJosef Bacik 				 int priority)
8451d3d4437SGlauber Costa {
846b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
8471d3d4437SGlauber Costa 	struct shrinker *shrinker;
8481d3d4437SGlauber Costa 
849fa1e512fSYang Shi 	/*
850fa1e512fSYang Shi 	 * The root memcg might be allocated even though memcg is disabled
851fa1e512fSYang Shi 	 * via "cgroup_disable=memory" boot parameter.  This could make
852fa1e512fSYang Shi 	 * mem_cgroup_is_root() return false, then just run memcg slab
853fa1e512fSYang Shi 	 * shrink, but skip global shrink.  This may result in premature
854fa1e512fSYang Shi 	 * oom.
855fa1e512fSYang Shi 	 */
856fa1e512fSYang Shi 	if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
857b0dedc49SKirill Tkhai 		return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
858cb731d6cSVladimir Davydov 
859e830c63aSTetsuo Handa 	if (!down_read_trylock(&shrinker_rwsem))
8601d3d4437SGlauber Costa 		goto out;
8611d3d4437SGlauber Costa 
8621d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
8636b4f7799SJohannes Weiner 		struct shrink_control sc = {
8646b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
8656b4f7799SJohannes Weiner 			.nid = nid,
866cb731d6cSVladimir Davydov 			.memcg = memcg,
8676b4f7799SJohannes Weiner 		};
8686b4f7799SJohannes Weiner 
8699b996468SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
8709b996468SKirill Tkhai 		if (ret == SHRINK_EMPTY)
8719b996468SKirill Tkhai 			ret = 0;
8729b996468SKirill Tkhai 		freed += ret;
873e496612cSMinchan Kim 		/*
874e496612cSMinchan Kim 		 * Bail out if someone want to register a new shrinker to
87555b65a57SEthon Paul 		 * prevent the registration from being stalled for long periods
876e496612cSMinchan Kim 		 * by parallel ongoing shrinking.
877e496612cSMinchan Kim 		 */
878e496612cSMinchan Kim 		if (rwsem_is_contended(&shrinker_rwsem)) {
879e496612cSMinchan Kim 			freed = freed ? : 1;
880e496612cSMinchan Kim 			break;
881e496612cSMinchan Kim 		}
882ec97097bSVladimir Davydov 	}
8831d3d4437SGlauber Costa 
8841da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
885f06590bdSMinchan Kim out:
886f06590bdSMinchan Kim 	cond_resched();
88724f7c6b9SDave Chinner 	return freed;
8881da177e4SLinus Torvalds }
8891da177e4SLinus Torvalds 
890cb731d6cSVladimir Davydov void drop_slab_node(int nid)
891cb731d6cSVladimir Davydov {
892cb731d6cSVladimir Davydov 	unsigned long freed;
893cb731d6cSVladimir Davydov 
894cb731d6cSVladimir Davydov 	do {
895cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
896cb731d6cSVladimir Davydov 
897069c411dSChunxin Zang 		if (fatal_signal_pending(current))
898069c411dSChunxin Zang 			return;
899069c411dSChunxin Zang 
900cb731d6cSVladimir Davydov 		freed = 0;
901aeed1d32SVladimir Davydov 		memcg = mem_cgroup_iter(NULL, NULL, NULL);
902cb731d6cSVladimir Davydov 		do {
9039092c71bSJosef Bacik 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
904cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
905cb731d6cSVladimir Davydov 	} while (freed > 10);
906cb731d6cSVladimir Davydov }
907cb731d6cSVladimir Davydov 
908cb731d6cSVladimir Davydov void drop_slab(void)
909cb731d6cSVladimir Davydov {
910cb731d6cSVladimir Davydov 	int nid;
911cb731d6cSVladimir Davydov 
912cb731d6cSVladimir Davydov 	for_each_online_node(nid)
913cb731d6cSVladimir Davydov 		drop_slab_node(nid);
914cb731d6cSVladimir Davydov }
915cb731d6cSVladimir Davydov 
9161da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
9171da177e4SLinus Torvalds {
918ceddc3a5SJohannes Weiner 	/*
919ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
92067891fffSMatthew Wilcox 	 * that isolated the page, the page cache and optional buffer
92167891fffSMatthew Wilcox 	 * heads at page->private.
922ceddc3a5SJohannes Weiner 	 */
9233efe62e4SMatthew Wilcox (Oracle) 	int page_cache_pins = thp_nr_pages(page);
92467891fffSMatthew Wilcox 	return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
9251da177e4SLinus Torvalds }
9261da177e4SLinus Torvalds 
927cb16556dSYang Shi static int may_write_to_inode(struct inode *inode)
9281da177e4SLinus Torvalds {
929930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
9301da177e4SLinus Torvalds 		return 1;
931703c2708STejun Heo 	if (!inode_write_congested(inode))
9321da177e4SLinus Torvalds 		return 1;
933703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
9341da177e4SLinus Torvalds 		return 1;
9351da177e4SLinus Torvalds 	return 0;
9361da177e4SLinus Torvalds }
9371da177e4SLinus Torvalds 
9381da177e4SLinus Torvalds /*
9391da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
9401da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
9411da177e4SLinus Torvalds  * fsync(), msync() or close().
9421da177e4SLinus Torvalds  *
9431da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
9441da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
9451da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
9461da177e4SLinus Torvalds  *
9471da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
9481da177e4SLinus Torvalds  * __GFP_FS.
9491da177e4SLinus Torvalds  */
9501da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
9511da177e4SLinus Torvalds 				struct page *page, int error)
9521da177e4SLinus Torvalds {
9537eaceaccSJens Axboe 	lock_page(page);
9543e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
9553e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
9561da177e4SLinus Torvalds 	unlock_page(page);
9571da177e4SLinus Torvalds }
9581da177e4SLinus Torvalds 
95904e62a29SChristoph Lameter /* possible outcome of pageout() */
96004e62a29SChristoph Lameter typedef enum {
96104e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
96204e62a29SChristoph Lameter 	PAGE_KEEP,
96304e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
96404e62a29SChristoph Lameter 	PAGE_ACTIVATE,
96504e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
96604e62a29SChristoph Lameter 	PAGE_SUCCESS,
96704e62a29SChristoph Lameter 	/* page is clean and locked */
96804e62a29SChristoph Lameter 	PAGE_CLEAN,
96904e62a29SChristoph Lameter } pageout_t;
97004e62a29SChristoph Lameter 
9711da177e4SLinus Torvalds /*
9721742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
9731742f19fSAndrew Morton  * Calls ->writepage().
9741da177e4SLinus Torvalds  */
975cb16556dSYang Shi static pageout_t pageout(struct page *page, struct address_space *mapping)
9761da177e4SLinus Torvalds {
9771da177e4SLinus Torvalds 	/*
9781da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
9791da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
9801da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
9811da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
9821da177e4SLinus Torvalds 	 * PagePrivate for that.
9831da177e4SLinus Torvalds 	 *
9848174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
9851da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
9861da177e4SLinus Torvalds 	 * will block.
9871da177e4SLinus Torvalds 	 *
9881da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
9891da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
9901da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
9911da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
9921da177e4SLinus Torvalds 	 */
9931da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
9941da177e4SLinus Torvalds 		return PAGE_KEEP;
9951da177e4SLinus Torvalds 	if (!mapping) {
9961da177e4SLinus Torvalds 		/*
9971da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
9981da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
9991da177e4SLinus Torvalds 		 */
1000266cf658SDavid Howells 		if (page_has_private(page)) {
10011da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
10021da177e4SLinus Torvalds 				ClearPageDirty(page);
1003b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
10041da177e4SLinus Torvalds 				return PAGE_CLEAN;
10051da177e4SLinus Torvalds 			}
10061da177e4SLinus Torvalds 		}
10071da177e4SLinus Torvalds 		return PAGE_KEEP;
10081da177e4SLinus Torvalds 	}
10091da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
10101da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
1011cb16556dSYang Shi 	if (!may_write_to_inode(mapping->host))
10121da177e4SLinus Torvalds 		return PAGE_KEEP;
10131da177e4SLinus Torvalds 
10141da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
10151da177e4SLinus Torvalds 		int res;
10161da177e4SLinus Torvalds 		struct writeback_control wbc = {
10171da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
10181da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
1019111ebb6eSOGAWA Hirofumi 			.range_start = 0,
1020111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
10211da177e4SLinus Torvalds 			.for_reclaim = 1,
10221da177e4SLinus Torvalds 		};
10231da177e4SLinus Torvalds 
10241da177e4SLinus Torvalds 		SetPageReclaim(page);
10251da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
10261da177e4SLinus Torvalds 		if (res < 0)
10271da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
1028994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
10291da177e4SLinus Torvalds 			ClearPageReclaim(page);
10301da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
10311da177e4SLinus Torvalds 		}
1032c661b078SAndy Whitcroft 
10331da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
10341da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
10351da177e4SLinus Torvalds 			ClearPageReclaim(page);
10361da177e4SLinus Torvalds 		}
10373aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
1038c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
10391da177e4SLinus Torvalds 		return PAGE_SUCCESS;
10401da177e4SLinus Torvalds 	}
10411da177e4SLinus Torvalds 
10421da177e4SLinus Torvalds 	return PAGE_CLEAN;
10431da177e4SLinus Torvalds }
10441da177e4SLinus Torvalds 
1045a649fd92SAndrew Morton /*
1046e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
1047e286781dSNick Piggin  * gets returned with a refcount of 0.
1048a649fd92SAndrew Morton  */
1049a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
1050b910718aSJohannes Weiner 			    bool reclaimed, struct mem_cgroup *target_memcg)
105149d2e9ccSChristoph Lameter {
1052c4843a75SGreg Thelen 	unsigned long flags;
1053bd4c82c2SHuang Ying 	int refcount;
1054aae466b0SJoonsoo Kim 	void *shadow = NULL;
1055c4843a75SGreg Thelen 
105628e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
105728e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
105849d2e9ccSChristoph Lameter 
1059b93b0163SMatthew Wilcox 	xa_lock_irqsave(&mapping->i_pages, flags);
106049d2e9ccSChristoph Lameter 	/*
10610fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
10620fd0e6b0SNick Piggin 	 *
10630fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
10640fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
10650fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
10660fd0e6b0SNick Piggin 	 * here, then the following race may occur:
10670fd0e6b0SNick Piggin 	 *
10680fd0e6b0SNick Piggin 	 * get_user_pages(&page);
10690fd0e6b0SNick Piggin 	 * [user mapping goes away]
10700fd0e6b0SNick Piggin 	 * write_to(page);
10710fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
10720fd0e6b0SNick Piggin 	 * SetPageDirty(page);
10730fd0e6b0SNick Piggin 	 * put_page(page);
10740fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
10750fd0e6b0SNick Piggin 	 *
10760fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
10770fd0e6b0SNick Piggin 	 *
10780fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
10790fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
10800139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
10810fd0e6b0SNick Piggin 	 *
10820fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
1083b93b0163SMatthew Wilcox 	 * and thus under the i_pages lock, then this ordering is not required.
108449d2e9ccSChristoph Lameter 	 */
1085906d278dSWilliam Kucharski 	refcount = 1 + compound_nr(page);
1086bd4c82c2SHuang Ying 	if (!page_ref_freeze(page, refcount))
108749d2e9ccSChristoph Lameter 		goto cannot_free;
10881c4c3b99SJiang Biao 	/* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
1089e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
1090bd4c82c2SHuang Ying 		page_ref_unfreeze(page, refcount);
109149d2e9ccSChristoph Lameter 		goto cannot_free;
1092e286781dSNick Piggin 	}
109349d2e9ccSChristoph Lameter 
109449d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
109549d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
10960a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
1097aae466b0SJoonsoo Kim 		if (reclaimed && !mapping_exiting(mapping))
1098aae466b0SJoonsoo Kim 			shadow = workingset_eviction(page, target_memcg);
1099aae466b0SJoonsoo Kim 		__delete_from_swap_cache(page, swap, shadow);
1100b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
110175f6d6d2SMinchan Kim 		put_swap_page(page, swap);
1102e286781dSNick Piggin 	} else {
11036072d13cSLinus Torvalds 		void (*freepage)(struct page *);
11046072d13cSLinus Torvalds 
11056072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
1106a528910eSJohannes Weiner 		/*
1107a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
1108a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
1109a528910eSJohannes Weiner 		 *
1110a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
1111238c3046Sdylan-meiners 		 * already exiting.  This is not just an optimization,
1112a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
1113a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
1114a528910eSJohannes Weiner 		 * back.
1115f9fe48beSRoss Zwisler 		 *
1116f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
1117f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
1118f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
1119f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
1120b93b0163SMatthew Wilcox 		 * same address_space.
1121a528910eSJohannes Weiner 		 */
11229de4f22aSHuang Ying 		if (reclaimed && page_is_file_lru(page) &&
1123f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
1124b910718aSJohannes Weiner 			shadow = workingset_eviction(page, target_memcg);
112562cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
1126b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
11276072d13cSLinus Torvalds 
11286072d13cSLinus Torvalds 		if (freepage != NULL)
11296072d13cSLinus Torvalds 			freepage(page);
1130e286781dSNick Piggin 	}
1131e286781dSNick Piggin 
113249d2e9ccSChristoph Lameter 	return 1;
113349d2e9ccSChristoph Lameter 
113449d2e9ccSChristoph Lameter cannot_free:
1135b93b0163SMatthew Wilcox 	xa_unlock_irqrestore(&mapping->i_pages, flags);
113649d2e9ccSChristoph Lameter 	return 0;
113749d2e9ccSChristoph Lameter }
113849d2e9ccSChristoph Lameter 
11391da177e4SLinus Torvalds /*
1140e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
1141e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
1142e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
1143e286781dSNick Piggin  * this page.
1144e286781dSNick Piggin  */
1145e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
1146e286781dSNick Piggin {
1147b910718aSJohannes Weiner 	if (__remove_mapping(mapping, page, false, NULL)) {
1148e286781dSNick Piggin 		/*
1149e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
1150e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
1151e286781dSNick Piggin 		 * atomic operation.
1152e286781dSNick Piggin 		 */
1153fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
1154e286781dSNick Piggin 		return 1;
1155e286781dSNick Piggin 	}
1156e286781dSNick Piggin 	return 0;
1157e286781dSNick Piggin }
1158e286781dSNick Piggin 
1159894bc310SLee Schermerhorn /**
1160894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
1161894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
1162894bc310SLee Schermerhorn  *
1163894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
1164894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
1165894bc310SLee Schermerhorn  *
1166894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
1167894bc310SLee Schermerhorn  */
1168894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
1169894bc310SLee Schermerhorn {
1170c53954a0SMel Gorman 	lru_cache_add(page);
1171894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
1172894bc310SLee Schermerhorn }
1173894bc310SLee Schermerhorn 
1174dfc8d636SJohannes Weiner enum page_references {
1175dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
1176dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
117764574746SJohannes Weiner 	PAGEREF_KEEP,
1178dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
1179dfc8d636SJohannes Weiner };
1180dfc8d636SJohannes Weiner 
1181dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
1182dfc8d636SJohannes Weiner 						  struct scan_control *sc)
1183dfc8d636SJohannes Weiner {
118464574746SJohannes Weiner 	int referenced_ptes, referenced_page;
1185dfc8d636SJohannes Weiner 	unsigned long vm_flags;
1186dfc8d636SJohannes Weiner 
1187c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1188c3ac9a8aSJohannes Weiner 					  &vm_flags);
118964574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
1190dfc8d636SJohannes Weiner 
1191dfc8d636SJohannes Weiner 	/*
1192dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
1193dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
1194dfc8d636SJohannes Weiner 	 */
1195dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
1196dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
1197dfc8d636SJohannes Weiner 
119864574746SJohannes Weiner 	if (referenced_ptes) {
119964574746SJohannes Weiner 		/*
120064574746SJohannes Weiner 		 * All mapped pages start out with page table
120164574746SJohannes Weiner 		 * references from the instantiating fault, so we need
120264574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
120364574746SJohannes Weiner 		 * than once.
120464574746SJohannes Weiner 		 *
120564574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
120664574746SJohannes Weiner 		 * inactive list.  Another page table reference will
120764574746SJohannes Weiner 		 * lead to its activation.
120864574746SJohannes Weiner 		 *
120964574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
121064574746SJohannes Weiner 		 * so that recently deactivated but used pages are
121164574746SJohannes Weiner 		 * quickly recovered.
121264574746SJohannes Weiner 		 */
121364574746SJohannes Weiner 		SetPageReferenced(page);
121464574746SJohannes Weiner 
121534dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
1216dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
1217dfc8d636SJohannes Weiner 
1218c909e993SKonstantin Khlebnikov 		/*
1219c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
1220c909e993SKonstantin Khlebnikov 		 */
1221b518154eSJoonsoo Kim 		if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
1222c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
1223c909e993SKonstantin Khlebnikov 
122464574746SJohannes Weiner 		return PAGEREF_KEEP;
122564574746SJohannes Weiner 	}
122664574746SJohannes Weiner 
1227dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
12282e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
1229dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
123064574746SJohannes Weiner 
123164574746SJohannes Weiner 	return PAGEREF_RECLAIM;
1232dfc8d636SJohannes Weiner }
1233dfc8d636SJohannes Weiner 
1234e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
1235e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
1236e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
1237e2be15f6SMel Gorman {
1238b4597226SMel Gorman 	struct address_space *mapping;
1239b4597226SMel Gorman 
1240e2be15f6SMel Gorman 	/*
1241e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
1242e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
1243e2be15f6SMel Gorman 	 */
12449de4f22aSHuang Ying 	if (!page_is_file_lru(page) ||
1245802a3a92SShaohua Li 	    (PageAnon(page) && !PageSwapBacked(page))) {
1246e2be15f6SMel Gorman 		*dirty = false;
1247e2be15f6SMel Gorman 		*writeback = false;
1248e2be15f6SMel Gorman 		return;
1249e2be15f6SMel Gorman 	}
1250e2be15f6SMel Gorman 
1251e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
1252e2be15f6SMel Gorman 	*dirty = PageDirty(page);
1253e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
1254b4597226SMel Gorman 
1255b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
1256b4597226SMel Gorman 	if (!page_has_private(page))
1257b4597226SMel Gorman 		return;
1258b4597226SMel Gorman 
1259b4597226SMel Gorman 	mapping = page_mapping(page);
1260b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
1261b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1262e2be15f6SMel Gorman }
1263e2be15f6SMel Gorman 
1264e286781dSNick Piggin /*
12651742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
12661da177e4SLinus Torvalds  */
1267730ec8c0SManinder Singh static unsigned int shrink_page_list(struct list_head *page_list,
1268599d0c95SMel Gorman 				     struct pglist_data *pgdat,
1269f84f6e2bSMel Gorman 				     struct scan_control *sc,
12703c710c1aSMichal Hocko 				     struct reclaim_stat *stat,
12718940b34aSMinchan Kim 				     bool ignore_references)
12721da177e4SLinus Torvalds {
12731da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
1274abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
1275730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
1276730ec8c0SManinder Singh 	unsigned int pgactivate = 0;
12771da177e4SLinus Torvalds 
1278060f005fSKirill Tkhai 	memset(stat, 0, sizeof(*stat));
12791da177e4SLinus Torvalds 	cond_resched();
12801da177e4SLinus Torvalds 
12811da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
12821da177e4SLinus Torvalds 		struct address_space *mapping;
12831da177e4SLinus Torvalds 		struct page *page;
12848940b34aSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM;
12854b793062SKirill Tkhai 		bool dirty, writeback, may_enter_fs;
128698879b3bSYang Shi 		unsigned int nr_pages;
12871da177e4SLinus Torvalds 
12881da177e4SLinus Torvalds 		cond_resched();
12891da177e4SLinus Torvalds 
12901da177e4SLinus Torvalds 		page = lru_to_page(page_list);
12911da177e4SLinus Torvalds 		list_del(&page->lru);
12921da177e4SLinus Torvalds 
1293529ae9aaSNick Piggin 		if (!trylock_page(page))
12941da177e4SLinus Torvalds 			goto keep;
12951da177e4SLinus Torvalds 
1296309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
12971da177e4SLinus Torvalds 
1298d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
129998879b3bSYang Shi 
130098879b3bSYang Shi 		/* Account the number of base pages even though THP */
130198879b3bSYang Shi 		sc->nr_scanned += nr_pages;
130280e43426SChristoph Lameter 
130339b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
1304ad6b6704SMinchan Kim 			goto activate_locked;
1305894bc310SLee Schermerhorn 
1306a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
130780e43426SChristoph Lameter 			goto keep_locked;
130880e43426SChristoph Lameter 
1309c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1310c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1311c661b078SAndy Whitcroft 
1312e62e384eSMichal Hocko 		/*
1313894befecSAndrey Ryabinin 		 * The number of dirty pages determines if a node is marked
1314e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
1315e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
1316e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
1317e2be15f6SMel Gorman 		 */
1318e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
1319e2be15f6SMel Gorman 		if (dirty || writeback)
1320060f005fSKirill Tkhai 			stat->nr_dirty++;
1321e2be15f6SMel Gorman 
1322e2be15f6SMel Gorman 		if (dirty && !writeback)
1323060f005fSKirill Tkhai 			stat->nr_unqueued_dirty++;
1324e2be15f6SMel Gorman 
1325d04e8acdSMel Gorman 		/*
1326d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
1327d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
1328d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
1329d04e8acdSMel Gorman 		 * end of the LRU a second time.
1330d04e8acdSMel Gorman 		 */
1331e2be15f6SMel Gorman 		mapping = page_mapping(page);
13321da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
1333703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
1334d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
1335060f005fSKirill Tkhai 			stat->nr_congested++;
1336e2be15f6SMel Gorman 
1337e2be15f6SMel Gorman 		/*
1338283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
1339283aba9fSMel Gorman 		 * are three cases to consider.
1340e62e384eSMichal Hocko 		 *
1341283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
1342283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
1343283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
1344283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
1345283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
1346283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
1347283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
1348b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
1349b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
1350c3b94f44SHugh Dickins 		 *
135197c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
1352ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1353ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1354ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
135597c9341fSTejun Heo 		 *    reclaim and continue scanning.
1356283aba9fSMel Gorman 		 *
1357ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1358ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1359283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1360283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1361283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1362283aba9fSMel Gorman 		 *    would probably show more reasons.
1363283aba9fSMel Gorman 		 *
13647fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1365283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1366283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1367283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1368283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1369c55e8d03SJohannes Weiner 		 *
1370c55e8d03SJohannes Weiner 		 * In cases 1) and 2) we activate the pages to get them out of
1371c55e8d03SJohannes Weiner 		 * the way while we continue scanning for clean pages on the
1372c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1373c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1374c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1375c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1376c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1377c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1378e62e384eSMichal Hocko 		 */
1379283aba9fSMel Gorman 		if (PageWriteback(page)) {
1380283aba9fSMel Gorman 			/* Case 1 above */
1381283aba9fSMel Gorman 			if (current_is_kswapd() &&
1382283aba9fSMel Gorman 			    PageReclaim(page) &&
1383599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1384060f005fSKirill Tkhai 				stat->nr_immediate++;
1385c55e8d03SJohannes Weiner 				goto activate_locked;
1386283aba9fSMel Gorman 
1387283aba9fSMel Gorman 			/* Case 2 above */
1388b5ead35eSJohannes Weiner 			} else if (writeback_throttling_sane(sc) ||
1389ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1390c3b94f44SHugh Dickins 				/*
1391c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1392c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1393c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1394c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1395c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1396c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1397c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1398c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1399c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1400c3b94f44SHugh Dickins 				 */
1401c3b94f44SHugh Dickins 				SetPageReclaim(page);
1402060f005fSKirill Tkhai 				stat->nr_writeback++;
1403c55e8d03SJohannes Weiner 				goto activate_locked;
1404283aba9fSMel Gorman 
1405283aba9fSMel Gorman 			/* Case 3 above */
1406283aba9fSMel Gorman 			} else {
14077fadc820SHugh Dickins 				unlock_page(page);
1408c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
14097fadc820SHugh Dickins 				/* then go back and try same page again */
14107fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
14117fadc820SHugh Dickins 				continue;
1412e62e384eSMichal Hocko 			}
1413283aba9fSMel Gorman 		}
14141da177e4SLinus Torvalds 
14158940b34aSMinchan Kim 		if (!ignore_references)
14166a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
141702c6de8dSMinchan Kim 
1418dfc8d636SJohannes Weiner 		switch (references) {
1419dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
14201da177e4SLinus Torvalds 			goto activate_locked;
142164574746SJohannes Weiner 		case PAGEREF_KEEP:
142298879b3bSYang Shi 			stat->nr_ref_keep += nr_pages;
142364574746SJohannes Weiner 			goto keep_locked;
1424dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1425dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1426dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1427dfc8d636SJohannes Weiner 		}
14281da177e4SLinus Torvalds 
14291da177e4SLinus Torvalds 		/*
14301da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
14311da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1432802a3a92SShaohua Li 		 * Lazyfree page could be freed directly
14331da177e4SLinus Torvalds 		 */
1434bd4c82c2SHuang Ying 		if (PageAnon(page) && PageSwapBacked(page)) {
1435bd4c82c2SHuang Ying 			if (!PageSwapCache(page)) {
143663eb6b93SHugh Dickins 				if (!(sc->gfp_mask & __GFP_IO))
143763eb6b93SHugh Dickins 					goto keep_locked;
1438feb889fbSLinus Torvalds 				if (page_maybe_dma_pinned(page))
1439feb889fbSLinus Torvalds 					goto keep_locked;
1440747552b1SHuang Ying 				if (PageTransHuge(page)) {
1441b8f593cdSHuang Ying 					/* cannot split THP, skip it */
1442747552b1SHuang Ying 					if (!can_split_huge_page(page, NULL))
1443b8f593cdSHuang Ying 						goto activate_locked;
1444747552b1SHuang Ying 					/*
1445747552b1SHuang Ying 					 * Split pages without a PMD map right
1446747552b1SHuang Ying 					 * away. Chances are some or all of the
1447747552b1SHuang Ying 					 * tail pages can be freed without IO.
1448747552b1SHuang Ying 					 */
1449747552b1SHuang Ying 					if (!compound_mapcount(page) &&
1450bd4c82c2SHuang Ying 					    split_huge_page_to_list(page,
1451bd4c82c2SHuang Ying 								    page_list))
1452747552b1SHuang Ying 						goto activate_locked;
1453747552b1SHuang Ying 				}
14540f074658SMinchan Kim 				if (!add_to_swap(page)) {
14550f074658SMinchan Kim 					if (!PageTransHuge(page))
145698879b3bSYang Shi 						goto activate_locked_split;
1457bd4c82c2SHuang Ying 					/* Fallback to swap normal pages */
1458bd4c82c2SHuang Ying 					if (split_huge_page_to_list(page,
1459bd4c82c2SHuang Ying 								    page_list))
14600f074658SMinchan Kim 						goto activate_locked;
1461fe490cc0SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1462fe490cc0SHuang Ying 					count_vm_event(THP_SWPOUT_FALLBACK);
1463fe490cc0SHuang Ying #endif
14640f074658SMinchan Kim 					if (!add_to_swap(page))
146598879b3bSYang Shi 						goto activate_locked_split;
14660f074658SMinchan Kim 				}
14670f074658SMinchan Kim 
14684b793062SKirill Tkhai 				may_enter_fs = true;
14691da177e4SLinus Torvalds 
1470e2be15f6SMel Gorman 				/* Adding to swap updated mapping */
14711da177e4SLinus Torvalds 				mapping = page_mapping(page);
1472bd4c82c2SHuang Ying 			}
14737751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
14747751b2daSKirill A. Shutemov 			/* Split file THP */
14757751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
14767751b2daSKirill A. Shutemov 				goto keep_locked;
1477e2be15f6SMel Gorman 		}
14781da177e4SLinus Torvalds 
14791da177e4SLinus Torvalds 		/*
148098879b3bSYang Shi 		 * THP may get split above, need minus tail pages and update
148198879b3bSYang Shi 		 * nr_pages to avoid accounting tail pages twice.
148298879b3bSYang Shi 		 *
148398879b3bSYang Shi 		 * The tail pages that are added into swap cache successfully
148498879b3bSYang Shi 		 * reach here.
148598879b3bSYang Shi 		 */
148698879b3bSYang Shi 		if ((nr_pages > 1) && !PageTransHuge(page)) {
148798879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
148898879b3bSYang Shi 			nr_pages = 1;
148998879b3bSYang Shi 		}
149098879b3bSYang Shi 
149198879b3bSYang Shi 		/*
14921da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
14931da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
14941da177e4SLinus Torvalds 		 */
1495802a3a92SShaohua Li 		if (page_mapped(page)) {
1496013339dfSShakeel Butt 			enum ttu_flags flags = TTU_BATCH_FLUSH;
14971f318a9bSJaewon Kim 			bool was_swapbacked = PageSwapBacked(page);
1498bd4c82c2SHuang Ying 
1499bd4c82c2SHuang Ying 			if (unlikely(PageTransHuge(page)))
1500bd4c82c2SHuang Ying 				flags |= TTU_SPLIT_HUGE_PMD;
15011f318a9bSJaewon Kim 
1502bd4c82c2SHuang Ying 			if (!try_to_unmap(page, flags)) {
150398879b3bSYang Shi 				stat->nr_unmap_fail += nr_pages;
15041f318a9bSJaewon Kim 				if (!was_swapbacked && PageSwapBacked(page))
15051f318a9bSJaewon Kim 					stat->nr_lazyfree_fail += nr_pages;
15061da177e4SLinus Torvalds 				goto activate_locked;
15071da177e4SLinus Torvalds 			}
15081da177e4SLinus Torvalds 		}
15091da177e4SLinus Torvalds 
15101da177e4SLinus Torvalds 		if (PageDirty(page)) {
1511ee72886dSMel Gorman 			/*
15124eda4823SJohannes Weiner 			 * Only kswapd can writeback filesystem pages
15134eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
15144eda4823SJohannes Weiner 			 * injecting inefficient single-page IO into
15154eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
15164eda4823SJohannes Weiner 			 * write pages when we've encountered many
15174eda4823SJohannes Weiner 			 * dirty pages, and when we've already scanned
15184eda4823SJohannes Weiner 			 * the rest of the LRU for clean pages and see
15194eda4823SJohannes Weiner 			 * the same dirty pages again (PageReclaim).
1520ee72886dSMel Gorman 			 */
15219de4f22aSHuang Ying 			if (page_is_file_lru(page) &&
15224eda4823SJohannes Weiner 			    (!current_is_kswapd() || !PageReclaim(page) ||
1523599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
152449ea7eb6SMel Gorman 				/*
152549ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
152649ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
152749ea7eb6SMel Gorman 				 * except we already have the page isolated
152849ea7eb6SMel Gorman 				 * and know it's dirty
152949ea7eb6SMel Gorman 				 */
1530c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
153149ea7eb6SMel Gorman 				SetPageReclaim(page);
153249ea7eb6SMel Gorman 
1533c55e8d03SJohannes Weiner 				goto activate_locked;
1534ee72886dSMel Gorman 			}
1535ee72886dSMel Gorman 
1536dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
15371da177e4SLinus Torvalds 				goto keep_locked;
15384dd4b920SAndrew Morton 			if (!may_enter_fs)
15391da177e4SLinus Torvalds 				goto keep_locked;
154052a8363eSChristoph Lameter 			if (!sc->may_writepage)
15411da177e4SLinus Torvalds 				goto keep_locked;
15421da177e4SLinus Torvalds 
1543d950c947SMel Gorman 			/*
1544d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1545d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1546d950c947SMel Gorman 			 * starts and then write it out here.
1547d950c947SMel Gorman 			 */
1548d950c947SMel Gorman 			try_to_unmap_flush_dirty();
1549cb16556dSYang Shi 			switch (pageout(page, mapping)) {
15501da177e4SLinus Torvalds 			case PAGE_KEEP:
15511da177e4SLinus Torvalds 				goto keep_locked;
15521da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
15531da177e4SLinus Torvalds 				goto activate_locked;
15541da177e4SLinus Torvalds 			case PAGE_SUCCESS:
15556c357848SMatthew Wilcox (Oracle) 				stat->nr_pageout += thp_nr_pages(page);
155696f8bf4fSJohannes Weiner 
15577d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
155841ac1999SMel Gorman 					goto keep;
15597d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
15601da177e4SLinus Torvalds 					goto keep;
15617d3579e8SKOSAKI Motohiro 
15621da177e4SLinus Torvalds 				/*
15631da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
15641da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
15651da177e4SLinus Torvalds 				 */
1566529ae9aaSNick Piggin 				if (!trylock_page(page))
15671da177e4SLinus Torvalds 					goto keep;
15681da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
15691da177e4SLinus Torvalds 					goto keep_locked;
15701da177e4SLinus Torvalds 				mapping = page_mapping(page);
157101359eb2SGustavo A. R. Silva 				fallthrough;
15721da177e4SLinus Torvalds 			case PAGE_CLEAN:
15731da177e4SLinus Torvalds 				; /* try to free the page below */
15741da177e4SLinus Torvalds 			}
15751da177e4SLinus Torvalds 		}
15761da177e4SLinus Torvalds 
15771da177e4SLinus Torvalds 		/*
15781da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
15791da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
15801da177e4SLinus Torvalds 		 * the page as well.
15811da177e4SLinus Torvalds 		 *
15821da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
15831da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
15841da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
15851da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
15861da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
15871da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
15881da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
15891da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
15901da177e4SLinus Torvalds 		 *
15911da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
15921da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
1593d12b8951SYang Shi 		 * truncate_cleanup_page().  We try to drop those buffers here
15941da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
15951da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
15961da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
15971da177e4SLinus Torvalds 		 */
1598266cf658SDavid Howells 		if (page_has_private(page)) {
15991da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
16001da177e4SLinus Torvalds 				goto activate_locked;
1601e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1602e286781dSNick Piggin 				unlock_page(page);
1603e286781dSNick Piggin 				if (put_page_testzero(page))
16041da177e4SLinus Torvalds 					goto free_it;
1605e286781dSNick Piggin 				else {
1606e286781dSNick Piggin 					/*
1607e286781dSNick Piggin 					 * rare race with speculative reference.
1608e286781dSNick Piggin 					 * the speculative reference will free
1609e286781dSNick Piggin 					 * this page shortly, so we may
1610e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1611e286781dSNick Piggin 					 * leave it off the LRU).
1612e286781dSNick Piggin 					 */
1613e286781dSNick Piggin 					nr_reclaimed++;
1614e286781dSNick Piggin 					continue;
1615e286781dSNick Piggin 				}
1616e286781dSNick Piggin 			}
16171da177e4SLinus Torvalds 		}
16181da177e4SLinus Torvalds 
1619802a3a92SShaohua Li 		if (PageAnon(page) && !PageSwapBacked(page)) {
1620802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
1621802a3a92SShaohua Li 			if (!page_ref_freeze(page, 1))
162249d2e9ccSChristoph Lameter 				goto keep_locked;
1623802a3a92SShaohua Li 			if (PageDirty(page)) {
1624802a3a92SShaohua Li 				page_ref_unfreeze(page, 1);
1625802a3a92SShaohua Li 				goto keep_locked;
1626802a3a92SShaohua Li 			}
16271da177e4SLinus Torvalds 
1628802a3a92SShaohua Li 			count_vm_event(PGLAZYFREED);
16292262185cSRoman Gushchin 			count_memcg_page_event(page, PGLAZYFREED);
1630b910718aSJohannes Weiner 		} else if (!mapping || !__remove_mapping(mapping, page, true,
1631b910718aSJohannes Weiner 							 sc->target_mem_cgroup))
1632802a3a92SShaohua Li 			goto keep_locked;
16339a1ea439SHugh Dickins 
16349a1ea439SHugh Dickins 		unlock_page(page);
1635e286781dSNick Piggin free_it:
163698879b3bSYang Shi 		/*
163798879b3bSYang Shi 		 * THP may get swapped out in a whole, need account
163898879b3bSYang Shi 		 * all base pages.
163998879b3bSYang Shi 		 */
164098879b3bSYang Shi 		nr_reclaimed += nr_pages;
1641abe4c3b5SMel Gorman 
1642abe4c3b5SMel Gorman 		/*
1643abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1644abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1645abe4c3b5SMel Gorman 		 */
16467ae88534SYang Shi 		if (unlikely(PageTransHuge(page)))
1647ff45fc3cSMatthew Wilcox (Oracle) 			destroy_compound_page(page);
16487ae88534SYang Shi 		else
1649abe4c3b5SMel Gorman 			list_add(&page->lru, &free_pages);
16501da177e4SLinus Torvalds 		continue;
16511da177e4SLinus Torvalds 
165298879b3bSYang Shi activate_locked_split:
165398879b3bSYang Shi 		/*
165498879b3bSYang Shi 		 * The tail pages that are failed to add into swap cache
165598879b3bSYang Shi 		 * reach here.  Fixup nr_scanned and nr_pages.
165698879b3bSYang Shi 		 */
165798879b3bSYang Shi 		if (nr_pages > 1) {
165898879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
165998879b3bSYang Shi 			nr_pages = 1;
166098879b3bSYang Shi 		}
16611da177e4SLinus Torvalds activate_locked:
166268a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
1663ad6b6704SMinchan Kim 		if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1664ad6b6704SMinchan Kim 						PageMlocked(page)))
1665a2c43eedSHugh Dickins 			try_to_free_swap(page);
1666309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
1667ad6b6704SMinchan Kim 		if (!PageMlocked(page)) {
16689de4f22aSHuang Ying 			int type = page_is_file_lru(page);
16691da177e4SLinus Torvalds 			SetPageActive(page);
167098879b3bSYang Shi 			stat->nr_activate[type] += nr_pages;
16712262185cSRoman Gushchin 			count_memcg_page_event(page, PGACTIVATE);
1672ad6b6704SMinchan Kim 		}
16731da177e4SLinus Torvalds keep_locked:
16741da177e4SLinus Torvalds 		unlock_page(page);
16751da177e4SLinus Torvalds keep:
16761da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1677309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
16781da177e4SLinus Torvalds 	}
1679abe4c3b5SMel Gorman 
168098879b3bSYang Shi 	pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
168198879b3bSYang Shi 
1682747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
168372b252aeSMel Gorman 	try_to_unmap_flush();
16842d4894b5SMel Gorman 	free_unref_page_list(&free_pages);
1685abe4c3b5SMel Gorman 
16861da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1687886cf190SKirill Tkhai 	count_vm_events(PGACTIVATE, pgactivate);
16880a31bc97SJohannes Weiner 
168905ff5137SAndrew Morton 	return nr_reclaimed;
16901da177e4SLinus Torvalds }
16911da177e4SLinus Torvalds 
1692730ec8c0SManinder Singh unsigned int reclaim_clean_pages_from_list(struct zone *zone,
169302c6de8dSMinchan Kim 					    struct list_head *page_list)
169402c6de8dSMinchan Kim {
169502c6de8dSMinchan Kim 	struct scan_control sc = {
169602c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
169702c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
169802c6de8dSMinchan Kim 		.may_unmap = 1,
169902c6de8dSMinchan Kim 	};
17001f318a9bSJaewon Kim 	struct reclaim_stat stat;
1701730ec8c0SManinder Singh 	unsigned int nr_reclaimed;
170202c6de8dSMinchan Kim 	struct page *page, *next;
170302c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
1704*2d2b8d2bSYu Zhao 	unsigned int noreclaim_flag;
170502c6de8dSMinchan Kim 
170602c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1707ae37c7ffSOscar Salvador 		if (!PageHuge(page) && page_is_file_lru(page) &&
1708ae37c7ffSOscar Salvador 		    !PageDirty(page) && !__PageMovable(page) &&
1709ae37c7ffSOscar Salvador 		    !PageUnevictable(page)) {
171002c6de8dSMinchan Kim 			ClearPageActive(page);
171102c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
171202c6de8dSMinchan Kim 		}
171302c6de8dSMinchan Kim 	}
171402c6de8dSMinchan Kim 
1715*2d2b8d2bSYu Zhao 	/*
1716*2d2b8d2bSYu Zhao 	 * We should be safe here since we are only dealing with file pages and
1717*2d2b8d2bSYu Zhao 	 * we are not kswapd and therefore cannot write dirty file pages. But
1718*2d2b8d2bSYu Zhao 	 * call memalloc_noreclaim_save() anyway, just in case these conditions
1719*2d2b8d2bSYu Zhao 	 * change in the future.
1720*2d2b8d2bSYu Zhao 	 */
1721*2d2b8d2bSYu Zhao 	noreclaim_flag = memalloc_noreclaim_save();
17221f318a9bSJaewon Kim 	nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1723013339dfSShakeel Butt 					&stat, true);
1724*2d2b8d2bSYu Zhao 	memalloc_noreclaim_restore(noreclaim_flag);
1725*2d2b8d2bSYu Zhao 
172602c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
17272da9f630SNicholas Piggin 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
17282da9f630SNicholas Piggin 			    -(long)nr_reclaimed);
17291f318a9bSJaewon Kim 	/*
17301f318a9bSJaewon Kim 	 * Since lazyfree pages are isolated from file LRU from the beginning,
17311f318a9bSJaewon Kim 	 * they will rotate back to anonymous LRU in the end if it failed to
17321f318a9bSJaewon Kim 	 * discard so isolated count will be mismatched.
17331f318a9bSJaewon Kim 	 * Compensate the isolated count for both LRU lists.
17341f318a9bSJaewon Kim 	 */
17351f318a9bSJaewon Kim 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
17361f318a9bSJaewon Kim 			    stat.nr_lazyfree_fail);
17371f318a9bSJaewon Kim 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
17382da9f630SNicholas Piggin 			    -(long)stat.nr_lazyfree_fail);
17391f318a9bSJaewon Kim 	return nr_reclaimed;
174002c6de8dSMinchan Kim }
174102c6de8dSMinchan Kim 
17425ad333ebSAndy Whitcroft /*
17435ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
17445ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
17455ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
17465ad333ebSAndy Whitcroft  *
17475ad333ebSAndy Whitcroft  * page:	page to consider
17485ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
17495ad333ebSAndy Whitcroft  *
1750c2135f7cSAlex Shi  * returns true on success, false on failure.
17515ad333ebSAndy Whitcroft  */
1752c2135f7cSAlex Shi bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
17535ad333ebSAndy Whitcroft {
17545ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
17555ad333ebSAndy Whitcroft 	if (!PageLRU(page))
1756c2135f7cSAlex Shi 		return false;
17575ad333ebSAndy Whitcroft 
1758e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1759e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1760c2135f7cSAlex Shi 		return false;
1761894bc310SLee Schermerhorn 
1762c8244935SMel Gorman 	/*
1763c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1764c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1765c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1766c8244935SMel Gorman 	 *
1767c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1768c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1769c8244935SMel Gorman 	 */
17701276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1771c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1772c8244935SMel Gorman 		if (PageWriteback(page))
1773c2135f7cSAlex Shi 			return false;
177439deaf85SMinchan Kim 
1775c8244935SMel Gorman 		if (PageDirty(page)) {
1776c8244935SMel Gorman 			struct address_space *mapping;
177769d763fcSMel Gorman 			bool migrate_dirty;
1778c8244935SMel Gorman 
1779c8244935SMel Gorman 			/*
1780c8244935SMel Gorman 			 * Only pages without mappings or that have a
1781c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
178269d763fcSMel Gorman 			 * without blocking. However, we can be racing with
178369d763fcSMel Gorman 			 * truncation so it's necessary to lock the page
178469d763fcSMel Gorman 			 * to stabilise the mapping as truncation holds
178569d763fcSMel Gorman 			 * the page lock until after the page is removed
178669d763fcSMel Gorman 			 * from the page cache.
1787c8244935SMel Gorman 			 */
178869d763fcSMel Gorman 			if (!trylock_page(page))
1789c2135f7cSAlex Shi 				return false;
179069d763fcSMel Gorman 
1791c8244935SMel Gorman 			mapping = page_mapping(page);
1792145e1a71SHugh Dickins 			migrate_dirty = !mapping || mapping->a_ops->migratepage;
179369d763fcSMel Gorman 			unlock_page(page);
179469d763fcSMel Gorman 			if (!migrate_dirty)
1795c2135f7cSAlex Shi 				return false;
1796c8244935SMel Gorman 		}
1797c8244935SMel Gorman 	}
1798c8244935SMel Gorman 
1799f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1800c2135f7cSAlex Shi 		return false;
1801f80c0673SMinchan Kim 
1802c2135f7cSAlex Shi 	return true;
18035ad333ebSAndy Whitcroft }
18045ad333ebSAndy Whitcroft 
18057ee36a14SMel Gorman /*
18067ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
180755b65a57SEthon Paul  * be complete before mem_cgroup_update_lru_size due to a sanity check.
18087ee36a14SMel Gorman  */
18097ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1810b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
18117ee36a14SMel Gorman {
18127ee36a14SMel Gorman 	int zid;
18137ee36a14SMel Gorman 
18147ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
18157ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
18167ee36a14SMel Gorman 			continue;
18177ee36a14SMel Gorman 
1818a892cb6bSWei Yang 		update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
18197ee36a14SMel Gorman 	}
18207ee36a14SMel Gorman 
18217ee36a14SMel Gorman }
18227ee36a14SMel Gorman 
1823f4b7e272SAndrey Ryabinin /**
182415b44736SHugh Dickins  * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
182515b44736SHugh Dickins  *
182615b44736SHugh Dickins  * lruvec->lru_lock is heavily contended.  Some of the functions that
18271da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
18281da177e4SLinus Torvalds  * and working on them outside the LRU lock.
18291da177e4SLinus Torvalds  *
18301da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
18311da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
18321da177e4SLinus Torvalds  *
183315b44736SHugh Dickins  * Lru_lock must be held before calling this function.
18341da177e4SLinus Torvalds  *
1835791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
18365dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
18371da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1838f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1839fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
18403cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
18411da177e4SLinus Torvalds  *
18421da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
18431da177e4SLinus Torvalds  */
184469e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
18455dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1846fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
1847a9e7c39fSKirill Tkhai 		enum lru_list lru)
18481da177e4SLinus Torvalds {
184975b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
185069e05944SAndrew Morton 	unsigned long nr_taken = 0;
1851599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
18527cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
18533db65812SJohannes Weiner 	unsigned long skipped = 0;
1854791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
1855b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
1856a9e7c39fSKirill Tkhai 	isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
18571da177e4SLinus Torvalds 
185898879b3bSYang Shi 	total_scan = 0;
1859791b48b6SMinchan Kim 	scan = 0;
186098879b3bSYang Shi 	while (scan < nr_to_scan && !list_empty(src)) {
18615ad333ebSAndy Whitcroft 		struct page *page;
18625ad333ebSAndy Whitcroft 
18631da177e4SLinus Torvalds 		page = lru_to_page(src);
18641da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
18651da177e4SLinus Torvalds 
1866d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
186798879b3bSYang Shi 		total_scan += nr_pages;
186898879b3bSYang Shi 
1869b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1870b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
187198879b3bSYang Shi 			nr_skipped[page_zonenum(page)] += nr_pages;
1872b2e18757SMel Gorman 			continue;
1873b2e18757SMel Gorman 		}
1874b2e18757SMel Gorman 
1875791b48b6SMinchan Kim 		/*
1876791b48b6SMinchan Kim 		 * Do not count skipped pages because that makes the function
1877791b48b6SMinchan Kim 		 * return with no isolated pages if the LRU mostly contains
1878791b48b6SMinchan Kim 		 * ineligible pages.  This causes the VM to not reclaim any
1879791b48b6SMinchan Kim 		 * pages, triggering a premature OOM.
188098879b3bSYang Shi 		 *
188198879b3bSYang Shi 		 * Account all tail pages of THP.  This would not cause
188298879b3bSYang Shi 		 * premature OOM since __isolate_lru_page() returns -EBUSY
188398879b3bSYang Shi 		 * only when the page is being freed somewhere else.
1884791b48b6SMinchan Kim 		 */
188598879b3bSYang Shi 		scan += nr_pages;
1886c2135f7cSAlex Shi 		if (!__isolate_lru_page_prepare(page, mode)) {
1887c2135f7cSAlex Shi 			/* It is being freed elsewhere */
1888c2135f7cSAlex Shi 			list_move(&page->lru, src);
1889c2135f7cSAlex Shi 			continue;
1890c2135f7cSAlex Shi 		}
18919df41314SAlex Shi 		/*
18929df41314SAlex Shi 		 * Be careful not to clear PageLRU until after we're
18939df41314SAlex Shi 		 * sure the page is not being freed elsewhere -- the
18949df41314SAlex Shi 		 * page release code relies on it.
18959df41314SAlex Shi 		 */
1896c2135f7cSAlex Shi 		if (unlikely(!get_page_unless_zero(page))) {
1897c2135f7cSAlex Shi 			list_move(&page->lru, src);
1898c2135f7cSAlex Shi 			continue;
1899c2135f7cSAlex Shi 		}
19009df41314SAlex Shi 
19019df41314SAlex Shi 		if (!TestClearPageLRU(page)) {
1902c2135f7cSAlex Shi 			/* Another thread is already isolating this page */
19039df41314SAlex Shi 			put_page(page);
1904c2135f7cSAlex Shi 			list_move(&page->lru, src);
1905c2135f7cSAlex Shi 			continue;
19069df41314SAlex Shi 		}
19079df41314SAlex Shi 
1908599d0c95SMel Gorman 		nr_taken += nr_pages;
1909599d0c95SMel Gorman 		nr_zone_taken[page_zonenum(page)] += nr_pages;
19105ad333ebSAndy Whitcroft 		list_move(&page->lru, dst);
19115ad333ebSAndy Whitcroft 	}
19121da177e4SLinus Torvalds 
1913b2e18757SMel Gorman 	/*
1914b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1915b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1916b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1917b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1918b2e18757SMel Gorman 	 * system at risk of premature OOM.
1919b2e18757SMel Gorman 	 */
19207cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
19217cc30fcfSMel Gorman 		int zid;
19227cc30fcfSMel Gorman 
19233db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
19247cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
19257cc30fcfSMel Gorman 			if (!nr_skipped[zid])
19267cc30fcfSMel Gorman 				continue;
19277cc30fcfSMel Gorman 
19287cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
19291265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
19307cc30fcfSMel Gorman 		}
19317cc30fcfSMel Gorman 	}
1932791b48b6SMinchan Kim 	*nr_scanned = total_scan;
19331265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1934791b48b6SMinchan Kim 				    total_scan, skipped, nr_taken, mode, lru);
1935b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
19361da177e4SLinus Torvalds 	return nr_taken;
19371da177e4SLinus Torvalds }
19381da177e4SLinus Torvalds 
193962695a84SNick Piggin /**
194062695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
194162695a84SNick Piggin  * @page: page to isolate from its LRU list
194262695a84SNick Piggin  *
194362695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
194462695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
194562695a84SNick Piggin  *
194662695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
194762695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
194862695a84SNick Piggin  *
194962695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1950894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1951894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1952894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
195362695a84SNick Piggin  *
195462695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
195562695a84SNick Piggin  * found will be decremented.
195662695a84SNick Piggin  *
195762695a84SNick Piggin  * Restrictions:
1958a5d09bedSMike Rapoport  *
195962695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
196001c4776bSHui Su  *     fundamental difference from isolate_lru_pages (which is called
196162695a84SNick Piggin  *     without a stable reference).
196262695a84SNick Piggin  * (2) the lru_lock must not be held.
196362695a84SNick Piggin  * (3) interrupts must be enabled.
196462695a84SNick Piggin  */
196562695a84SNick Piggin int isolate_lru_page(struct page *page)
196662695a84SNick Piggin {
196762695a84SNick Piggin 	int ret = -EBUSY;
196862695a84SNick Piggin 
1969309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1970cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
19710c917313SKonstantin Khlebnikov 
1972d25b5bd8SAlex Shi 	if (TestClearPageLRU(page)) {
1973fa9add64SHugh Dickins 		struct lruvec *lruvec;
197462695a84SNick Piggin 
19750c917313SKonstantin Khlebnikov 		get_page(page);
19766168d0daSAlex Shi 		lruvec = lock_page_lruvec_irq(page);
197746ae6b2cSYu Zhao 		del_page_from_lru_list(page, lruvec);
19786168d0daSAlex Shi 		unlock_page_lruvec_irq(lruvec);
1979fa9add64SHugh Dickins 		ret = 0;
198062695a84SNick Piggin 	}
1981d25b5bd8SAlex Shi 
198262695a84SNick Piggin 	return ret;
198362695a84SNick Piggin }
198462695a84SNick Piggin 
19855ad333ebSAndy Whitcroft /*
1986d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1987178821b8SXianting Tian  * then get rescheduled. When there are massive number of tasks doing page
1988d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1989d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1990d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
199135cd7815SRik van Riel  */
1992599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
199335cd7815SRik van Riel 		struct scan_control *sc)
199435cd7815SRik van Riel {
199535cd7815SRik van Riel 	unsigned long inactive, isolated;
199635cd7815SRik van Riel 
199735cd7815SRik van Riel 	if (current_is_kswapd())
199835cd7815SRik van Riel 		return 0;
199935cd7815SRik van Riel 
2000b5ead35eSJohannes Weiner 	if (!writeback_throttling_sane(sc))
200135cd7815SRik van Riel 		return 0;
200235cd7815SRik van Riel 
200335cd7815SRik van Riel 	if (file) {
2004599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2005599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
200635cd7815SRik van Riel 	} else {
2007599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2008599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
200935cd7815SRik van Riel 	}
201035cd7815SRik van Riel 
20113cf23841SFengguang Wu 	/*
20123cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
20133cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
20143cf23841SFengguang Wu 	 * deadlock.
20153cf23841SFengguang Wu 	 */
2016d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
20173cf23841SFengguang Wu 		inactive >>= 3;
20183cf23841SFengguang Wu 
201935cd7815SRik van Riel 	return isolated > inactive;
202035cd7815SRik van Riel }
202135cd7815SRik van Riel 
2022a222f341SKirill Tkhai /*
202315b44736SHugh Dickins  * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
202415b44736SHugh Dickins  * On return, @list is reused as a list of pages to be freed by the caller.
2025a222f341SKirill Tkhai  *
2026a222f341SKirill Tkhai  * Returns the number of pages moved to the given lruvec.
2027a222f341SKirill Tkhai  */
20289ef56b78SMuchun Song static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2029a222f341SKirill Tkhai 				      struct list_head *list)
203066635629SMel Gorman {
2031a222f341SKirill Tkhai 	int nr_pages, nr_moved = 0;
20323f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
2033a222f341SKirill Tkhai 	struct page *page;
203466635629SMel Gorman 
2035a222f341SKirill Tkhai 	while (!list_empty(list)) {
2036a222f341SKirill Tkhai 		page = lru_to_page(list);
2037309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
2038a222f341SKirill Tkhai 		list_del(&page->lru);
20393d06afabSAlex Shi 		if (unlikely(!page_evictable(page))) {
20406168d0daSAlex Shi 			spin_unlock_irq(&lruvec->lru_lock);
204166635629SMel Gorman 			putback_lru_page(page);
20426168d0daSAlex Shi 			spin_lock_irq(&lruvec->lru_lock);
204366635629SMel Gorman 			continue;
204466635629SMel Gorman 		}
2045fa9add64SHugh Dickins 
20463d06afabSAlex Shi 		/*
20473d06afabSAlex Shi 		 * The SetPageLRU needs to be kept here for list integrity.
20483d06afabSAlex Shi 		 * Otherwise:
20493d06afabSAlex Shi 		 *   #0 move_pages_to_lru             #1 release_pages
20503d06afabSAlex Shi 		 *   if !put_page_testzero
20513d06afabSAlex Shi 		 *				      if (put_page_testzero())
20523d06afabSAlex Shi 		 *				        !PageLRU //skip lru_lock
20533d06afabSAlex Shi 		 *     SetPageLRU()
20543d06afabSAlex Shi 		 *     list_add(&page->lru,)
20553d06afabSAlex Shi 		 *                                        list_add(&page->lru,)
20563d06afabSAlex Shi 		 */
20577a608572SLinus Torvalds 		SetPageLRU(page);
2058a222f341SKirill Tkhai 
20593d06afabSAlex Shi 		if (unlikely(put_page_testzero(page))) {
206087560179SYu Zhao 			__clear_page_lru_flags(page);
20612bcf8879SHugh Dickins 
20622bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
20636168d0daSAlex Shi 				spin_unlock_irq(&lruvec->lru_lock);
2064ff45fc3cSMatthew Wilcox (Oracle) 				destroy_compound_page(page);
20656168d0daSAlex Shi 				spin_lock_irq(&lruvec->lru_lock);
20662bcf8879SHugh Dickins 			} else
20672bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
20683d06afabSAlex Shi 
20693d06afabSAlex Shi 			continue;
20703d06afabSAlex Shi 		}
20713d06afabSAlex Shi 
2072afca9157SAlex Shi 		/*
2073afca9157SAlex Shi 		 * All pages were isolated from the same lruvec (and isolation
2074afca9157SAlex Shi 		 * inhibits memcg migration).
2075afca9157SAlex Shi 		 */
20767467c391SMuchun Song 		VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
20773a9c9788SYu Zhao 		add_page_to_lru_list(page, lruvec);
20783d06afabSAlex Shi 		nr_pages = thp_nr_pages(page);
2079a222f341SKirill Tkhai 		nr_moved += nr_pages;
208031d8fcacSJohannes Weiner 		if (PageActive(page))
208131d8fcacSJohannes Weiner 			workingset_age_nonresident(lruvec, nr_pages);
208266635629SMel Gorman 	}
208366635629SMel Gorman 
20843f79768fSHugh Dickins 	/*
20853f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
20863f79768fSHugh Dickins 	 */
2087a222f341SKirill Tkhai 	list_splice(&pages_to_free, list);
2088a222f341SKirill Tkhai 
2089a222f341SKirill Tkhai 	return nr_moved;
209066635629SMel Gorman }
209166635629SMel Gorman 
209266635629SMel Gorman /*
2093399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
2094a37b0715SNeilBrown  * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
2095399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
2096399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
2097399ba0b9SNeilBrown  */
2098399ba0b9SNeilBrown static int current_may_throttle(void)
2099399ba0b9SNeilBrown {
2100a37b0715SNeilBrown 	return !(current->flags & PF_LOCAL_THROTTLE) ||
2101399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
2102399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
2103399ba0b9SNeilBrown }
2104399ba0b9SNeilBrown 
2105399ba0b9SNeilBrown /*
2106b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
21071742f19fSAndrew Morton  * of reclaimed pages
21081da177e4SLinus Torvalds  */
21099ef56b78SMuchun Song static unsigned long
21101a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
21119e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
21121da177e4SLinus Torvalds {
21131da177e4SLinus Torvalds 	LIST_HEAD(page_list);
2114e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
2115730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
2116e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
2117060f005fSKirill Tkhai 	struct reclaim_stat stat;
2118497a6c1bSJohannes Weiner 	bool file = is_file_lru(lru);
2119f46b7912SKirill Tkhai 	enum vm_event_item item;
2120599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2121db73ee0dSMichal Hocko 	bool stalled = false;
212278dc583dSKOSAKI Motohiro 
2123599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
2124db73ee0dSMichal Hocko 		if (stalled)
2125db73ee0dSMichal Hocko 			return 0;
2126db73ee0dSMichal Hocko 
2127db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
2128db73ee0dSMichal Hocko 		msleep(100);
2129db73ee0dSMichal Hocko 		stalled = true;
213035cd7815SRik van Riel 
213135cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
213235cd7815SRik van Riel 		if (fatal_signal_pending(current))
213335cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
213435cd7815SRik van Riel 	}
213535cd7815SRik van Riel 
21361da177e4SLinus Torvalds 	lru_add_drain();
2137f80c0673SMinchan Kim 
21386168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
21391da177e4SLinus Torvalds 
21405dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
2141a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
214295d918fcSKonstantin Khlebnikov 
2143599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2144f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
2145b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
2146f46b7912SKirill Tkhai 		__count_vm_events(item, nr_scanned);
2147f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
2148497a6c1bSJohannes Weiner 	__count_vm_events(PGSCAN_ANON + file, nr_scanned);
2149497a6c1bSJohannes Weiner 
21506168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
2151d563c050SHillf Danton 
2152d563c050SHillf Danton 	if (nr_taken == 0)
215366635629SMel Gorman 		return 0;
2154b35ea17bSKOSAKI Motohiro 
2155013339dfSShakeel Butt 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
2156c661b078SAndy Whitcroft 
21576168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2158497a6c1bSJohannes Weiner 	move_pages_to_lru(lruvec, &page_list);
2159497a6c1bSJohannes Weiner 
2160497a6c1bSJohannes Weiner 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2161f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
2162b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
2163f46b7912SKirill Tkhai 		__count_vm_events(item, nr_reclaimed);
2164f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
2165497a6c1bSJohannes Weiner 	__count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
21666168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
21673f79768fSHugh Dickins 
216875cc3c91SAlex Shi 	lru_note_cost(lruvec, file, stat.nr_pageout);
2169747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
21702d4894b5SMel Gorman 	free_unref_page_list(&page_list);
2171e11da5b4SMel Gorman 
217292df3a72SMel Gorman 	/*
21731c610d5fSAndrey Ryabinin 	 * If dirty pages are scanned that are not queued for IO, it
21741c610d5fSAndrey Ryabinin 	 * implies that flushers are not doing their job. This can
21751c610d5fSAndrey Ryabinin 	 * happen when memory pressure pushes dirty pages to the end of
21761c610d5fSAndrey Ryabinin 	 * the LRU before the dirty limits are breached and the dirty
21771c610d5fSAndrey Ryabinin 	 * data has expired. It can also happen when the proportion of
21781c610d5fSAndrey Ryabinin 	 * dirty pages grows not through writes but through memory
21791c610d5fSAndrey Ryabinin 	 * pressure reclaiming all the clean cache. And in some cases,
21801c610d5fSAndrey Ryabinin 	 * the flushers simply cannot keep up with the allocation
21811c610d5fSAndrey Ryabinin 	 * rate. Nudge the flusher threads in case they are asleep.
21821c610d5fSAndrey Ryabinin 	 */
21831c610d5fSAndrey Ryabinin 	if (stat.nr_unqueued_dirty == nr_taken)
21841c610d5fSAndrey Ryabinin 		wakeup_flusher_threads(WB_REASON_VMSCAN);
21851c610d5fSAndrey Ryabinin 
2186d108c772SAndrey Ryabinin 	sc->nr.dirty += stat.nr_dirty;
2187d108c772SAndrey Ryabinin 	sc->nr.congested += stat.nr_congested;
2188d108c772SAndrey Ryabinin 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2189d108c772SAndrey Ryabinin 	sc->nr.writeback += stat.nr_writeback;
2190d108c772SAndrey Ryabinin 	sc->nr.immediate += stat.nr_immediate;
2191d108c772SAndrey Ryabinin 	sc->nr.taken += nr_taken;
2192d108c772SAndrey Ryabinin 	if (file)
2193d108c772SAndrey Ryabinin 		sc->nr.file_taken += nr_taken;
21948e950282SMel Gorman 
2195599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2196d51d1e64SSteven Rostedt 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
219705ff5137SAndrew Morton 	return nr_reclaimed;
21981da177e4SLinus Torvalds }
21991da177e4SLinus Torvalds 
220015b44736SHugh Dickins /*
220115b44736SHugh Dickins  * shrink_active_list() moves pages from the active LRU to the inactive LRU.
220215b44736SHugh Dickins  *
220315b44736SHugh Dickins  * We move them the other way if the page is referenced by one or more
220415b44736SHugh Dickins  * processes.
220515b44736SHugh Dickins  *
220615b44736SHugh Dickins  * If the pages are mostly unmapped, the processing is fast and it is
220715b44736SHugh Dickins  * appropriate to hold lru_lock across the whole operation.  But if
220815b44736SHugh Dickins  * the pages are mapped, the processing is slow (page_referenced()), so
220915b44736SHugh Dickins  * we should drop lru_lock around each page.  It's impossible to balance
221015b44736SHugh Dickins  * this, so instead we remove the pages from the LRU while processing them.
221115b44736SHugh Dickins  * It is safe to rely on PG_active against the non-LRU pages in here because
221215b44736SHugh Dickins  * nobody will play with that bit on a non-LRU page.
221315b44736SHugh Dickins  *
221415b44736SHugh Dickins  * The downside is that we have to touch page->_refcount against each page.
221515b44736SHugh Dickins  * But we had to alter page->flags anyway.
221615b44736SHugh Dickins  */
2217f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
22181a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
2219f16015fbSJohannes Weiner 			       struct scan_control *sc,
22209e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
22211cfb419bSKAMEZAWA Hiroyuki {
222244c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
2223f626012dSHugh Dickins 	unsigned long nr_scanned;
22246fe6b7e3SWu Fengguang 	unsigned long vm_flags;
22251cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
22268cab4754SWu Fengguang 	LIST_HEAD(l_active);
2227b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
22281cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
22299d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
22309d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
22313cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
2232599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
22331cfb419bSKAMEZAWA Hiroyuki 
22341da177e4SLinus Torvalds 	lru_add_drain();
2235f80c0673SMinchan Kim 
22366168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2237925b7673SJohannes Weiner 
22385dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2239a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
224089b5fae5SJohannes Weiner 
2241599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
22421cfb419bSKAMEZAWA Hiroyuki 
2243912c0572SShakeel Butt 	if (!cgroup_reclaim(sc))
2244599d0c95SMel Gorman 		__count_vm_events(PGREFILL, nr_scanned);
22452fa2690cSYafang Shao 	__count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
22469d5e6a9fSHugh Dickins 
22476168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
22481da177e4SLinus Torvalds 
22491da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
22501da177e4SLinus Torvalds 		cond_resched();
22511da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
22521da177e4SLinus Torvalds 		list_del(&page->lru);
22537e9cd484SRik van Riel 
225439b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
2255894bc310SLee Schermerhorn 			putback_lru_page(page);
2256894bc310SLee Schermerhorn 			continue;
2257894bc310SLee Schermerhorn 		}
2258894bc310SLee Schermerhorn 
2259cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
2260cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
2261cc715d99SMel Gorman 				if (page_has_private(page))
2262cc715d99SMel Gorman 					try_to_release_page(page, 0);
2263cc715d99SMel Gorman 				unlock_page(page);
2264cc715d99SMel Gorman 			}
2265cc715d99SMel Gorman 		}
2266cc715d99SMel Gorman 
2267c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
2268c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
22698cab4754SWu Fengguang 			/*
22708cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
22718cab4754SWu Fengguang 			 * give them one more trip around the active list. So
22728cab4754SWu Fengguang 			 * that executable code get better chances to stay in
22738cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
22748cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
22758cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
22768cab4754SWu Fengguang 			 * so we ignore them here.
22778cab4754SWu Fengguang 			 */
22789de4f22aSHuang Ying 			if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
22796c357848SMatthew Wilcox (Oracle) 				nr_rotated += thp_nr_pages(page);
22808cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
22818cab4754SWu Fengguang 				continue;
22828cab4754SWu Fengguang 			}
22838cab4754SWu Fengguang 		}
22847e9cd484SRik van Riel 
22855205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
22861899ad18SJohannes Weiner 		SetPageWorkingset(page);
22871da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
22881da177e4SLinus Torvalds 	}
22891da177e4SLinus Torvalds 
2290b555749aSAndrew Morton 	/*
22918cab4754SWu Fengguang 	 * Move pages back to the lru list.
2292b555749aSAndrew Morton 	 */
22936168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2294556adecbSRik van Riel 
2295a222f341SKirill Tkhai 	nr_activate = move_pages_to_lru(lruvec, &l_active);
2296a222f341SKirill Tkhai 	nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2297f372d89eSKirill Tkhai 	/* Keep all free pages in l_active list */
2298f372d89eSKirill Tkhai 	list_splice(&l_inactive, &l_active);
22999851ac13SKirill Tkhai 
23009851ac13SKirill Tkhai 	__count_vm_events(PGDEACTIVATE, nr_deactivate);
23019851ac13SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
23029851ac13SKirill Tkhai 
2303599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
23046168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
23052bcf8879SHugh Dickins 
2306f372d89eSKirill Tkhai 	mem_cgroup_uncharge_list(&l_active);
2307f372d89eSKirill Tkhai 	free_unref_page_list(&l_active);
23089d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
23099d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
23101da177e4SLinus Torvalds }
23111da177e4SLinus Torvalds 
23121a4e58ccSMinchan Kim unsigned long reclaim_pages(struct list_head *page_list)
23131a4e58ccSMinchan Kim {
2314f661d007SYang Shi 	int nid = NUMA_NO_NODE;
2315730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
23161a4e58ccSMinchan Kim 	LIST_HEAD(node_page_list);
23171a4e58ccSMinchan Kim 	struct reclaim_stat dummy_stat;
23181a4e58ccSMinchan Kim 	struct page *page;
2319*2d2b8d2bSYu Zhao 	unsigned int noreclaim_flag;
23201a4e58ccSMinchan Kim 	struct scan_control sc = {
23211a4e58ccSMinchan Kim 		.gfp_mask = GFP_KERNEL,
23221a4e58ccSMinchan Kim 		.priority = DEF_PRIORITY,
23231a4e58ccSMinchan Kim 		.may_writepage = 1,
23241a4e58ccSMinchan Kim 		.may_unmap = 1,
23251a4e58ccSMinchan Kim 		.may_swap = 1,
23261a4e58ccSMinchan Kim 	};
23271a4e58ccSMinchan Kim 
2328*2d2b8d2bSYu Zhao 	noreclaim_flag = memalloc_noreclaim_save();
2329*2d2b8d2bSYu Zhao 
23301a4e58ccSMinchan Kim 	while (!list_empty(page_list)) {
23311a4e58ccSMinchan Kim 		page = lru_to_page(page_list);
2332f661d007SYang Shi 		if (nid == NUMA_NO_NODE) {
23331a4e58ccSMinchan Kim 			nid = page_to_nid(page);
23341a4e58ccSMinchan Kim 			INIT_LIST_HEAD(&node_page_list);
23351a4e58ccSMinchan Kim 		}
23361a4e58ccSMinchan Kim 
23371a4e58ccSMinchan Kim 		if (nid == page_to_nid(page)) {
23381a4e58ccSMinchan Kim 			ClearPageActive(page);
23391a4e58ccSMinchan Kim 			list_move(&page->lru, &node_page_list);
23401a4e58ccSMinchan Kim 			continue;
23411a4e58ccSMinchan Kim 		}
23421a4e58ccSMinchan Kim 
23431a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
23441a4e58ccSMinchan Kim 						NODE_DATA(nid),
2345013339dfSShakeel Butt 						&sc, &dummy_stat, false);
23461a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
23471a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
23481a4e58ccSMinchan Kim 			list_del(&page->lru);
23491a4e58ccSMinchan Kim 			putback_lru_page(page);
23501a4e58ccSMinchan Kim 		}
23511a4e58ccSMinchan Kim 
2352f661d007SYang Shi 		nid = NUMA_NO_NODE;
23531a4e58ccSMinchan Kim 	}
23541a4e58ccSMinchan Kim 
23551a4e58ccSMinchan Kim 	if (!list_empty(&node_page_list)) {
23561a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
23571a4e58ccSMinchan Kim 						NODE_DATA(nid),
2358013339dfSShakeel Butt 						&sc, &dummy_stat, false);
23591a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
23601a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
23611a4e58ccSMinchan Kim 			list_del(&page->lru);
23621a4e58ccSMinchan Kim 			putback_lru_page(page);
23631a4e58ccSMinchan Kim 		}
23641a4e58ccSMinchan Kim 	}
23651a4e58ccSMinchan Kim 
2366*2d2b8d2bSYu Zhao 	memalloc_noreclaim_restore(noreclaim_flag);
2367*2d2b8d2bSYu Zhao 
23681a4e58ccSMinchan Kim 	return nr_reclaimed;
23691a4e58ccSMinchan Kim }
23701a4e58ccSMinchan Kim 
2371b91ac374SJohannes Weiner static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2372b91ac374SJohannes Weiner 				 struct lruvec *lruvec, struct scan_control *sc)
2373b91ac374SJohannes Weiner {
2374b91ac374SJohannes Weiner 	if (is_active_lru(lru)) {
2375b91ac374SJohannes Weiner 		if (sc->may_deactivate & (1 << is_file_lru(lru)))
2376b91ac374SJohannes Weiner 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2377b91ac374SJohannes Weiner 		else
2378b91ac374SJohannes Weiner 			sc->skipped_deactivate = 1;
2379b91ac374SJohannes Weiner 		return 0;
2380b91ac374SJohannes Weiner 	}
2381b91ac374SJohannes Weiner 
2382b91ac374SJohannes Weiner 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2383b91ac374SJohannes Weiner }
2384b91ac374SJohannes Weiner 
238559dc76b0SRik van Riel /*
238659dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
238759dc76b0SRik van Riel  * to do too much work.
238814797e23SKOSAKI Motohiro  *
238959dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
239059dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
239159dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
239259dc76b0SRik van Riel  *
239359dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
239459dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
239559dc76b0SRik van Riel  *
23962a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
23972a2e4885SJohannes Weiner  *
239859dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
23993a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
240059dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
240159dc76b0SRik van Riel  *
240259dc76b0SRik van Riel  * total     target    max
240359dc76b0SRik van Riel  * memory    ratio     inactive
240459dc76b0SRik van Riel  * -------------------------------------
240559dc76b0SRik van Riel  *   10MB       1         5MB
240659dc76b0SRik van Riel  *  100MB       1        50MB
240759dc76b0SRik van Riel  *    1GB       3       250MB
240859dc76b0SRik van Riel  *   10GB      10       0.9GB
240959dc76b0SRik van Riel  *  100GB      31         3GB
241059dc76b0SRik van Riel  *    1TB     101        10GB
241159dc76b0SRik van Riel  *   10TB     320        32GB
241214797e23SKOSAKI Motohiro  */
2413b91ac374SJohannes Weiner static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
241414797e23SKOSAKI Motohiro {
2415b91ac374SJohannes Weiner 	enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
24162a2e4885SJohannes Weiner 	unsigned long inactive, active;
24172a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
241859dc76b0SRik van Riel 	unsigned long gb;
241959dc76b0SRik van Riel 
2420b91ac374SJohannes Weiner 	inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2421b91ac374SJohannes Weiner 	active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2422f8d1a311SMel Gorman 
242359dc76b0SRik van Riel 	gb = (inactive + active) >> (30 - PAGE_SHIFT);
24244002570cSJoonsoo Kim 	if (gb)
242559dc76b0SRik van Riel 		inactive_ratio = int_sqrt(10 * gb);
2426b39415b2SRik van Riel 	else
242759dc76b0SRik van Riel 		inactive_ratio = 1;
2428fd538803SMichal Hocko 
242959dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2430b39415b2SRik van Riel }
2431b39415b2SRik van Riel 
24329a265114SJohannes Weiner enum scan_balance {
24339a265114SJohannes Weiner 	SCAN_EQUAL,
24349a265114SJohannes Weiner 	SCAN_FRACT,
24359a265114SJohannes Weiner 	SCAN_ANON,
24369a265114SJohannes Weiner 	SCAN_FILE,
24379a265114SJohannes Weiner };
24389a265114SJohannes Weiner 
24391da177e4SLinus Torvalds /*
24404f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
24414f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
24424f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
24434f98a2feSRik van Riel  * onto the active list instead of evict.
24444f98a2feSRik van Riel  *
2445be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2446be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
24474f98a2feSRik van Riel  */
2448afaf07a6SJohannes Weiner static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2449afaf07a6SJohannes Weiner 			   unsigned long *nr)
24504f98a2feSRik van Riel {
2451afaf07a6SJohannes Weiner 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2452d483a5ddSJohannes Weiner 	unsigned long anon_cost, file_cost, total_cost;
245333377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
2454ed017373SYu Zhao 	u64 fraction[ANON_AND_FILE];
24559a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
24569a265114SJohannes Weiner 	enum scan_balance scan_balance;
24579a265114SJohannes Weiner 	unsigned long ap, fp;
24589a265114SJohannes Weiner 	enum lru_list lru;
245976a33fc3SShaohua Li 
246076a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2461d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
24629a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
246376a33fc3SShaohua Li 		goto out;
246476a33fc3SShaohua Li 	}
24654f98a2feSRik van Riel 
246610316b31SJohannes Weiner 	/*
246710316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
246810316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
246910316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
247010316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
247110316b31SJohannes Weiner 	 * too expensive.
247210316b31SJohannes Weiner 	 */
2473b5ead35eSJohannes Weiner 	if (cgroup_reclaim(sc) && !swappiness) {
24749a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
247510316b31SJohannes Weiner 		goto out;
247610316b31SJohannes Weiner 	}
247710316b31SJohannes Weiner 
247810316b31SJohannes Weiner 	/*
247910316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
248010316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
248110316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
248210316b31SJohannes Weiner 	 */
248302695175SJohannes Weiner 	if (!sc->priority && swappiness) {
24849a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
248510316b31SJohannes Weiner 		goto out;
248610316b31SJohannes Weiner 	}
248710316b31SJohannes Weiner 
248811d16c25SJohannes Weiner 	/*
248953138ceaSJohannes Weiner 	 * If the system is almost out of file pages, force-scan anon.
249062376251SJohannes Weiner 	 */
2491b91ac374SJohannes Weiner 	if (sc->file_is_tiny) {
249262376251SJohannes Weiner 		scan_balance = SCAN_ANON;
249362376251SJohannes Weiner 		goto out;
249462376251SJohannes Weiner 	}
249562376251SJohannes Weiner 
249662376251SJohannes Weiner 	/*
2497b91ac374SJohannes Weiner 	 * If there is enough inactive page cache, we do not reclaim
2498b91ac374SJohannes Weiner 	 * anything from the anonymous working right now.
2499e9868505SRik van Riel 	 */
2500b91ac374SJohannes Weiner 	if (sc->cache_trim_mode) {
25019a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2502e9868505SRik van Riel 		goto out;
25034f98a2feSRik van Riel 	}
25044f98a2feSRik van Riel 
25059a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
25064f98a2feSRik van Riel 	/*
2507314b57fbSJohannes Weiner 	 * Calculate the pressure balance between anon and file pages.
2508314b57fbSJohannes Weiner 	 *
2509314b57fbSJohannes Weiner 	 * The amount of pressure we put on each LRU is inversely
2510314b57fbSJohannes Weiner 	 * proportional to the cost of reclaiming each list, as
2511314b57fbSJohannes Weiner 	 * determined by the share of pages that are refaulting, times
2512314b57fbSJohannes Weiner 	 * the relative IO cost of bringing back a swapped out
2513314b57fbSJohannes Weiner 	 * anonymous page vs reloading a filesystem page (swappiness).
2514314b57fbSJohannes Weiner 	 *
2515d483a5ddSJohannes Weiner 	 * Although we limit that influence to ensure no list gets
2516d483a5ddSJohannes Weiner 	 * left behind completely: at least a third of the pressure is
2517d483a5ddSJohannes Weiner 	 * applied, before swappiness.
2518d483a5ddSJohannes Weiner 	 *
2519314b57fbSJohannes Weiner 	 * With swappiness at 100, anon and file have equal IO cost.
252058c37f6eSKOSAKI Motohiro 	 */
2521d483a5ddSJohannes Weiner 	total_cost = sc->anon_cost + sc->file_cost;
2522d483a5ddSJohannes Weiner 	anon_cost = total_cost + sc->anon_cost;
2523d483a5ddSJohannes Weiner 	file_cost = total_cost + sc->file_cost;
2524d483a5ddSJohannes Weiner 	total_cost = anon_cost + file_cost;
252558c37f6eSKOSAKI Motohiro 
2526d483a5ddSJohannes Weiner 	ap = swappiness * (total_cost + 1);
2527d483a5ddSJohannes Weiner 	ap /= anon_cost + 1;
25284f98a2feSRik van Riel 
2529d483a5ddSJohannes Weiner 	fp = (200 - swappiness) * (total_cost + 1);
2530d483a5ddSJohannes Weiner 	fp /= file_cost + 1;
25314f98a2feSRik van Riel 
253276a33fc3SShaohua Li 	fraction[0] = ap;
253376a33fc3SShaohua Li 	fraction[1] = fp;
2534a4fe1631SJohannes Weiner 	denominator = ap + fp;
253576a33fc3SShaohua Li out:
25364111304dSHugh Dickins 	for_each_evictable_lru(lru) {
25374111304dSHugh Dickins 		int file = is_file_lru(lru);
25389783aa99SChris Down 		unsigned long lruvec_size;
253976a33fc3SShaohua Li 		unsigned long scan;
25401bc63fb1SChris Down 		unsigned long protection;
254176a33fc3SShaohua Li 
25429783aa99SChris Down 		lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
254322f7496fSYafang Shao 		protection = mem_cgroup_protection(sc->target_mem_cgroup,
254422f7496fSYafang Shao 						   memcg,
25451bc63fb1SChris Down 						   sc->memcg_low_reclaim);
25469783aa99SChris Down 
25471bc63fb1SChris Down 		if (protection) {
25489783aa99SChris Down 			/*
25499783aa99SChris Down 			 * Scale a cgroup's reclaim pressure by proportioning
25509783aa99SChris Down 			 * its current usage to its memory.low or memory.min
25519783aa99SChris Down 			 * setting.
25529783aa99SChris Down 			 *
25539783aa99SChris Down 			 * This is important, as otherwise scanning aggression
25549783aa99SChris Down 			 * becomes extremely binary -- from nothing as we
25559783aa99SChris Down 			 * approach the memory protection threshold, to totally
25569783aa99SChris Down 			 * nominal as we exceed it.  This results in requiring
25579783aa99SChris Down 			 * setting extremely liberal protection thresholds. It
25589783aa99SChris Down 			 * also means we simply get no protection at all if we
25599783aa99SChris Down 			 * set it too low, which is not ideal.
25601bc63fb1SChris Down 			 *
25611bc63fb1SChris Down 			 * If there is any protection in place, we reduce scan
25621bc63fb1SChris Down 			 * pressure by how much of the total memory used is
25631bc63fb1SChris Down 			 * within protection thresholds.
25649783aa99SChris Down 			 *
25659de7ca46SChris Down 			 * There is one special case: in the first reclaim pass,
25669de7ca46SChris Down 			 * we skip over all groups that are within their low
25679de7ca46SChris Down 			 * protection. If that fails to reclaim enough pages to
25689de7ca46SChris Down 			 * satisfy the reclaim goal, we come back and override
25699de7ca46SChris Down 			 * the best-effort low protection. However, we still
25709de7ca46SChris Down 			 * ideally want to honor how well-behaved groups are in
25719de7ca46SChris Down 			 * that case instead of simply punishing them all
25729de7ca46SChris Down 			 * equally. As such, we reclaim them based on how much
25731bc63fb1SChris Down 			 * memory they are using, reducing the scan pressure
25741bc63fb1SChris Down 			 * again by how much of the total memory used is under
25751bc63fb1SChris Down 			 * hard protection.
25769783aa99SChris Down 			 */
25771bc63fb1SChris Down 			unsigned long cgroup_size = mem_cgroup_size(memcg);
25781bc63fb1SChris Down 
25791bc63fb1SChris Down 			/* Avoid TOCTOU with earlier protection check */
25801bc63fb1SChris Down 			cgroup_size = max(cgroup_size, protection);
25811bc63fb1SChris Down 
25821bc63fb1SChris Down 			scan = lruvec_size - lruvec_size * protection /
25831bc63fb1SChris Down 				cgroup_size;
25849783aa99SChris Down 
25859783aa99SChris Down 			/*
25861bc63fb1SChris Down 			 * Minimally target SWAP_CLUSTER_MAX pages to keep
258755b65a57SEthon Paul 			 * reclaim moving forwards, avoiding decrementing
25889de7ca46SChris Down 			 * sc->priority further than desirable.
25899783aa99SChris Down 			 */
25901bc63fb1SChris Down 			scan = max(scan, SWAP_CLUSTER_MAX);
25919783aa99SChris Down 		} else {
25929783aa99SChris Down 			scan = lruvec_size;
25939783aa99SChris Down 		}
25949783aa99SChris Down 
25959783aa99SChris Down 		scan >>= sc->priority;
25969783aa99SChris Down 
2597688035f7SJohannes Weiner 		/*
2598688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2599688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2600688035f7SJohannes Weiner 		 */
2601688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
26029783aa99SChris Down 			scan = min(lruvec_size, SWAP_CLUSTER_MAX);
26039a265114SJohannes Weiner 
26049a265114SJohannes Weiner 		switch (scan_balance) {
26059a265114SJohannes Weiner 		case SCAN_EQUAL:
26069a265114SJohannes Weiner 			/* Scan lists relative to size */
26079a265114SJohannes Weiner 			break;
26089a265114SJohannes Weiner 		case SCAN_FRACT:
26099a265114SJohannes Weiner 			/*
26109a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
26119a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
261276073c64SGavin Shan 			 * Make sure we don't miss the last page on
261376073c64SGavin Shan 			 * the offlined memory cgroups because of a
261476073c64SGavin Shan 			 * round-off error.
26159a265114SJohannes Weiner 			 */
261676073c64SGavin Shan 			scan = mem_cgroup_online(memcg) ?
261776073c64SGavin Shan 			       div64_u64(scan * fraction[file], denominator) :
261876073c64SGavin Shan 			       DIV64_U64_ROUND_UP(scan * fraction[file],
26196f04f48dSSuleiman Souhlal 						  denominator);
26209a265114SJohannes Weiner 			break;
26219a265114SJohannes Weiner 		case SCAN_FILE:
26229a265114SJohannes Weiner 		case SCAN_ANON:
26239a265114SJohannes Weiner 			/* Scan one type exclusively */
2624e072bff6SMateusz Nosek 			if ((scan_balance == SCAN_FILE) != file)
26259a265114SJohannes Weiner 				scan = 0;
26269a265114SJohannes Weiner 			break;
26279a265114SJohannes Weiner 		default:
26289a265114SJohannes Weiner 			/* Look ma, no brain */
26299a265114SJohannes Weiner 			BUG();
26309a265114SJohannes Weiner 		}
26316b4f7799SJohannes Weiner 
26324111304dSHugh Dickins 		nr[lru] = scan;
263376a33fc3SShaohua Li 	}
26346e08a369SWu Fengguang }
26354f98a2feSRik van Riel 
2636afaf07a6SJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
26379b4f98cdSJohannes Weiner {
26389b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2639e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
26409b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
26419b4f98cdSJohannes Weiner 	enum lru_list lru;
26429b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
26439b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
26449b4f98cdSJohannes Weiner 	struct blk_plug plug;
26451a501907SMel Gorman 	bool scan_adjusted;
26469b4f98cdSJohannes Weiner 
2647afaf07a6SJohannes Weiner 	get_scan_count(lruvec, sc, nr);
26489b4f98cdSJohannes Weiner 
2649e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2650e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2651e82e0561SMel Gorman 
26521a501907SMel Gorman 	/*
26531a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
26541a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
26551a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
26561a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
26571a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
26581a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
26591a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
26601a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
26611a501907SMel Gorman 	 * dropped to zero at the first pass.
26621a501907SMel Gorman 	 */
2663b5ead35eSJohannes Weiner 	scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
26641a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
26651a501907SMel Gorman 
26669b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
26679b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
26689b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2669e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2670e82e0561SMel Gorman 		unsigned long nr_scanned;
2671e82e0561SMel Gorman 
26729b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
26739b4f98cdSJohannes Weiner 			if (nr[lru]) {
26749b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
26759b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
26769b4f98cdSJohannes Weiner 
26779b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
26783b991208SJohannes Weiner 							    lruvec, sc);
26799b4f98cdSJohannes Weiner 			}
26809b4f98cdSJohannes Weiner 		}
2681e82e0561SMel Gorman 
2682bd041733SMichal Hocko 		cond_resched();
2683bd041733SMichal Hocko 
2684e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2685e82e0561SMel Gorman 			continue;
2686e82e0561SMel Gorman 
26879b4f98cdSJohannes Weiner 		/*
2688e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
26891a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2690e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2691e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2692e82e0561SMel Gorman 		 * proportional to the original scan target.
2693e82e0561SMel Gorman 		 */
2694e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2695e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2696e82e0561SMel Gorman 
26971a501907SMel Gorman 		/*
26981a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
26991a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
27001a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
27011a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
27021a501907SMel Gorman 		 */
27031a501907SMel Gorman 		if (!nr_file || !nr_anon)
27041a501907SMel Gorman 			break;
27051a501907SMel Gorman 
2706e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2707e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2708e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2709e82e0561SMel Gorman 			lru = LRU_BASE;
2710e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2711e82e0561SMel Gorman 		} else {
2712e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2713e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2714e82e0561SMel Gorman 			lru = LRU_FILE;
2715e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2716e82e0561SMel Gorman 		}
2717e82e0561SMel Gorman 
2718e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2719e82e0561SMel Gorman 		nr[lru] = 0;
2720e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2721e82e0561SMel Gorman 
2722e82e0561SMel Gorman 		/*
2723e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2724e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2725e82e0561SMel Gorman 		 */
2726e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2727e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2728e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2729e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2730e82e0561SMel Gorman 
2731e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2732e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2733e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2734e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2735e82e0561SMel Gorman 
2736e82e0561SMel Gorman 		scan_adjusted = true;
27379b4f98cdSJohannes Weiner 	}
27389b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
27399b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
27409b4f98cdSJohannes Weiner 
27419b4f98cdSJohannes Weiner 	/*
27429b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
27439b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
27449b4f98cdSJohannes Weiner 	 */
2745b91ac374SJohannes Weiner 	if (total_swap_pages && inactive_is_low(lruvec, LRU_INACTIVE_ANON))
27469b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
27479b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
27489b4f98cdSJohannes Weiner }
27499b4f98cdSJohannes Weiner 
275023b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
27519e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
275223b9da55SMel Gorman {
2753d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
275423b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
27559e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
275623b9da55SMel Gorman 		return true;
275723b9da55SMel Gorman 
275823b9da55SMel Gorman 	return false;
275923b9da55SMel Gorman }
276023b9da55SMel Gorman 
27614f98a2feSRik van Riel /*
276223b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
276323b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
276423b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
2765df3a45f9SQiwu Chen  * calls try_to_compact_pages() that it will have enough free pages to succeed.
276623b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
27673e7d3449SMel Gorman  */
2768a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
27693e7d3449SMel Gorman 					unsigned long nr_reclaimed,
27703e7d3449SMel Gorman 					struct scan_control *sc)
27713e7d3449SMel Gorman {
27723e7d3449SMel Gorman 	unsigned long pages_for_compaction;
27733e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2774a9dd0a83SMel Gorman 	int z;
27753e7d3449SMel Gorman 
27763e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
27779e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
27783e7d3449SMel Gorman 		return false;
27793e7d3449SMel Gorman 
27803e7d3449SMel Gorman 	/*
27815ee04716SVlastimil Babka 	 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
27825ee04716SVlastimil Babka 	 * number of pages that were scanned. This will return to the caller
27835ee04716SVlastimil Babka 	 * with the risk reclaim/compaction and the resulting allocation attempt
27845ee04716SVlastimil Babka 	 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
27855ee04716SVlastimil Babka 	 * allocations through requiring that the full LRU list has been scanned
27865ee04716SVlastimil Babka 	 * first, by assuming that zero delta of sc->nr_scanned means full LRU
27875ee04716SVlastimil Babka 	 * scan, but that approximation was wrong, and there were corner cases
27885ee04716SVlastimil Babka 	 * where always a non-zero amount of pages were scanned.
27892876592fSMel Gorman 	 */
27902876592fSMel Gorman 	if (!nr_reclaimed)
27912876592fSMel Gorman 		return false;
27923e7d3449SMel Gorman 
27933e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2794a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2795a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
27966aa303deSMel Gorman 		if (!managed_zone(zone))
2797a9dd0a83SMel Gorman 			continue;
2798a9dd0a83SMel Gorman 
2799a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2800cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
28013e7d3449SMel Gorman 		case COMPACT_CONTINUE:
28023e7d3449SMel Gorman 			return false;
28033e7d3449SMel Gorman 		default:
2804a9dd0a83SMel Gorman 			/* check next zone */
2805a9dd0a83SMel Gorman 			;
28063e7d3449SMel Gorman 		}
28073e7d3449SMel Gorman 	}
28081c6c1597SHillf Danton 
28091c6c1597SHillf Danton 	/*
28101c6c1597SHillf Danton 	 * If we have not reclaimed enough pages for compaction and the
28111c6c1597SHillf Danton 	 * inactive lists are large enough, continue reclaiming
28121c6c1597SHillf Danton 	 */
28131c6c1597SHillf Danton 	pages_for_compaction = compact_gap(sc->order);
28141c6c1597SHillf Danton 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
28151c6c1597SHillf Danton 	if (get_nr_swap_pages() > 0)
28161c6c1597SHillf Danton 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
28171c6c1597SHillf Danton 
28185ee04716SVlastimil Babka 	return inactive_lru_pages > pages_for_compaction;
2819a9dd0a83SMel Gorman }
28203e7d3449SMel Gorman 
28210f6a5cffSJohannes Weiner static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
2822f16015fbSJohannes Weiner {
28230f6a5cffSJohannes Weiner 	struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
2824694fbc0fSAndrew Morton 	struct mem_cgroup *memcg;
2825d108c772SAndrey Ryabinin 
28260f6a5cffSJohannes Weiner 	memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
2827694fbc0fSAndrew Morton 	do {
2828afaf07a6SJohannes Weiner 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
28298e8ae645SJohannes Weiner 		unsigned long reclaimed;
2830cb731d6cSVladimir Davydov 		unsigned long scanned;
28319b4f98cdSJohannes Weiner 
2832e3336cabSXunlei Pang 		/*
2833e3336cabSXunlei Pang 		 * This loop can become CPU-bound when target memcgs
2834e3336cabSXunlei Pang 		 * aren't eligible for reclaim - either because they
2835e3336cabSXunlei Pang 		 * don't have any reclaimable pages, or because their
2836e3336cabSXunlei Pang 		 * memory is explicitly protected. Avoid soft lockups.
2837e3336cabSXunlei Pang 		 */
2838e3336cabSXunlei Pang 		cond_resched();
2839e3336cabSXunlei Pang 
284045c7f7e1SChris Down 		mem_cgroup_calculate_protection(target_memcg, memcg);
284145c7f7e1SChris Down 
284245c7f7e1SChris Down 		if (mem_cgroup_below_min(memcg)) {
2843bf8d5d52SRoman Gushchin 			/*
2844bf8d5d52SRoman Gushchin 			 * Hard protection.
2845bf8d5d52SRoman Gushchin 			 * If there is no reclaimable memory, OOM.
2846bf8d5d52SRoman Gushchin 			 */
2847bf8d5d52SRoman Gushchin 			continue;
284845c7f7e1SChris Down 		} else if (mem_cgroup_below_low(memcg)) {
2849bf8d5d52SRoman Gushchin 			/*
2850bf8d5d52SRoman Gushchin 			 * Soft protection.
2851bf8d5d52SRoman Gushchin 			 * Respect the protection only as long as
2852bf8d5d52SRoman Gushchin 			 * there is an unprotected supply
2853bf8d5d52SRoman Gushchin 			 * of reclaimable memory from other cgroups.
2854bf8d5d52SRoman Gushchin 			 */
2855d6622f63SYisheng Xie 			if (!sc->memcg_low_reclaim) {
2856d6622f63SYisheng Xie 				sc->memcg_low_skipped = 1;
2857241994edSJohannes Weiner 				continue;
2858d6622f63SYisheng Xie 			}
2859e27be240SJohannes Weiner 			memcg_memory_event(memcg, MEMCG_LOW);
2860241994edSJohannes Weiner 		}
2861241994edSJohannes Weiner 
28628e8ae645SJohannes Weiner 		reclaimed = sc->nr_reclaimed;
2863cb731d6cSVladimir Davydov 		scanned = sc->nr_scanned;
2864afaf07a6SJohannes Weiner 
2865afaf07a6SJohannes Weiner 		shrink_lruvec(lruvec, sc);
2866f9be23d6SKonstantin Khlebnikov 
286728360f39SMel Gorman 		shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
286828360f39SMel Gorman 			    sc->priority);
2869cb731d6cSVladimir Davydov 
28708e8ae645SJohannes Weiner 		/* Record the group's reclaim efficiency */
28718e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, memcg, false,
28728e8ae645SJohannes Weiner 			   sc->nr_scanned - scanned,
28738e8ae645SJohannes Weiner 			   sc->nr_reclaimed - reclaimed);
28748e8ae645SJohannes Weiner 
28750f6a5cffSJohannes Weiner 	} while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
28760f6a5cffSJohannes Weiner }
28770f6a5cffSJohannes Weiner 
28786c9e0907SLiu Song static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
28790f6a5cffSJohannes Weiner {
28800f6a5cffSJohannes Weiner 	struct reclaim_state *reclaim_state = current->reclaim_state;
28810f6a5cffSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
28821b05117dSJohannes Weiner 	struct lruvec *target_lruvec;
28830f6a5cffSJohannes Weiner 	bool reclaimable = false;
2884b91ac374SJohannes Weiner 	unsigned long file;
28850f6a5cffSJohannes Weiner 
28861b05117dSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
28871b05117dSJohannes Weiner 
28880f6a5cffSJohannes Weiner again:
28890f6a5cffSJohannes Weiner 	memset(&sc->nr, 0, sizeof(sc->nr));
28900f6a5cffSJohannes Weiner 
28910f6a5cffSJohannes Weiner 	nr_reclaimed = sc->nr_reclaimed;
28920f6a5cffSJohannes Weiner 	nr_scanned = sc->nr_scanned;
28930f6a5cffSJohannes Weiner 
289453138ceaSJohannes Weiner 	/*
28957cf111bcSJohannes Weiner 	 * Determine the scan balance between anon and file LRUs.
28967cf111bcSJohannes Weiner 	 */
28976168d0daSAlex Shi 	spin_lock_irq(&target_lruvec->lru_lock);
28987cf111bcSJohannes Weiner 	sc->anon_cost = target_lruvec->anon_cost;
28997cf111bcSJohannes Weiner 	sc->file_cost = target_lruvec->file_cost;
29006168d0daSAlex Shi 	spin_unlock_irq(&target_lruvec->lru_lock);
29017cf111bcSJohannes Weiner 
29027cf111bcSJohannes Weiner 	/*
2903b91ac374SJohannes Weiner 	 * Target desirable inactive:active list ratios for the anon
2904b91ac374SJohannes Weiner 	 * and file LRU lists.
2905b91ac374SJohannes Weiner 	 */
2906b91ac374SJohannes Weiner 	if (!sc->force_deactivate) {
2907b91ac374SJohannes Weiner 		unsigned long refaults;
2908b91ac374SJohannes Weiner 
2909170b04b7SJoonsoo Kim 		refaults = lruvec_page_state(target_lruvec,
2910170b04b7SJoonsoo Kim 				WORKINGSET_ACTIVATE_ANON);
2911170b04b7SJoonsoo Kim 		if (refaults != target_lruvec->refaults[0] ||
2912170b04b7SJoonsoo Kim 			inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2913b91ac374SJohannes Weiner 			sc->may_deactivate |= DEACTIVATE_ANON;
2914b91ac374SJohannes Weiner 		else
2915b91ac374SJohannes Weiner 			sc->may_deactivate &= ~DEACTIVATE_ANON;
2916b91ac374SJohannes Weiner 
2917b91ac374SJohannes Weiner 		/*
2918b91ac374SJohannes Weiner 		 * When refaults are being observed, it means a new
2919b91ac374SJohannes Weiner 		 * workingset is being established. Deactivate to get
2920b91ac374SJohannes Weiner 		 * rid of any stale active pages quickly.
2921b91ac374SJohannes Weiner 		 */
2922b91ac374SJohannes Weiner 		refaults = lruvec_page_state(target_lruvec,
2923170b04b7SJoonsoo Kim 				WORKINGSET_ACTIVATE_FILE);
2924170b04b7SJoonsoo Kim 		if (refaults != target_lruvec->refaults[1] ||
2925b91ac374SJohannes Weiner 		    inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2926b91ac374SJohannes Weiner 			sc->may_deactivate |= DEACTIVATE_FILE;
2927b91ac374SJohannes Weiner 		else
2928b91ac374SJohannes Weiner 			sc->may_deactivate &= ~DEACTIVATE_FILE;
2929b91ac374SJohannes Weiner 	} else
2930b91ac374SJohannes Weiner 		sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2931b91ac374SJohannes Weiner 
2932b91ac374SJohannes Weiner 	/*
2933b91ac374SJohannes Weiner 	 * If we have plenty of inactive file pages that aren't
2934b91ac374SJohannes Weiner 	 * thrashing, try to reclaim those first before touching
2935b91ac374SJohannes Weiner 	 * anonymous pages.
2936b91ac374SJohannes Weiner 	 */
2937b91ac374SJohannes Weiner 	file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2938b91ac374SJohannes Weiner 	if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2939b91ac374SJohannes Weiner 		sc->cache_trim_mode = 1;
2940b91ac374SJohannes Weiner 	else
2941b91ac374SJohannes Weiner 		sc->cache_trim_mode = 0;
2942b91ac374SJohannes Weiner 
2943b91ac374SJohannes Weiner 	/*
294453138ceaSJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
294553138ceaSJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
294653138ceaSJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
294753138ceaSJohannes Weiner 	 * shrinks, so does the window for rotation from references.
294853138ceaSJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
294953138ceaSJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
295053138ceaSJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
295153138ceaSJohannes Weiner 	 */
295253138ceaSJohannes Weiner 	if (!cgroup_reclaim(sc)) {
295353138ceaSJohannes Weiner 		unsigned long total_high_wmark = 0;
2954b91ac374SJohannes Weiner 		unsigned long free, anon;
2955b91ac374SJohannes Weiner 		int z;
295653138ceaSJohannes Weiner 
295753138ceaSJohannes Weiner 		free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
295853138ceaSJohannes Weiner 		file = node_page_state(pgdat, NR_ACTIVE_FILE) +
295953138ceaSJohannes Weiner 			   node_page_state(pgdat, NR_INACTIVE_FILE);
296053138ceaSJohannes Weiner 
296153138ceaSJohannes Weiner 		for (z = 0; z < MAX_NR_ZONES; z++) {
296253138ceaSJohannes Weiner 			struct zone *zone = &pgdat->node_zones[z];
296353138ceaSJohannes Weiner 			if (!managed_zone(zone))
296453138ceaSJohannes Weiner 				continue;
296553138ceaSJohannes Weiner 
296653138ceaSJohannes Weiner 			total_high_wmark += high_wmark_pages(zone);
296753138ceaSJohannes Weiner 		}
296853138ceaSJohannes Weiner 
2969b91ac374SJohannes Weiner 		/*
2970b91ac374SJohannes Weiner 		 * Consider anon: if that's low too, this isn't a
2971b91ac374SJohannes Weiner 		 * runaway file reclaim problem, but rather just
2972b91ac374SJohannes Weiner 		 * extreme pressure. Reclaim as per usual then.
2973b91ac374SJohannes Weiner 		 */
2974b91ac374SJohannes Weiner 		anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2975b91ac374SJohannes Weiner 
2976b91ac374SJohannes Weiner 		sc->file_is_tiny =
2977b91ac374SJohannes Weiner 			file + free <= total_high_wmark &&
2978b91ac374SJohannes Weiner 			!(sc->may_deactivate & DEACTIVATE_ANON) &&
2979b91ac374SJohannes Weiner 			anon >> sc->priority;
298053138ceaSJohannes Weiner 	}
298153138ceaSJohannes Weiner 
29820f6a5cffSJohannes Weiner 	shrink_node_memcgs(pgdat, sc);
298370ddf637SAnton Vorontsov 
29846b4f7799SJohannes Weiner 	if (reclaim_state) {
2985cb731d6cSVladimir Davydov 		sc->nr_reclaimed += reclaim_state->reclaimed_slab;
29866b4f7799SJohannes Weiner 		reclaim_state->reclaimed_slab = 0;
29876b4f7799SJohannes Weiner 	}
29886b4f7799SJohannes Weiner 
29898e8ae645SJohannes Weiner 	/* Record the subtree's reclaim efficiency */
29901b05117dSJohannes Weiner 	vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
299170ddf637SAnton Vorontsov 		   sc->nr_scanned - nr_scanned,
299270ddf637SAnton Vorontsov 		   sc->nr_reclaimed - nr_reclaimed);
299370ddf637SAnton Vorontsov 
29942344d7e4SJohannes Weiner 	if (sc->nr_reclaimed - nr_reclaimed)
29952344d7e4SJohannes Weiner 		reclaimable = true;
29962344d7e4SJohannes Weiner 
2997e3c1ac58SAndrey Ryabinin 	if (current_is_kswapd()) {
2998d108c772SAndrey Ryabinin 		/*
2999e3c1ac58SAndrey Ryabinin 		 * If reclaim is isolating dirty pages under writeback,
3000e3c1ac58SAndrey Ryabinin 		 * it implies that the long-lived page allocation rate
3001e3c1ac58SAndrey Ryabinin 		 * is exceeding the page laundering rate. Either the
3002e3c1ac58SAndrey Ryabinin 		 * global limits are not being effective at throttling
3003e3c1ac58SAndrey Ryabinin 		 * processes due to the page distribution throughout
3004e3c1ac58SAndrey Ryabinin 		 * zones or there is heavy usage of a slow backing
3005e3c1ac58SAndrey Ryabinin 		 * device. The only option is to throttle from reclaim
3006e3c1ac58SAndrey Ryabinin 		 * context which is not ideal as there is no guarantee
3007d108c772SAndrey Ryabinin 		 * the dirtying process is throttled in the same way
3008d108c772SAndrey Ryabinin 		 * balance_dirty_pages() manages.
3009d108c772SAndrey Ryabinin 		 *
3010e3c1ac58SAndrey Ryabinin 		 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
3011e3c1ac58SAndrey Ryabinin 		 * count the number of pages under pages flagged for
3012e3c1ac58SAndrey Ryabinin 		 * immediate reclaim and stall if any are encountered
3013e3c1ac58SAndrey Ryabinin 		 * in the nr_immediate check below.
3014d108c772SAndrey Ryabinin 		 */
3015d108c772SAndrey Ryabinin 		if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
3016d108c772SAndrey Ryabinin 			set_bit(PGDAT_WRITEBACK, &pgdat->flags);
3017d108c772SAndrey Ryabinin 
3018d108c772SAndrey Ryabinin 		/* Allow kswapd to start writing pages during reclaim.*/
3019d108c772SAndrey Ryabinin 		if (sc->nr.unqueued_dirty == sc->nr.file_taken)
3020d108c772SAndrey Ryabinin 			set_bit(PGDAT_DIRTY, &pgdat->flags);
3021d108c772SAndrey Ryabinin 
3022d108c772SAndrey Ryabinin 		/*
30231eba09c1SRandy Dunlap 		 * If kswapd scans pages marked for immediate
3024d108c772SAndrey Ryabinin 		 * reclaim and under writeback (nr_immediate), it
3025d108c772SAndrey Ryabinin 		 * implies that pages are cycling through the LRU
3026d108c772SAndrey Ryabinin 		 * faster than they are written so also forcibly stall.
3027d108c772SAndrey Ryabinin 		 */
3028d108c772SAndrey Ryabinin 		if (sc->nr.immediate)
3029d108c772SAndrey Ryabinin 			congestion_wait(BLK_RW_ASYNC, HZ/10);
3030d108c772SAndrey Ryabinin 	}
3031d108c772SAndrey Ryabinin 
3032d108c772SAndrey Ryabinin 	/*
30331b05117dSJohannes Weiner 	 * Tag a node/memcg as congested if all the dirty pages
30341b05117dSJohannes Weiner 	 * scanned were backed by a congested BDI and
30351b05117dSJohannes Weiner 	 * wait_iff_congested will stall.
30361b05117dSJohannes Weiner 	 *
3037e3c1ac58SAndrey Ryabinin 	 * Legacy memcg will stall in page writeback so avoid forcibly
3038e3c1ac58SAndrey Ryabinin 	 * stalling in wait_iff_congested().
3039e3c1ac58SAndrey Ryabinin 	 */
30401b05117dSJohannes Weiner 	if ((current_is_kswapd() ||
30411b05117dSJohannes Weiner 	     (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
3042e3c1ac58SAndrey Ryabinin 	    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
30431b05117dSJohannes Weiner 		set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
3044e3c1ac58SAndrey Ryabinin 
3045e3c1ac58SAndrey Ryabinin 	/*
3046d108c772SAndrey Ryabinin 	 * Stall direct reclaim for IO completions if underlying BDIs
3047d108c772SAndrey Ryabinin 	 * and node is congested. Allow kswapd to continue until it
3048d108c772SAndrey Ryabinin 	 * starts encountering unqueued dirty pages or cycling through
3049d108c772SAndrey Ryabinin 	 * the LRU too quickly.
3050d108c772SAndrey Ryabinin 	 */
30511b05117dSJohannes Weiner 	if (!current_is_kswapd() && current_may_throttle() &&
30521b05117dSJohannes Weiner 	    !sc->hibernation_mode &&
30531b05117dSJohannes Weiner 	    test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
3054e3c1ac58SAndrey Ryabinin 		wait_iff_congested(BLK_RW_ASYNC, HZ/10);
3055d108c772SAndrey Ryabinin 
3056d2af3397SJohannes Weiner 	if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
3057d2af3397SJohannes Weiner 				    sc))
3058d2af3397SJohannes Weiner 		goto again;
30592344d7e4SJohannes Weiner 
3060c73322d0SJohannes Weiner 	/*
3061c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
3062c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
3063c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
3064c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
3065c73322d0SJohannes Weiner 	 */
3066c73322d0SJohannes Weiner 	if (reclaimable)
3067c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
3068f16015fbSJohannes Weiner }
3069f16015fbSJohannes Weiner 
307053853e2dSVlastimil Babka /*
3071fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
3072fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
3073fdd4c614SVlastimil Babka  * should reclaim first.
307453853e2dSVlastimil Babka  */
30754f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
3076fe4b1b24SMel Gorman {
307731483b6aSMel Gorman 	unsigned long watermark;
3078fdd4c614SVlastimil Babka 	enum compact_result suitable;
3079fe4b1b24SMel Gorman 
3080fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
3081fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
3082fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
3083fdd4c614SVlastimil Babka 		return true;
3084fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
3085fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
3086fe4b1b24SMel Gorman 		return false;
3087fe4b1b24SMel Gorman 
3088fdd4c614SVlastimil Babka 	/*
3089fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
3090fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
3091fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
3092fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
3093fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
3094fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
3095fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
3096fdd4c614SVlastimil Babka 	 */
3097fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
3098fdd4c614SVlastimil Babka 
3099fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
3100fe4b1b24SMel Gorman }
3101fe4b1b24SMel Gorman 
31021da177e4SLinus Torvalds /*
31031da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
31041da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
31051da177e4SLinus Torvalds  * request.
31061da177e4SLinus Torvalds  *
31071da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
31081da177e4SLinus Torvalds  * scan then give up on it.
31091da177e4SLinus Torvalds  */
31100a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
31111da177e4SLinus Torvalds {
3112dd1a239fSMel Gorman 	struct zoneref *z;
311354a6eb5cSMel Gorman 	struct zone *zone;
31140608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
31150608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3116619d0d76SWeijie Yang 	gfp_t orig_mask;
311779dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
31181cfb419bSKAMEZAWA Hiroyuki 
3119cc715d99SMel Gorman 	/*
3120cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
3121cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
3122cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
3123cc715d99SMel Gorman 	 */
3124619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
3125b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
3126cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
31274f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
3128b2e18757SMel Gorman 	}
3129cc715d99SMel Gorman 
3130d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
3131b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
3132b2e18757SMel Gorman 		/*
31331cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
31341cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
31351cfb419bSKAMEZAWA Hiroyuki 		 */
3136b5ead35eSJohannes Weiner 		if (!cgroup_reclaim(sc)) {
3137344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
3138344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
31391da177e4SLinus Torvalds 				continue;
314065ec02cbSVladimir Davydov 
3141e0887c19SRik van Riel 			/*
3142e0c23279SMel Gorman 			 * If we already have plenty of memory free for
3143e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
3144e0c23279SMel Gorman 			 * Even though compaction is invoked for any
3145e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
3146e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
3147c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
3148c7cfa37bSCopot Alexandru 			 * page allocations.
3149e0887c19SRik van Riel 			 */
31500b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
31510b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
31524f588331SMel Gorman 			    compaction_ready(zone, sc)) {
31530b06496aSJohannes Weiner 				sc->compaction_ready = true;
3154e0887c19SRik van Riel 				continue;
3155e0887c19SRik van Riel 			}
31560b06496aSJohannes Weiner 
31570608f43dSAndrew Morton 			/*
315879dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
315979dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
316079dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
316179dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
316279dafcdcSMel Gorman 			 */
316379dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
316479dafcdcSMel Gorman 				continue;
316579dafcdcSMel Gorman 
316679dafcdcSMel Gorman 			/*
31670608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
31680608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
31690608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
31700608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
31710608f43dSAndrew Morton 			 */
31720608f43dSAndrew Morton 			nr_soft_scanned = 0;
3173ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
31740608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
31750608f43dSAndrew Morton 						&nr_soft_scanned);
31760608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
31770608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
3178ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
3179ac34a1a3SKAMEZAWA Hiroyuki 		}
3180d149e3b2SYing Han 
318179dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
318279dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
318379dafcdcSMel Gorman 			continue;
318479dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
3185970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
31861da177e4SLinus Torvalds 	}
3187e0c23279SMel Gorman 
318865ec02cbSVladimir Davydov 	/*
3189619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
3190619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
3191619d0d76SWeijie Yang 	 */
3192619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
31931da177e4SLinus Torvalds }
31941da177e4SLinus Torvalds 
3195b910718aSJohannes Weiner static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
31962a2e4885SJohannes Weiner {
3197b910718aSJohannes Weiner 	struct lruvec *target_lruvec;
31982a2e4885SJohannes Weiner 	unsigned long refaults;
31992a2e4885SJohannes Weiner 
3200b910718aSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
3201170b04b7SJoonsoo Kim 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
3202170b04b7SJoonsoo Kim 	target_lruvec->refaults[0] = refaults;
3203170b04b7SJoonsoo Kim 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
3204170b04b7SJoonsoo Kim 	target_lruvec->refaults[1] = refaults;
32052a2e4885SJohannes Weiner }
32062a2e4885SJohannes Weiner 
32071da177e4SLinus Torvalds /*
32081da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
32091da177e4SLinus Torvalds  *
32101da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
32111da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
32121da177e4SLinus Torvalds  *
32131da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
32141da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
32155b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
32165b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
32175b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
32185b0830cbSJens Axboe  * work, and the allocation attempt will fail.
3219a41f24eaSNishanth Aravamudan  *
3220a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
3221a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
32221da177e4SLinus Torvalds  */
3223dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
32243115cd91SVladimir Davydov 					  struct scan_control *sc)
32251da177e4SLinus Torvalds {
3226241994edSJohannes Weiner 	int initial_priority = sc->priority;
32272a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
32282a2e4885SJohannes Weiner 	struct zoneref *z;
32292a2e4885SJohannes Weiner 	struct zone *zone;
3230241994edSJohannes Weiner retry:
3231873b4771SKeika Kobayashi 	delayacct_freepages_start();
3232873b4771SKeika Kobayashi 
3233b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
32347cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
32351da177e4SLinus Torvalds 
32369e3b2f8cSKonstantin Khlebnikov 	do {
323770ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
323870ddf637SAnton Vorontsov 				sc->priority);
323966e1707bSBalbir Singh 		sc->nr_scanned = 0;
32400a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
3241e0c23279SMel Gorman 
3242bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
32430b06496aSJohannes Weiner 			break;
32440b06496aSJohannes Weiner 
32450b06496aSJohannes Weiner 		if (sc->compaction_ready)
32460b06496aSJohannes Weiner 			break;
32471da177e4SLinus Torvalds 
32481da177e4SLinus Torvalds 		/*
32490e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
32500e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
32510e50ce3bSMinchan Kim 		 */
32520e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
32530e50ce3bSMinchan Kim 			sc->may_writepage = 1;
32540b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
3255bb21c7ceSKOSAKI Motohiro 
32562a2e4885SJohannes Weiner 	last_pgdat = NULL;
32572a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
32582a2e4885SJohannes Weiner 					sc->nodemask) {
32592a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
32602a2e4885SJohannes Weiner 			continue;
32612a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
32621b05117dSJohannes Weiner 
32632a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
32641b05117dSJohannes Weiner 
32651b05117dSJohannes Weiner 		if (cgroup_reclaim(sc)) {
32661b05117dSJohannes Weiner 			struct lruvec *lruvec;
32671b05117dSJohannes Weiner 
32681b05117dSJohannes Weiner 			lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
32691b05117dSJohannes Weiner 						   zone->zone_pgdat);
32701b05117dSJohannes Weiner 			clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
32711b05117dSJohannes Weiner 		}
32722a2e4885SJohannes Weiner 	}
32732a2e4885SJohannes Weiner 
3274873b4771SKeika Kobayashi 	delayacct_freepages_end();
3275873b4771SKeika Kobayashi 
3276bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
3277bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
3278bb21c7ceSKOSAKI Motohiro 
32790cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
32800b06496aSJohannes Weiner 	if (sc->compaction_ready)
32817335084dSMel Gorman 		return 1;
32827335084dSMel Gorman 
3283b91ac374SJohannes Weiner 	/*
3284b91ac374SJohannes Weiner 	 * We make inactive:active ratio decisions based on the node's
3285b91ac374SJohannes Weiner 	 * composition of memory, but a restrictive reclaim_idx or a
3286b91ac374SJohannes Weiner 	 * memory.low cgroup setting can exempt large amounts of
3287b91ac374SJohannes Weiner 	 * memory from reclaim. Neither of which are very common, so
3288b91ac374SJohannes Weiner 	 * instead of doing costly eligibility calculations of the
3289b91ac374SJohannes Weiner 	 * entire cgroup subtree up front, we assume the estimates are
3290b91ac374SJohannes Weiner 	 * good, and retry with forcible deactivation if that fails.
3291b91ac374SJohannes Weiner 	 */
3292b91ac374SJohannes Weiner 	if (sc->skipped_deactivate) {
3293b91ac374SJohannes Weiner 		sc->priority = initial_priority;
3294b91ac374SJohannes Weiner 		sc->force_deactivate = 1;
3295b91ac374SJohannes Weiner 		sc->skipped_deactivate = 0;
3296b91ac374SJohannes Weiner 		goto retry;
3297b91ac374SJohannes Weiner 	}
3298b91ac374SJohannes Weiner 
3299241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
3300d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
3301241994edSJohannes Weiner 		sc->priority = initial_priority;
3302b91ac374SJohannes Weiner 		sc->force_deactivate = 0;
3303d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
3304d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
3305241994edSJohannes Weiner 		goto retry;
3306241994edSJohannes Weiner 	}
3307241994edSJohannes Weiner 
3308bb21c7ceSKOSAKI Motohiro 	return 0;
33091da177e4SLinus Torvalds }
33101da177e4SLinus Torvalds 
3311c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
33125515061dSMel Gorman {
33135515061dSMel Gorman 	struct zone *zone;
33145515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
33155515061dSMel Gorman 	unsigned long free_pages = 0;
33165515061dSMel Gorman 	int i;
33175515061dSMel Gorman 	bool wmark_ok;
33185515061dSMel Gorman 
3319c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3320c73322d0SJohannes Weiner 		return true;
3321c73322d0SJohannes Weiner 
33225515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
33235515061dSMel Gorman 		zone = &pgdat->node_zones[i];
3324d450abd8SJohannes Weiner 		if (!managed_zone(zone))
3325d450abd8SJohannes Weiner 			continue;
3326d450abd8SJohannes Weiner 
3327d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
3328675becceSMel Gorman 			continue;
3329675becceSMel Gorman 
33305515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
33315515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
33325515061dSMel Gorman 	}
33335515061dSMel Gorman 
3334675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
3335675becceSMel Gorman 	if (!pfmemalloc_reserve)
3336675becceSMel Gorman 		return true;
3337675becceSMel Gorman 
33385515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
33395515061dSMel Gorman 
33405515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
33415515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
334297a225e6SJoonsoo Kim 		if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
334397a225e6SJoonsoo Kim 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
33445644e1fbSQian Cai 
33455515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
33465515061dSMel Gorman 	}
33475515061dSMel Gorman 
33485515061dSMel Gorman 	return wmark_ok;
33495515061dSMel Gorman }
33505515061dSMel Gorman 
33515515061dSMel Gorman /*
33525515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
33535515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
33545515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
335550694c28SMel Gorman  * when the low watermark is reached.
335650694c28SMel Gorman  *
335750694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
335850694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
33595515061dSMel Gorman  */
336050694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
33615515061dSMel Gorman 					nodemask_t *nodemask)
33625515061dSMel Gorman {
3363675becceSMel Gorman 	struct zoneref *z;
33645515061dSMel Gorman 	struct zone *zone;
3365675becceSMel Gorman 	pg_data_t *pgdat = NULL;
33665515061dSMel Gorman 
33675515061dSMel Gorman 	/*
33685515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
33695515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
33705515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
33715515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
33725515061dSMel Gorman 	 * processes to block on log_wait_commit().
33735515061dSMel Gorman 	 */
33745515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
337550694c28SMel Gorman 		goto out;
337650694c28SMel Gorman 
337750694c28SMel Gorman 	/*
337850694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
337950694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
338050694c28SMel Gorman 	 */
338150694c28SMel Gorman 	if (fatal_signal_pending(current))
338250694c28SMel Gorman 		goto out;
33835515061dSMel Gorman 
3384675becceSMel Gorman 	/*
3385675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
3386675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3387675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
3388675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
3389675becceSMel Gorman 	 *
3390675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
3391675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
3392675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
3393675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
3394675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
3395675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
3396675becceSMel Gorman 	 * should make reasonable progress.
3397675becceSMel Gorman 	 */
3398675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
339917636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
3400675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
3401675becceSMel Gorman 			continue;
3402675becceSMel Gorman 
3403675becceSMel Gorman 		/* Throttle based on the first usable node */
34045515061dSMel Gorman 		pgdat = zone->zone_pgdat;
3405c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
340650694c28SMel Gorman 			goto out;
3407675becceSMel Gorman 		break;
3408675becceSMel Gorman 	}
3409675becceSMel Gorman 
3410675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
3411675becceSMel Gorman 	if (!pgdat)
3412675becceSMel Gorman 		goto out;
34135515061dSMel Gorman 
341468243e76SMel Gorman 	/* Account for the throttling */
341568243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
341668243e76SMel Gorman 
34175515061dSMel Gorman 	/*
34185515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
34195515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
34205515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
34215515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
34225515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
34235515061dSMel Gorman 	 * second before continuing.
34245515061dSMel Gorman 	 */
34255515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
34265515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3427c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
342850694c28SMel Gorman 
342950694c28SMel Gorman 		goto check_pending;
34305515061dSMel Gorman 	}
34315515061dSMel Gorman 
34325515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
34335515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3434c73322d0SJohannes Weiner 		allow_direct_reclaim(pgdat));
343550694c28SMel Gorman 
343650694c28SMel Gorman check_pending:
343750694c28SMel Gorman 	if (fatal_signal_pending(current))
343850694c28SMel Gorman 		return true;
343950694c28SMel Gorman 
344050694c28SMel Gorman out:
344150694c28SMel Gorman 	return false;
34425515061dSMel Gorman }
34435515061dSMel Gorman 
3444dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3445327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
344666e1707bSBalbir Singh {
344733906bc5SMel Gorman 	unsigned long nr_reclaimed;
344866e1707bSBalbir Singh 	struct scan_control sc = {
344922fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3450f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3451b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
3452ee814fe2SJohannes Weiner 		.order = order,
3453ee814fe2SJohannes Weiner 		.nodemask = nodemask,
3454ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
3455ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3456a6dc60f8SJohannes Weiner 		.may_unmap = 1,
34572e2e4259SKOSAKI Motohiro 		.may_swap = 1,
345866e1707bSBalbir Singh 	};
345966e1707bSBalbir Singh 
34605515061dSMel Gorman 	/*
3461bb451fdfSGreg Thelen 	 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3462bb451fdfSGreg Thelen 	 * Confirm they are large enough for max values.
3463bb451fdfSGreg Thelen 	 */
3464bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3465bb451fdfSGreg Thelen 	BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3466bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3467bb451fdfSGreg Thelen 
3468bb451fdfSGreg Thelen 	/*
346950694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
347050694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
347150694c28SMel Gorman 	 * point.
34725515061dSMel Gorman 	 */
3473f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
34745515061dSMel Gorman 		return 1;
34755515061dSMel Gorman 
34761732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
34773481c37fSYafang Shao 	trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
347833906bc5SMel Gorman 
34793115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
348033906bc5SMel Gorman 
348133906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
34821732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
348333906bc5SMel Gorman 
348433906bc5SMel Gorman 	return nr_reclaimed;
348566e1707bSBalbir Singh }
348666e1707bSBalbir Singh 
3487c255a458SAndrew Morton #ifdef CONFIG_MEMCG
348866e1707bSBalbir Singh 
3489d2e5fb92SMichal Hocko /* Only used by soft limit reclaim. Do not reuse for anything else. */
3490a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
34914e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
3492ef8f2327SMel Gorman 						pg_data_t *pgdat,
34930ae5e89cSYing Han 						unsigned long *nr_scanned)
34944e416953SBalbir Singh {
3495afaf07a6SJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
34964e416953SBalbir Singh 	struct scan_control sc = {
3497b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3498ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
34994e416953SBalbir Singh 		.may_writepage = !laptop_mode,
35004e416953SBalbir Singh 		.may_unmap = 1,
3501b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
35024e416953SBalbir Singh 		.may_swap = !noswap,
35034e416953SBalbir Singh 	};
35040ae5e89cSYing Han 
3505d2e5fb92SMichal Hocko 	WARN_ON_ONCE(!current->reclaim_state);
3506d2e5fb92SMichal Hocko 
35074e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
35084e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3509bdce6d9eSKOSAKI Motohiro 
35109e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
35113481c37fSYafang Shao 						      sc.gfp_mask);
3512bdce6d9eSKOSAKI Motohiro 
35134e416953SBalbir Singh 	/*
35144e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
35154e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3516a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
35174e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
35184e416953SBalbir Singh 	 * the priority and make it zero.
35194e416953SBalbir Singh 	 */
3520afaf07a6SJohannes Weiner 	shrink_lruvec(lruvec, &sc);
3521bdce6d9eSKOSAKI Motohiro 
3522bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3523bdce6d9eSKOSAKI Motohiro 
35240ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
35250308f7cfSYafang Shao 
35264e416953SBalbir Singh 	return sc.nr_reclaimed;
35274e416953SBalbir Singh }
35284e416953SBalbir Singh 
352972835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3530b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
35318c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3532b70a2a21SJohannes Weiner 					   bool may_swap)
353366e1707bSBalbir Singh {
3534bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3535499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
353666e1707bSBalbir Singh 	struct scan_control sc = {
3537b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
35387dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3539ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3540b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3541ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3542ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
354366e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3544a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3545b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3546a09ed5e0SYing Han 	};
3547fa40d1eeSShakeel Butt 	/*
3548fa40d1eeSShakeel Butt 	 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
3549fa40d1eeSShakeel Butt 	 * equal pressure on all the nodes. This is based on the assumption that
3550fa40d1eeSShakeel Butt 	 * the reclaim does not bail out early.
3551fa40d1eeSShakeel Butt 	 */
3552fa40d1eeSShakeel Butt 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
355366e1707bSBalbir Singh 
35541732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
35553481c37fSYafang Shao 	trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
3556499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3557eb414681SJohannes Weiner 
35583115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3559eb414681SJohannes Weiner 
3560499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3561bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
35621732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3563bdce6d9eSKOSAKI Motohiro 
3564bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
356566e1707bSBalbir Singh }
356666e1707bSBalbir Singh #endif
356766e1707bSBalbir Singh 
35681d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3569ef8f2327SMel Gorman 				struct scan_control *sc)
3570f16015fbSJohannes Weiner {
3571b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3572b91ac374SJohannes Weiner 	struct lruvec *lruvec;
3573b95a2f2dSJohannes Weiner 
3574b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3575b95a2f2dSJohannes Weiner 		return;
3576b95a2f2dSJohannes Weiner 
3577b91ac374SJohannes Weiner 	lruvec = mem_cgroup_lruvec(NULL, pgdat);
3578b91ac374SJohannes Weiner 	if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
3579b91ac374SJohannes Weiner 		return;
3580b91ac374SJohannes Weiner 
3581b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3582b95a2f2dSJohannes Weiner 	do {
3583b91ac374SJohannes Weiner 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
35841a93be0eSKonstantin Khlebnikov 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
35859e3b2f8cSKonstantin Khlebnikov 				   sc, LRU_ACTIVE_ANON);
3586b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3587b95a2f2dSJohannes Weiner 	} while (memcg);
3588f16015fbSJohannes Weiner }
3589f16015fbSJohannes Weiner 
359097a225e6SJoonsoo Kim static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
35911c30844dSMel Gorman {
35921c30844dSMel Gorman 	int i;
35931c30844dSMel Gorman 	struct zone *zone;
35941c30844dSMel Gorman 
35951c30844dSMel Gorman 	/*
35961c30844dSMel Gorman 	 * Check for watermark boosts top-down as the higher zones
35971c30844dSMel Gorman 	 * are more likely to be boosted. Both watermarks and boosts
35981eba09c1SRandy Dunlap 	 * should not be checked at the same time as reclaim would
35991c30844dSMel Gorman 	 * start prematurely when there is no boosting and a lower
36001c30844dSMel Gorman 	 * zone is balanced.
36011c30844dSMel Gorman 	 */
360297a225e6SJoonsoo Kim 	for (i = highest_zoneidx; i >= 0; i--) {
36031c30844dSMel Gorman 		zone = pgdat->node_zones + i;
36041c30844dSMel Gorman 		if (!managed_zone(zone))
36051c30844dSMel Gorman 			continue;
36061c30844dSMel Gorman 
36071c30844dSMel Gorman 		if (zone->watermark_boost)
36081c30844dSMel Gorman 			return true;
36091c30844dSMel Gorman 	}
36101c30844dSMel Gorman 
36111c30844dSMel Gorman 	return false;
36121c30844dSMel Gorman }
36131c30844dSMel Gorman 
3614e716f2ebSMel Gorman /*
3615e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
361697a225e6SJoonsoo Kim  * and highest_zoneidx
3617e716f2ebSMel Gorman  */
361897a225e6SJoonsoo Kim static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
361960cefed4SJohannes Weiner {
3620e716f2ebSMel Gorman 	int i;
3621e716f2ebSMel Gorman 	unsigned long mark = -1;
3622e716f2ebSMel Gorman 	struct zone *zone;
362360cefed4SJohannes Weiner 
36241c30844dSMel Gorman 	/*
36251c30844dSMel Gorman 	 * Check watermarks bottom-up as lower zones are more likely to
36261c30844dSMel Gorman 	 * meet watermarks.
36271c30844dSMel Gorman 	 */
362897a225e6SJoonsoo Kim 	for (i = 0; i <= highest_zoneidx; i++) {
3629e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
36306256c6b4SMel Gorman 
3631e716f2ebSMel Gorman 		if (!managed_zone(zone))
3632e716f2ebSMel Gorman 			continue;
3633e716f2ebSMel Gorman 
3634e716f2ebSMel Gorman 		mark = high_wmark_pages(zone);
363597a225e6SJoonsoo Kim 		if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
36366256c6b4SMel Gorman 			return true;
363760cefed4SJohannes Weiner 	}
363860cefed4SJohannes Weiner 
3639e716f2ebSMel Gorman 	/*
364097a225e6SJoonsoo Kim 	 * If a node has no populated zone within highest_zoneidx, it does not
3641e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3642e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3643e716f2ebSMel Gorman 	 */
3644e716f2ebSMel Gorman 	if (mark == -1)
3645e716f2ebSMel Gorman 		return true;
3646e716f2ebSMel Gorman 
3647e716f2ebSMel Gorman 	return false;
3648e716f2ebSMel Gorman }
3649e716f2ebSMel Gorman 
3650631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
3651631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
3652631b6e08SMel Gorman {
36531b05117dSJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
36541b05117dSJohannes Weiner 
36551b05117dSJohannes Weiner 	clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3656631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
3657631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3658631b6e08SMel Gorman }
3659631b6e08SMel Gorman 
36601741c877SMel Gorman /*
36615515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
36625515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
36635515061dSMel Gorman  *
36645515061dSMel Gorman  * Returns true if kswapd is ready to sleep
36655515061dSMel Gorman  */
366697a225e6SJoonsoo Kim static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
366797a225e6SJoonsoo Kim 				int highest_zoneidx)
3668f50de2d3SMel Gorman {
36695515061dSMel Gorman 	/*
36709e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3671c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
36729e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
36739e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
36749e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
36759e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
36769e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
36779e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
36789e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
36799e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
36809e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
36815515061dSMel Gorman 	 */
36829e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
36839e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3684f50de2d3SMel Gorman 
3685c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3686c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3687c73322d0SJohannes Weiner 		return true;
3688c73322d0SJohannes Weiner 
368997a225e6SJoonsoo Kim 	if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
3690631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
3691333b0a45SShantanu Goel 		return true;
36921d82de61SMel Gorman 	}
36931d82de61SMel Gorman 
3694333b0a45SShantanu Goel 	return false;
3695f50de2d3SMel Gorman }
3696f50de2d3SMel Gorman 
36971da177e4SLinus Torvalds /*
36981d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
36991d82de61SMel Gorman  * zone that is currently unbalanced.
3700b8e83b94SMel Gorman  *
3701b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3702283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3703283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
370475485363SMel Gorman  */
37051d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3706accf6242SVlastimil Babka 			       struct scan_control *sc)
370775485363SMel Gorman {
37081d82de61SMel Gorman 	struct zone *zone;
37091d82de61SMel Gorman 	int z;
371075485363SMel Gorman 
37111d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
37121d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3713970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
37141d82de61SMel Gorman 		zone = pgdat->node_zones + z;
37156aa303deSMel Gorman 		if (!managed_zone(zone))
37161d82de61SMel Gorman 			continue;
37177c954f6dSMel Gorman 
37181d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
37197c954f6dSMel Gorman 	}
37207c954f6dSMel Gorman 
37211d82de61SMel Gorman 	/*
37221d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
37231d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
37241d82de61SMel Gorman 	 */
3725970a39a3SMel Gorman 	shrink_node(pgdat, sc);
37261d82de61SMel Gorman 
37271d82de61SMel Gorman 	/*
37281d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
37291d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
37301d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
37311d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
37321d82de61SMel Gorman 	 * can direct reclaim/compact.
37331d82de61SMel Gorman 	 */
37349861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
37351d82de61SMel Gorman 		sc->order = 0;
37361d82de61SMel Gorman 
3737b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
373875485363SMel Gorman }
373975485363SMel Gorman 
3740c49c2c47SMel Gorman /* Page allocator PCP high watermark is lowered if reclaim is active. */
3741c49c2c47SMel Gorman static inline void
3742c49c2c47SMel Gorman update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
3743c49c2c47SMel Gorman {
3744c49c2c47SMel Gorman 	int i;
3745c49c2c47SMel Gorman 	struct zone *zone;
3746c49c2c47SMel Gorman 
3747c49c2c47SMel Gorman 	for (i = 0; i <= highest_zoneidx; i++) {
3748c49c2c47SMel Gorman 		zone = pgdat->node_zones + i;
3749c49c2c47SMel Gorman 
3750c49c2c47SMel Gorman 		if (!managed_zone(zone))
3751c49c2c47SMel Gorman 			continue;
3752c49c2c47SMel Gorman 
3753c49c2c47SMel Gorman 		if (active)
3754c49c2c47SMel Gorman 			set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
3755c49c2c47SMel Gorman 		else
3756c49c2c47SMel Gorman 			clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
3757c49c2c47SMel Gorman 	}
3758c49c2c47SMel Gorman }
3759c49c2c47SMel Gorman 
3760c49c2c47SMel Gorman static inline void
3761c49c2c47SMel Gorman set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
3762c49c2c47SMel Gorman {
3763c49c2c47SMel Gorman 	update_reclaim_active(pgdat, highest_zoneidx, true);
3764c49c2c47SMel Gorman }
3765c49c2c47SMel Gorman 
3766c49c2c47SMel Gorman static inline void
3767c49c2c47SMel Gorman clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
3768c49c2c47SMel Gorman {
3769c49c2c47SMel Gorman 	update_reclaim_active(pgdat, highest_zoneidx, false);
3770c49c2c47SMel Gorman }
3771c49c2c47SMel Gorman 
377275485363SMel Gorman /*
37731d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
37741d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
37751d82de61SMel Gorman  * balanced.
37761da177e4SLinus Torvalds  *
37771d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
37781da177e4SLinus Torvalds  *
37791da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
378041858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
37818bb4e7a2SWei Yang  * found to have free_pages <= high_wmark_pages(zone), any page in that zone
37821d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
37831d82de61SMel Gorman  * balanced.
37841da177e4SLinus Torvalds  */
378597a225e6SJoonsoo Kim static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
37861da177e4SLinus Torvalds {
37871da177e4SLinus Torvalds 	int i;
37880608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
37890608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3790eb414681SJohannes Weiner 	unsigned long pflags;
37911c30844dSMel Gorman 	unsigned long nr_boost_reclaim;
37921c30844dSMel Gorman 	unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
37931c30844dSMel Gorman 	bool boosted;
37941d82de61SMel Gorman 	struct zone *zone;
3795179e9639SAndrew Morton 	struct scan_control sc = {
3796179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3797ee814fe2SJohannes Weiner 		.order = order,
3798a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3799179e9639SAndrew Morton 	};
380093781325SOmar Sandoval 
38011732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
3802eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
380393781325SOmar Sandoval 	__fs_reclaim_acquire();
380493781325SOmar Sandoval 
3805f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
38061da177e4SLinus Torvalds 
38071c30844dSMel Gorman 	/*
38081c30844dSMel Gorman 	 * Account for the reclaim boost. Note that the zone boost is left in
38091c30844dSMel Gorman 	 * place so that parallel allocations that are near the watermark will
38101c30844dSMel Gorman 	 * stall or direct reclaim until kswapd is finished.
38111c30844dSMel Gorman 	 */
38121c30844dSMel Gorman 	nr_boost_reclaim = 0;
381397a225e6SJoonsoo Kim 	for (i = 0; i <= highest_zoneidx; i++) {
38141c30844dSMel Gorman 		zone = pgdat->node_zones + i;
38151c30844dSMel Gorman 		if (!managed_zone(zone))
38161c30844dSMel Gorman 			continue;
38171c30844dSMel Gorman 
38181c30844dSMel Gorman 		nr_boost_reclaim += zone->watermark_boost;
38191c30844dSMel Gorman 		zone_boosts[i] = zone->watermark_boost;
38201c30844dSMel Gorman 	}
38211c30844dSMel Gorman 	boosted = nr_boost_reclaim;
38221c30844dSMel Gorman 
38231c30844dSMel Gorman restart:
3824c49c2c47SMel Gorman 	set_reclaim_active(pgdat, highest_zoneidx);
38251c30844dSMel Gorman 	sc.priority = DEF_PRIORITY;
38269e3b2f8cSKonstantin Khlebnikov 	do {
3827c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
3828b8e83b94SMel Gorman 		bool raise_priority = true;
38291c30844dSMel Gorman 		bool balanced;
383093781325SOmar Sandoval 		bool ret;
3831b8e83b94SMel Gorman 
383297a225e6SJoonsoo Kim 		sc.reclaim_idx = highest_zoneidx;
38331da177e4SLinus Torvalds 
383486c79f6bSMel Gorman 		/*
383584c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
383684c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
383784c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
383884c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
383984c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
384084c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
384184c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
384284c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
384386c79f6bSMel Gorman 		 */
384486c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
384586c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
384686c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
38476aa303deSMel Gorman 				if (!managed_zone(zone))
384886c79f6bSMel Gorman 					continue;
384986c79f6bSMel Gorman 
3850970a39a3SMel Gorman 				sc.reclaim_idx = i;
385186c79f6bSMel Gorman 				break;
385286c79f6bSMel Gorman 			}
385386c79f6bSMel Gorman 		}
385486c79f6bSMel Gorman 
385586c79f6bSMel Gorman 		/*
38561c30844dSMel Gorman 		 * If the pgdat is imbalanced then ignore boosting and preserve
38571c30844dSMel Gorman 		 * the watermarks for a later time and restart. Note that the
38581c30844dSMel Gorman 		 * zone watermarks will be still reset at the end of balancing
38591c30844dSMel Gorman 		 * on the grounds that the normal reclaim should be enough to
38601c30844dSMel Gorman 		 * re-evaluate if boosting is required when kswapd next wakes.
386186c79f6bSMel Gorman 		 */
386297a225e6SJoonsoo Kim 		balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
38631c30844dSMel Gorman 		if (!balanced && nr_boost_reclaim) {
38641c30844dSMel Gorman 			nr_boost_reclaim = 0;
38651c30844dSMel Gorman 			goto restart;
38661c30844dSMel Gorman 		}
38671c30844dSMel Gorman 
38681c30844dSMel Gorman 		/*
38691c30844dSMel Gorman 		 * If boosting is not active then only reclaim if there are no
38701c30844dSMel Gorman 		 * eligible zones. Note that sc.reclaim_idx is not used as
38711c30844dSMel Gorman 		 * buffer_heads_over_limit may have adjusted it.
38721c30844dSMel Gorman 		 */
38731c30844dSMel Gorman 		if (!nr_boost_reclaim && balanced)
38741da177e4SLinus Torvalds 			goto out;
3875e1dbeda6SAndrew Morton 
38761c30844dSMel Gorman 		/* Limit the priority of boosting to avoid reclaim writeback */
38771c30844dSMel Gorman 		if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
38781c30844dSMel Gorman 			raise_priority = false;
38791c30844dSMel Gorman 
38801c30844dSMel Gorman 		/*
38811c30844dSMel Gorman 		 * Do not writeback or swap pages for boosted reclaim. The
38821c30844dSMel Gorman 		 * intent is to relieve pressure not issue sub-optimal IO
38831c30844dSMel Gorman 		 * from reclaim context. If no pages are reclaimed, the
38841c30844dSMel Gorman 		 * reclaim will be aborted.
38851c30844dSMel Gorman 		 */
38861c30844dSMel Gorman 		sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
38871c30844dSMel Gorman 		sc.may_swap = !nr_boost_reclaim;
38881c30844dSMel Gorman 
38891da177e4SLinus Torvalds 		/*
38901d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
38911d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
38921d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
38931d82de61SMel Gorman 		 * about consistent aging.
38941d82de61SMel Gorman 		 */
3895ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
38961d82de61SMel Gorman 
38971d82de61SMel Gorman 		/*
3898b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3899b7ea3c41SMel Gorman 		 * even in laptop mode.
3900b7ea3c41SMel Gorman 		 */
3901047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
3902b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3903b7ea3c41SMel Gorman 
39041d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
39051da177e4SLinus Torvalds 		sc.nr_scanned = 0;
39060608f43dSAndrew Morton 		nr_soft_scanned = 0;
3907ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
39081d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
39090608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
39100608f43dSAndrew Morton 
391132a4330dSRik van Riel 		/*
39121d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
39131d82de61SMel Gorman 		 * enough pages are already being scanned that that high
39141d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
391532a4330dSRik van Riel 		 */
3916970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3917b8e83b94SMel Gorman 			raise_priority = false;
3918d7868daeSMel Gorman 
39195515061dSMel Gorman 		/*
39205515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
39215515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
39225515061dSMel Gorman 		 * able to safely make forward progress. Wake them
39235515061dSMel Gorman 		 */
39245515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3925c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
3926cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
39275515061dSMel Gorman 
3928b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
392993781325SOmar Sandoval 		__fs_reclaim_release();
393093781325SOmar Sandoval 		ret = try_to_freeze();
393193781325SOmar Sandoval 		__fs_reclaim_acquire();
393293781325SOmar Sandoval 		if (ret || kthread_should_stop())
3933b8e83b94SMel Gorman 			break;
3934b8e83b94SMel Gorman 
3935b8e83b94SMel Gorman 		/*
3936b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3937b8e83b94SMel Gorman 		 * progress in reclaiming pages
3938b8e83b94SMel Gorman 		 */
3939c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
39401c30844dSMel Gorman 		nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
39411c30844dSMel Gorman 
39421c30844dSMel Gorman 		/*
39431c30844dSMel Gorman 		 * If reclaim made no progress for a boost, stop reclaim as
39441c30844dSMel Gorman 		 * IO cannot be queued and it could be an infinite loop in
39451c30844dSMel Gorman 		 * extreme circumstances.
39461c30844dSMel Gorman 		 */
39471c30844dSMel Gorman 		if (nr_boost_reclaim && !nr_reclaimed)
39481c30844dSMel Gorman 			break;
39491c30844dSMel Gorman 
3950c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
3951b8e83b94SMel Gorman 			sc.priority--;
39521d82de61SMel Gorman 	} while (sc.priority >= 1);
39531da177e4SLinus Torvalds 
3954c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
3955c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
3956c73322d0SJohannes Weiner 
3957b8e83b94SMel Gorman out:
3958c49c2c47SMel Gorman 	clear_reclaim_active(pgdat, highest_zoneidx);
3959c49c2c47SMel Gorman 
39601c30844dSMel Gorman 	/* If reclaim was boosted, account for the reclaim done in this pass */
39611c30844dSMel Gorman 	if (boosted) {
39621c30844dSMel Gorman 		unsigned long flags;
39631c30844dSMel Gorman 
396497a225e6SJoonsoo Kim 		for (i = 0; i <= highest_zoneidx; i++) {
39651c30844dSMel Gorman 			if (!zone_boosts[i])
39661c30844dSMel Gorman 				continue;
39671c30844dSMel Gorman 
39681c30844dSMel Gorman 			/* Increments are under the zone lock */
39691c30844dSMel Gorman 			zone = pgdat->node_zones + i;
39701c30844dSMel Gorman 			spin_lock_irqsave(&zone->lock, flags);
39711c30844dSMel Gorman 			zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
39721c30844dSMel Gorman 			spin_unlock_irqrestore(&zone->lock, flags);
39731c30844dSMel Gorman 		}
39741c30844dSMel Gorman 
39751c30844dSMel Gorman 		/*
39761c30844dSMel Gorman 		 * As there is now likely space, wakeup kcompact to defragment
39771c30844dSMel Gorman 		 * pageblocks.
39781c30844dSMel Gorman 		 */
397997a225e6SJoonsoo Kim 		wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
39801c30844dSMel Gorman 	}
39811c30844dSMel Gorman 
39822a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
398393781325SOmar Sandoval 	__fs_reclaim_release();
3984eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
39851732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3986e5ca8071SYafang Shao 
39870abdee2bSMel Gorman 	/*
39881d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
39891d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
39901d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
39911d82de61SMel Gorman 	 * remain at the higher level.
39920abdee2bSMel Gorman 	 */
39931d82de61SMel Gorman 	return sc.order;
39941da177e4SLinus Torvalds }
39951da177e4SLinus Torvalds 
3996e716f2ebSMel Gorman /*
399797a225e6SJoonsoo Kim  * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
399897a225e6SJoonsoo Kim  * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
399997a225e6SJoonsoo Kim  * not a valid index then either kswapd runs for first time or kswapd couldn't
400097a225e6SJoonsoo Kim  * sleep after previous reclaim attempt (node is still unbalanced). In that
400197a225e6SJoonsoo Kim  * case return the zone index of the previous kswapd reclaim cycle.
4002e716f2ebSMel Gorman  */
400397a225e6SJoonsoo Kim static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
400497a225e6SJoonsoo Kim 					   enum zone_type prev_highest_zoneidx)
4005e716f2ebSMel Gorman {
400697a225e6SJoonsoo Kim 	enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
40075644e1fbSQian Cai 
400897a225e6SJoonsoo Kim 	return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
4009e716f2ebSMel Gorman }
4010e716f2ebSMel Gorman 
401138087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
401297a225e6SJoonsoo Kim 				unsigned int highest_zoneidx)
4013f0bc0a60SKOSAKI Motohiro {
4014f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
4015f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
4016f0bc0a60SKOSAKI Motohiro 
4017f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
4018f0bc0a60SKOSAKI Motohiro 		return;
4019f0bc0a60SKOSAKI Motohiro 
4020f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
4021f0bc0a60SKOSAKI Motohiro 
4022333b0a45SShantanu Goel 	/*
4023333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
4024333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
4025333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
4026333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
4027333b0a45SShantanu Goel 	 * succeed.
4028333b0a45SShantanu Goel 	 */
402997a225e6SJoonsoo Kim 	if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
4030fd901c95SVlastimil Babka 		/*
4031fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
4032fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
4033fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
4034fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
4035fd901c95SVlastimil Babka 		 */
4036fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
4037fd901c95SVlastimil Babka 
4038fd901c95SVlastimil Babka 		/*
4039fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
4040fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
4041fd901c95SVlastimil Babka 		 */
404297a225e6SJoonsoo Kim 		wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
4043fd901c95SVlastimil Babka 
4044f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
404538087d9bSMel Gorman 
404638087d9bSMel Gorman 		/*
404797a225e6SJoonsoo Kim 		 * If woken prematurely then reset kswapd_highest_zoneidx and
404838087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
404938087d9bSMel Gorman 		 * the previous request that slept prematurely.
405038087d9bSMel Gorman 		 */
405138087d9bSMel Gorman 		if (remaining) {
405297a225e6SJoonsoo Kim 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
405397a225e6SJoonsoo Kim 					kswapd_highest_zoneidx(pgdat,
405497a225e6SJoonsoo Kim 							highest_zoneidx));
40555644e1fbSQian Cai 
40565644e1fbSQian Cai 			if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
40575644e1fbSQian Cai 				WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
405838087d9bSMel Gorman 		}
405938087d9bSMel Gorman 
4060f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
4061f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
4062f0bc0a60SKOSAKI Motohiro 	}
4063f0bc0a60SKOSAKI Motohiro 
4064f0bc0a60SKOSAKI Motohiro 	/*
4065f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
4066f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
4067f0bc0a60SKOSAKI Motohiro 	 */
4068d9f21d42SMel Gorman 	if (!remaining &&
406997a225e6SJoonsoo Kim 	    prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
4070f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
4071f0bc0a60SKOSAKI Motohiro 
4072f0bc0a60SKOSAKI Motohiro 		/*
4073f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
4074f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
4075f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
4076f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
4077f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
4078f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
4079f0bc0a60SKOSAKI Motohiro 		 */
4080f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
40811c7e7f6cSAaditya Kumar 
40821c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
4083f0bc0a60SKOSAKI Motohiro 			schedule();
40841c7e7f6cSAaditya Kumar 
4085f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
4086f0bc0a60SKOSAKI Motohiro 	} else {
4087f0bc0a60SKOSAKI Motohiro 		if (remaining)
4088f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
4089f0bc0a60SKOSAKI Motohiro 		else
4090f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
4091f0bc0a60SKOSAKI Motohiro 	}
4092f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
4093f0bc0a60SKOSAKI Motohiro }
4094f0bc0a60SKOSAKI Motohiro 
40951da177e4SLinus Torvalds /*
40961da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
40971da177e4SLinus Torvalds  * from the init process.
40981da177e4SLinus Torvalds  *
40991da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
41001da177e4SLinus Torvalds  * free memory available even if there is no other activity
41011da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
41021da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
41031da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
41041da177e4SLinus Torvalds  *
41051da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
41061da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
41071da177e4SLinus Torvalds  */
41081da177e4SLinus Torvalds static int kswapd(void *p)
41091da177e4SLinus Torvalds {
4110e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
411197a225e6SJoonsoo Kim 	unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
41121da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t *)p;
41131da177e4SLinus Torvalds 	struct task_struct *tsk = current;
4114a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
41151da177e4SLinus Torvalds 
4116174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
4117c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
41181da177e4SLinus Torvalds 
41191da177e4SLinus Torvalds 	/*
41201da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
41211da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
41221da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
41231da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
41241da177e4SLinus Torvalds 	 *
41251da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
41261da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
41271da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
41281da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
41291da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
41301da177e4SLinus Torvalds 	 */
4131930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
413283144186SRafael J. Wysocki 	set_freezable();
41331da177e4SLinus Torvalds 
41345644e1fbSQian Cai 	WRITE_ONCE(pgdat->kswapd_order, 0);
413597a225e6SJoonsoo Kim 	WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
41361da177e4SLinus Torvalds 	for ( ; ; ) {
41376f6313d4SJeff Liu 		bool ret;
41383e1d1d28SChristoph Lameter 
41395644e1fbSQian Cai 		alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
414097a225e6SJoonsoo Kim 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
414197a225e6SJoonsoo Kim 							highest_zoneidx);
4142e716f2ebSMel Gorman 
414338087d9bSMel Gorman kswapd_try_sleep:
414438087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
414597a225e6SJoonsoo Kim 					highest_zoneidx);
4146215ddd66SMel Gorman 
414797a225e6SJoonsoo Kim 		/* Read the new order and highest_zoneidx */
41482b47a24cSLukas Bulwahn 		alloc_order = READ_ONCE(pgdat->kswapd_order);
414997a225e6SJoonsoo Kim 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
415097a225e6SJoonsoo Kim 							highest_zoneidx);
41515644e1fbSQian Cai 		WRITE_ONCE(pgdat->kswapd_order, 0);
415297a225e6SJoonsoo Kim 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
41531da177e4SLinus Torvalds 
41548fe23e05SDavid Rientjes 		ret = try_to_freeze();
41558fe23e05SDavid Rientjes 		if (kthread_should_stop())
41568fe23e05SDavid Rientjes 			break;
41578fe23e05SDavid Rientjes 
41588fe23e05SDavid Rientjes 		/*
41598fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
41608fe23e05SDavid Rientjes 		 * after returning from the refrigerator
4161b1296cc4SRafael J. Wysocki 		 */
416238087d9bSMel Gorman 		if (ret)
416338087d9bSMel Gorman 			continue;
41641d82de61SMel Gorman 
416538087d9bSMel Gorman 		/*
416638087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
416738087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
416838087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
416938087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
417038087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
417138087d9bSMel Gorman 		 * request (alloc_order).
417238087d9bSMel Gorman 		 */
417397a225e6SJoonsoo Kim 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
4174e5146b12SMel Gorman 						alloc_order);
417597a225e6SJoonsoo Kim 		reclaim_order = balance_pgdat(pgdat, alloc_order,
417697a225e6SJoonsoo Kim 						highest_zoneidx);
417738087d9bSMel Gorman 		if (reclaim_order < alloc_order)
417838087d9bSMel Gorman 			goto kswapd_try_sleep;
417933906bc5SMel Gorman 	}
4180b0a8cc58STakamori Yamaguchi 
418171abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
418271abdc15SJohannes Weiner 
41831da177e4SLinus Torvalds 	return 0;
41841da177e4SLinus Torvalds }
41851da177e4SLinus Torvalds 
41861da177e4SLinus Torvalds /*
41875ecd9d40SDavid Rientjes  * A zone is low on free memory or too fragmented for high-order memory.  If
41885ecd9d40SDavid Rientjes  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
41895ecd9d40SDavid Rientjes  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
41905ecd9d40SDavid Rientjes  * has failed or is not needed, still wake up kcompactd if only compaction is
41915ecd9d40SDavid Rientjes  * needed.
41921da177e4SLinus Torvalds  */
41935ecd9d40SDavid Rientjes void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
419497a225e6SJoonsoo Kim 		   enum zone_type highest_zoneidx)
41951da177e4SLinus Torvalds {
41961da177e4SLinus Torvalds 	pg_data_t *pgdat;
41975644e1fbSQian Cai 	enum zone_type curr_idx;
41981da177e4SLinus Torvalds 
41996aa303deSMel Gorman 	if (!managed_zone(zone))
42001da177e4SLinus Torvalds 		return;
42011da177e4SLinus Torvalds 
42025ecd9d40SDavid Rientjes 	if (!cpuset_zone_allowed(zone, gfp_flags))
42031da177e4SLinus Torvalds 		return;
4204dffcac2cSShakeel Butt 
42055644e1fbSQian Cai 	pgdat = zone->zone_pgdat;
420697a225e6SJoonsoo Kim 	curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
42075644e1fbSQian Cai 
420897a225e6SJoonsoo Kim 	if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
420997a225e6SJoonsoo Kim 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
42105644e1fbSQian Cai 
42115644e1fbSQian Cai 	if (READ_ONCE(pgdat->kswapd_order) < order)
42125644e1fbSQian Cai 		WRITE_ONCE(pgdat->kswapd_order, order);
42135644e1fbSQian Cai 
42148d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
42151da177e4SLinus Torvalds 		return;
4216e1a55637SMel Gorman 
42175ecd9d40SDavid Rientjes 	/* Hopeless node, leave it to direct reclaim if possible */
42185ecd9d40SDavid Rientjes 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
421997a225e6SJoonsoo Kim 	    (pgdat_balanced(pgdat, order, highest_zoneidx) &&
422097a225e6SJoonsoo Kim 	     !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
42215ecd9d40SDavid Rientjes 		/*
42225ecd9d40SDavid Rientjes 		 * There may be plenty of free memory available, but it's too
42235ecd9d40SDavid Rientjes 		 * fragmented for high-order allocations.  Wake up kcompactd
42245ecd9d40SDavid Rientjes 		 * and rely on compaction_suitable() to determine if it's
42255ecd9d40SDavid Rientjes 		 * needed.  If it fails, it will defer subsequent attempts to
42265ecd9d40SDavid Rientjes 		 * ratelimit its work.
42275ecd9d40SDavid Rientjes 		 */
42285ecd9d40SDavid Rientjes 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
422997a225e6SJoonsoo Kim 			wakeup_kcompactd(pgdat, order, highest_zoneidx);
4230c73322d0SJohannes Weiner 		return;
42315ecd9d40SDavid Rientjes 	}
4232c73322d0SJohannes Weiner 
423397a225e6SJoonsoo Kim 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
42345ecd9d40SDavid Rientjes 				      gfp_flags);
42358d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
42361da177e4SLinus Torvalds }
42371da177e4SLinus Torvalds 
4238c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
42391da177e4SLinus Torvalds /*
42407b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
4241d6277db4SRafael J. Wysocki  * freed pages.
4242d6277db4SRafael J. Wysocki  *
4243d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
4244d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
4245d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
42461da177e4SLinus Torvalds  */
42477b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
42481da177e4SLinus Torvalds {
4249d6277db4SRafael J. Wysocki 	struct scan_control sc = {
42507b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
4251ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
4252b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
42539e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
4254ee814fe2SJohannes Weiner 		.may_writepage = 1,
4255ee814fe2SJohannes Weiner 		.may_unmap = 1,
4256ee814fe2SJohannes Weiner 		.may_swap = 1,
4257ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
42581da177e4SLinus Torvalds 	};
42597b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
42607b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
4261499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
42621da177e4SLinus Torvalds 
4263d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
426493781325SOmar Sandoval 	noreclaim_flag = memalloc_noreclaim_save();
42651732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
4266d6277db4SRafael J. Wysocki 
42673115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4268d6277db4SRafael J. Wysocki 
42691732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
4270499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
427193781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4272d6277db4SRafael J. Wysocki 
42737b51755cSKOSAKI Motohiro 	return nr_reclaimed;
42741da177e4SLinus Torvalds }
4275c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
42761da177e4SLinus Torvalds 
42773218ae14SYasunori Goto /*
42783218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
42793218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
42803218ae14SYasunori Goto  */
42813218ae14SYasunori Goto int kswapd_run(int nid)
42823218ae14SYasunori Goto {
42833218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
42843218ae14SYasunori Goto 	int ret = 0;
42853218ae14SYasunori Goto 
42863218ae14SYasunori Goto 	if (pgdat->kswapd)
42873218ae14SYasunori Goto 		return 0;
42883218ae14SYasunori Goto 
42893218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
42903218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
42913218ae14SYasunori Goto 		/* failure at boot is fatal */
4292c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
4293d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
4294d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
4295d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
42963218ae14SYasunori Goto 	}
42973218ae14SYasunori Goto 	return ret;
42983218ae14SYasunori Goto }
42993218ae14SYasunori Goto 
43008fe23e05SDavid Rientjes /*
4301d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
4302bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
43038fe23e05SDavid Rientjes  */
43048fe23e05SDavid Rientjes void kswapd_stop(int nid)
43058fe23e05SDavid Rientjes {
43068fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
43078fe23e05SDavid Rientjes 
4308d8adde17SJiang Liu 	if (kswapd) {
43098fe23e05SDavid Rientjes 		kthread_stop(kswapd);
4310d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
4311d8adde17SJiang Liu 	}
43128fe23e05SDavid Rientjes }
43138fe23e05SDavid Rientjes 
43141da177e4SLinus Torvalds static int __init kswapd_init(void)
43151da177e4SLinus Torvalds {
43166b700b5bSWei Yang 	int nid;
431769e05944SAndrew Morton 
43181da177e4SLinus Torvalds 	swap_setup();
431948fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
43203218ae14SYasunori Goto  		kswapd_run(nid);
43211da177e4SLinus Torvalds 	return 0;
43221da177e4SLinus Torvalds }
43231da177e4SLinus Torvalds 
43241da177e4SLinus Torvalds module_init(kswapd_init)
43259eeff239SChristoph Lameter 
43269eeff239SChristoph Lameter #ifdef CONFIG_NUMA
43279eeff239SChristoph Lameter /*
4328a5f5f91dSMel Gorman  * Node reclaim mode
43299eeff239SChristoph Lameter  *
4330a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
43319eeff239SChristoph Lameter  * the watermarks.
43329eeff239SChristoph Lameter  */
4333a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
43349eeff239SChristoph Lameter 
433551998364SDave Hansen /*
4336a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
4337a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
4338a92f7126SChristoph Lameter  * a zone.
4339a92f7126SChristoph Lameter  */
4340a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
4341a92f7126SChristoph Lameter 
43429eeff239SChristoph Lameter /*
4343a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
43449614634fSChristoph Lameter  * occur.
43459614634fSChristoph Lameter  */
43469614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
43479614634fSChristoph Lameter 
43489614634fSChristoph Lameter /*
43490ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
43500ff38490SChristoph Lameter  * slab reclaim needs to occur.
43510ff38490SChristoph Lameter  */
43520ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
43530ff38490SChristoph Lameter 
435411fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
435590afa5deSMel Gorman {
435611fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
435711fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
435811fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
435990afa5deSMel Gorman 
436090afa5deSMel Gorman 	/*
436190afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
436290afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
436390afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
436490afa5deSMel Gorman 	 */
436590afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
436690afa5deSMel Gorman }
436790afa5deSMel Gorman 
436890afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4369a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
437090afa5deSMel Gorman {
4371d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
4372d031a157SAlexandru Moise 	unsigned long delta = 0;
437390afa5deSMel Gorman 
437490afa5deSMel Gorman 	/*
437595bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
437690afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
437711fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
437890afa5deSMel Gorman 	 * a better estimate
437990afa5deSMel Gorman 	 */
4380a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
4381a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
438290afa5deSMel Gorman 	else
4383a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
438490afa5deSMel Gorman 
438590afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
4386a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
4387a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
438890afa5deSMel Gorman 
438990afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
439090afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
439190afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
439290afa5deSMel Gorman 
439390afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
439490afa5deSMel Gorman }
439590afa5deSMel Gorman 
43960ff38490SChristoph Lameter /*
4397a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
43989eeff239SChristoph Lameter  */
4399a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
44009eeff239SChristoph Lameter {
44017fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
440269e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
44039eeff239SChristoph Lameter 	struct task_struct *p = current;
4404499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
4405179e9639SAndrew Morton 	struct scan_control sc = {
440662b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4407f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
4408bd2f6199SJohannes Weiner 		.order = order,
4409a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
4410a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4411a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4412ee814fe2SJohannes Weiner 		.may_swap = 1,
4413f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
4414179e9639SAndrew Morton 	};
44159eeff239SChristoph Lameter 
4416132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4417132bb8cfSYafang Shao 					   sc.gfp_mask);
4418132bb8cfSYafang Shao 
44199eeff239SChristoph Lameter 	cond_resched();
442093781325SOmar Sandoval 	fs_reclaim_acquire(sc.gfp_mask);
4421d4f7796eSChristoph Lameter 	/*
442295bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4423d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
442495bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
4425d4f7796eSChristoph Lameter 	 */
4426499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
4427499118e9SVlastimil Babka 	p->flags |= PF_SWAPWRITE;
44281732d2b0SAndrew Morton 	set_task_reclaim_state(p, &sc.reclaim_state);
4429c84db23cSChristoph Lameter 
4430a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
4431a92f7126SChristoph Lameter 		/*
4432894befecSAndrey Ryabinin 		 * Free memory by calling shrink node with increasing
44330ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
4434a92f7126SChristoph Lameter 		 */
4435a92f7126SChristoph Lameter 		do {
4436970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
44379e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
44380ff38490SChristoph Lameter 	}
4439a92f7126SChristoph Lameter 
44401732d2b0SAndrew Morton 	set_task_reclaim_state(p, NULL);
4441499118e9SVlastimil Babka 	current->flags &= ~PF_SWAPWRITE;
4442499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
444393781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4444132bb8cfSYafang Shao 
4445132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4446132bb8cfSYafang Shao 
4447a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
44489eeff239SChristoph Lameter }
4449179e9639SAndrew Morton 
4450a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4451179e9639SAndrew Morton {
4452d773ed6bSDavid Rientjes 	int ret;
4453179e9639SAndrew Morton 
4454179e9639SAndrew Morton 	/*
4455a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
44560ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
445734aa1330SChristoph Lameter 	 *
44589614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
44599614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
4460a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
4461a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
44629614634fSChristoph Lameter 	 * unmapped file backed pages.
4463179e9639SAndrew Morton 	 */
4464a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4465d42f3245SRoman Gushchin 	    node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
4466d42f3245SRoman Gushchin 	    pgdat->min_slab_pages)
4467a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
4468179e9639SAndrew Morton 
4469179e9639SAndrew Morton 	/*
4470d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
4471179e9639SAndrew Morton 	 */
4472d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4473a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4474179e9639SAndrew Morton 
4475179e9639SAndrew Morton 	/*
4476a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
4477179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
4478179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
4479179e9639SAndrew Morton 	 * as wide as possible.
4480179e9639SAndrew Morton 	 */
4481a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4482a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4483d773ed6bSDavid Rientjes 
4484a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4485a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4486fa5e084eSMel Gorman 
4487a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
4488a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4489d773ed6bSDavid Rientjes 
449024cf7251SMel Gorman 	if (!ret)
449124cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
449224cf7251SMel Gorman 
4493d773ed6bSDavid Rientjes 	return ret;
4494179e9639SAndrew Morton }
44959eeff239SChristoph Lameter #endif
4496894bc310SLee Schermerhorn 
449789e004eaSLee Schermerhorn /**
449864e3d12fSKuo-Hsin Yang  * check_move_unevictable_pages - check pages for evictability and move to
449964e3d12fSKuo-Hsin Yang  * appropriate zone lru list
450064e3d12fSKuo-Hsin Yang  * @pvec: pagevec with lru pages to check
450189e004eaSLee Schermerhorn  *
450264e3d12fSKuo-Hsin Yang  * Checks pages for evictability, if an evictable page is in the unevictable
450364e3d12fSKuo-Hsin Yang  * lru list, moves it to the appropriate evictable lru list. This function
450464e3d12fSKuo-Hsin Yang  * should be only used for lru pages.
450589e004eaSLee Schermerhorn  */
450664e3d12fSKuo-Hsin Yang void check_move_unevictable_pages(struct pagevec *pvec)
450789e004eaSLee Schermerhorn {
45086168d0daSAlex Shi 	struct lruvec *lruvec = NULL;
450924513264SHugh Dickins 	int pgscanned = 0;
451024513264SHugh Dickins 	int pgrescued = 0;
451189e004eaSLee Schermerhorn 	int i;
451289e004eaSLee Schermerhorn 
451364e3d12fSKuo-Hsin Yang 	for (i = 0; i < pvec->nr; i++) {
451464e3d12fSKuo-Hsin Yang 		struct page *page = pvec->pages[i];
45158d8869caSHugh Dickins 		int nr_pages;
451689e004eaSLee Schermerhorn 
45178d8869caSHugh Dickins 		if (PageTransTail(page))
45188d8869caSHugh Dickins 			continue;
45198d8869caSHugh Dickins 
45208d8869caSHugh Dickins 		nr_pages = thp_nr_pages(page);
45218d8869caSHugh Dickins 		pgscanned += nr_pages;
45228d8869caSHugh Dickins 
4523d25b5bd8SAlex Shi 		/* block memcg migration during page moving between lru */
4524d25b5bd8SAlex Shi 		if (!TestClearPageLRU(page))
4525d25b5bd8SAlex Shi 			continue;
4526d25b5bd8SAlex Shi 
45272a5e4e34SAlexander Duyck 		lruvec = relock_page_lruvec_irq(page, lruvec);
4528d25b5bd8SAlex Shi 		if (page_evictable(page) && PageUnevictable(page)) {
452946ae6b2cSYu Zhao 			del_page_from_lru_list(page, lruvec);
453024513264SHugh Dickins 			ClearPageUnevictable(page);
45313a9c9788SYu Zhao 			add_page_to_lru_list(page, lruvec);
45328d8869caSHugh Dickins 			pgrescued += nr_pages;
453389e004eaSLee Schermerhorn 		}
4534d25b5bd8SAlex Shi 		SetPageLRU(page);
453589e004eaSLee Schermerhorn 	}
453624513264SHugh Dickins 
45376168d0daSAlex Shi 	if (lruvec) {
453824513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
453924513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
45406168d0daSAlex Shi 		unlock_page_lruvec_irq(lruvec);
4541d25b5bd8SAlex Shi 	} else if (pgscanned) {
4542d25b5bd8SAlex Shi 		count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
454324513264SHugh Dickins 	}
454485046579SHugh Dickins }
454564e3d12fSKuo-Hsin Yang EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
4546