xref: /openbmc/linux/mm/vmscan.c (revision 476b30a0949aec865dcc64d4c14f621b1a8afd12)
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 
349*476b30a0SYang Shi 	if (mem_cgroup_disabled())
350*476b30a0SYang Shi 		return -ENOSYS;
351*476b30a0SYang 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 
400b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
40189b5fae5SJohannes Weiner {
402b5ead35eSJohannes Weiner 	return sc->target_mem_cgroup;
40389b5fae5SJohannes Weiner }
40497c9341fSTejun Heo 
40597c9341fSTejun Heo /**
406b5ead35eSJohannes Weiner  * writeback_throttling_sane - is the usual dirty throttling mechanism available?
40797c9341fSTejun Heo  * @sc: scan_control in question
40897c9341fSTejun Heo  *
40997c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
41097c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
41197c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
41297c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
41397c9341fSTejun Heo  * allocation and configurability.
41497c9341fSTejun Heo  *
41597c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
41697c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
41797c9341fSTejun Heo  */
418b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
41997c9341fSTejun Heo {
420b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
42197c9341fSTejun Heo 		return true;
42297c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
42369234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
42497c9341fSTejun Heo 		return true;
42597c9341fSTejun Heo #endif
42697c9341fSTejun Heo 	return false;
42797c9341fSTejun Heo }
42891a45470SKAMEZAWA Hiroyuki #else
4290a432dcbSYang Shi static int prealloc_memcg_shrinker(struct shrinker *shrinker)
4300a432dcbSYang Shi {
431*476b30a0SYang Shi 	return -ENOSYS;
4320a432dcbSYang Shi }
4330a432dcbSYang Shi 
4340a432dcbSYang Shi static void unregister_memcg_shrinker(struct shrinker *shrinker)
4350a432dcbSYang Shi {
4360a432dcbSYang Shi }
4370a432dcbSYang Shi 
43886750830SYang Shi static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
43986750830SYang Shi 				   struct mem_cgroup *memcg)
44086750830SYang Shi {
44186750830SYang Shi 	return 0;
44286750830SYang Shi }
44386750830SYang Shi 
44486750830SYang Shi static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
44586750830SYang Shi 				  struct mem_cgroup *memcg)
44686750830SYang Shi {
44786750830SYang Shi 	return 0;
44886750830SYang Shi }
44986750830SYang Shi 
450b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
45189b5fae5SJohannes Weiner {
452b5ead35eSJohannes Weiner 	return false;
45389b5fae5SJohannes Weiner }
45497c9341fSTejun Heo 
455b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
45697c9341fSTejun Heo {
45797c9341fSTejun Heo 	return true;
45897c9341fSTejun Heo }
45991a45470SKAMEZAWA Hiroyuki #endif
46091a45470SKAMEZAWA Hiroyuki 
46186750830SYang Shi static long xchg_nr_deferred(struct shrinker *shrinker,
46286750830SYang Shi 			     struct shrink_control *sc)
46386750830SYang Shi {
46486750830SYang Shi 	int nid = sc->nid;
46586750830SYang Shi 
46686750830SYang Shi 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
46786750830SYang Shi 		nid = 0;
46886750830SYang Shi 
46986750830SYang Shi 	if (sc->memcg &&
47086750830SYang Shi 	    (shrinker->flags & SHRINKER_MEMCG_AWARE))
47186750830SYang Shi 		return xchg_nr_deferred_memcg(nid, shrinker,
47286750830SYang Shi 					      sc->memcg);
47386750830SYang Shi 
47486750830SYang Shi 	return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
47586750830SYang Shi }
47686750830SYang Shi 
47786750830SYang Shi 
47886750830SYang Shi static long add_nr_deferred(long nr, struct shrinker *shrinker,
47986750830SYang Shi 			    struct shrink_control *sc)
48086750830SYang Shi {
48186750830SYang Shi 	int nid = sc->nid;
48286750830SYang Shi 
48386750830SYang Shi 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
48486750830SYang Shi 		nid = 0;
48586750830SYang Shi 
48686750830SYang Shi 	if (sc->memcg &&
48786750830SYang Shi 	    (shrinker->flags & SHRINKER_MEMCG_AWARE))
48886750830SYang Shi 		return add_nr_deferred_memcg(nr, nid, shrinker,
48986750830SYang Shi 					     sc->memcg);
49086750830SYang Shi 
49186750830SYang Shi 	return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
49286750830SYang Shi }
49386750830SYang Shi 
4945a1c84b4SMel Gorman /*
4955a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
4965a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
4975a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
4985a1c84b4SMel Gorman  */
4995a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
5005a1c84b4SMel Gorman {
5015a1c84b4SMel Gorman 	unsigned long nr;
5025a1c84b4SMel Gorman 
5035a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
5045a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
5055a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
5065a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
5075a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
5085a1c84b4SMel Gorman 
5095a1c84b4SMel Gorman 	return nr;
5105a1c84b4SMel Gorman }
5115a1c84b4SMel Gorman 
512fd538803SMichal Hocko /**
513fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
514fd538803SMichal Hocko  * @lruvec: lru vector
515fd538803SMichal Hocko  * @lru: lru to use
516fd538803SMichal Hocko  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
517fd538803SMichal Hocko  */
5182091339dSYu Zhao static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
5192091339dSYu Zhao 				     int zone_idx)
520c9f299d9SKOSAKI Motohiro {
521de3b0150SJohannes Weiner 	unsigned long size = 0;
522fd538803SMichal Hocko 	int zid;
523a3d8e054SKOSAKI Motohiro 
524de3b0150SJohannes Weiner 	for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
525fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
526fd538803SMichal Hocko 
527fd538803SMichal Hocko 		if (!managed_zone(zone))
528fd538803SMichal Hocko 			continue;
529fd538803SMichal Hocko 
530fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
531de3b0150SJohannes Weiner 			size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
532fd538803SMichal Hocko 		else
533de3b0150SJohannes Weiner 			size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
534c9f299d9SKOSAKI Motohiro 	}
535de3b0150SJohannes Weiner 	return size;
536b4536f0cSMichal Hocko }
537b4536f0cSMichal Hocko 
5381da177e4SLinus Torvalds /*
5391d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
5401da177e4SLinus Torvalds  */
5418e04944fSTetsuo Handa int prealloc_shrinker(struct shrinker *shrinker)
5421da177e4SLinus Torvalds {
543*476b30a0SYang Shi 	unsigned int size;
544*476b30a0SYang Shi 	int err;
5451d3d4437SGlauber Costa 
546*476b30a0SYang Shi 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
547*476b30a0SYang Shi 		err = prealloc_memcg_shrinker(shrinker);
548*476b30a0SYang Shi 		if (err != -ENOSYS)
549*476b30a0SYang Shi 			return err;
550*476b30a0SYang Shi 
551*476b30a0SYang Shi 		shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
552*476b30a0SYang Shi 	}
553*476b30a0SYang Shi 
554*476b30a0SYang Shi 	size = sizeof(*shrinker->nr_deferred);
5551d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
5561d3d4437SGlauber Costa 		size *= nr_node_ids;
5571d3d4437SGlauber Costa 
5581d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
5591d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
5601d3d4437SGlauber Costa 		return -ENOMEM;
561b4c2b231SKirill Tkhai 
5628e04944fSTetsuo Handa 	return 0;
5638e04944fSTetsuo Handa }
5641d3d4437SGlauber Costa 
5658e04944fSTetsuo Handa void free_prealloced_shrinker(struct shrinker *shrinker)
5668e04944fSTetsuo Handa {
56741ca668aSYang Shi 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
56841ca668aSYang Shi 		down_write(&shrinker_rwsem);
569b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
57041ca668aSYang Shi 		up_write(&shrinker_rwsem);
571*476b30a0SYang Shi 		return;
57241ca668aSYang Shi 	}
573b4c2b231SKirill Tkhai 
5748e04944fSTetsuo Handa 	kfree(shrinker->nr_deferred);
5758e04944fSTetsuo Handa 	shrinker->nr_deferred = NULL;
5768e04944fSTetsuo Handa }
5778e04944fSTetsuo Handa 
5788e04944fSTetsuo Handa void register_shrinker_prepared(struct shrinker *shrinker)
5798e04944fSTetsuo Handa {
5801da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
5811da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
58241ca668aSYang Shi 	shrinker->flags |= SHRINKER_REGISTERED;
5831da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
5848e04944fSTetsuo Handa }
5858e04944fSTetsuo Handa 
5868e04944fSTetsuo Handa int register_shrinker(struct shrinker *shrinker)
5878e04944fSTetsuo Handa {
5888e04944fSTetsuo Handa 	int err = prealloc_shrinker(shrinker);
5898e04944fSTetsuo Handa 
5908e04944fSTetsuo Handa 	if (err)
5918e04944fSTetsuo Handa 		return err;
5928e04944fSTetsuo Handa 	register_shrinker_prepared(shrinker);
5931d3d4437SGlauber Costa 	return 0;
5941da177e4SLinus Torvalds }
5958e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
5961da177e4SLinus Torvalds 
5971da177e4SLinus Torvalds /*
5981da177e4SLinus Torvalds  * Remove one
5991da177e4SLinus Torvalds  */
6008e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
6011da177e4SLinus Torvalds {
60241ca668aSYang Shi 	if (!(shrinker->flags & SHRINKER_REGISTERED))
603bb422a73STetsuo Handa 		return;
60441ca668aSYang Shi 
6051da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
6061da177e4SLinus Torvalds 	list_del(&shrinker->list);
60741ca668aSYang Shi 	shrinker->flags &= ~SHRINKER_REGISTERED;
60841ca668aSYang Shi 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
60941ca668aSYang Shi 		unregister_memcg_shrinker(shrinker);
6101da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
61141ca668aSYang Shi 
612ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
613bb422a73STetsuo Handa 	shrinker->nr_deferred = NULL;
6141da177e4SLinus Torvalds }
6158e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
6161da177e4SLinus Torvalds 
6171da177e4SLinus Torvalds #define SHRINK_BATCH 128
6181d3d4437SGlauber Costa 
619cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
6209092c71bSJosef Bacik 				    struct shrinker *shrinker, int priority)
6211da177e4SLinus Torvalds {
62224f7c6b9SDave Chinner 	unsigned long freed = 0;
6231da177e4SLinus Torvalds 	unsigned long long delta;
624635697c6SKonstantin Khlebnikov 	long total_scan;
625d5bc5fd3SVladimir Davydov 	long freeable;
626acf92b48SDave Chinner 	long nr;
627acf92b48SDave Chinner 	long new_nr;
628e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
629e9299f50SDave Chinner 					  : SHRINK_BATCH;
6305f33a080SShaohua Li 	long scanned = 0, next_deferred;
6311da177e4SLinus Torvalds 
632d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
6339b996468SKirill Tkhai 	if (freeable == 0 || freeable == SHRINK_EMPTY)
6349b996468SKirill Tkhai 		return freeable;
635635697c6SKonstantin Khlebnikov 
636acf92b48SDave Chinner 	/*
637acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
638acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
639acf92b48SDave Chinner 	 * don't also do this scanning work.
640acf92b48SDave Chinner 	 */
64186750830SYang Shi 	nr = xchg_nr_deferred(shrinker, shrinkctl);
642acf92b48SDave Chinner 
643acf92b48SDave Chinner 	total_scan = nr;
6444b85afbdSJohannes Weiner 	if (shrinker->seeks) {
6459092c71bSJosef Bacik 		delta = freeable >> priority;
6469092c71bSJosef Bacik 		delta *= 4;
6479092c71bSJosef Bacik 		do_div(delta, shrinker->seeks);
6484b85afbdSJohannes Weiner 	} else {
6494b85afbdSJohannes Weiner 		/*
6504b85afbdSJohannes Weiner 		 * These objects don't require any IO to create. Trim
6514b85afbdSJohannes Weiner 		 * them aggressively under memory pressure to keep
6524b85afbdSJohannes Weiner 		 * them from causing refetches in the IO caches.
6534b85afbdSJohannes Weiner 		 */
6544b85afbdSJohannes Weiner 		delta = freeable / 2;
6554b85afbdSJohannes Weiner 	}
656172b06c3SRoman Gushchin 
657acf92b48SDave Chinner 	total_scan += delta;
658acf92b48SDave Chinner 	if (total_scan < 0) {
659d75f773cSSakari Ailus 		pr_err("shrink_slab: %pS negative objects to delete nr=%ld\n",
660a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
661d5bc5fd3SVladimir Davydov 		total_scan = freeable;
6625f33a080SShaohua Li 		next_deferred = nr;
6635f33a080SShaohua Li 	} else
6645f33a080SShaohua Li 		next_deferred = total_scan;
665ea164d73SAndrea Arcangeli 
666ea164d73SAndrea Arcangeli 	/*
6673567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
6683567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
6693567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
6703567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
6713567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
672d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
6733567b59aSDave Chinner 	 * memory.
6743567b59aSDave Chinner 	 *
6753567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
6763567b59aSDave Chinner 	 * a large delta change is calculated directly.
6773567b59aSDave Chinner 	 */
678d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
679d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
6803567b59aSDave Chinner 
6813567b59aSDave Chinner 	/*
682ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
683ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
684ea164d73SAndrea Arcangeli 	 * freeable entries.
685ea164d73SAndrea Arcangeli 	 */
686d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
687d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
6881da177e4SLinus Torvalds 
68924f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
6909092c71bSJosef Bacik 				   freeable, delta, total_scan, priority);
69109576073SDave Chinner 
6920b1fb40aSVladimir Davydov 	/*
6930b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
6940b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
6950b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
6960b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
6970b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
6980b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
6990b1fb40aSVladimir Davydov 	 * batch_size.
7000b1fb40aSVladimir Davydov 	 *
7010b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
7020b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
703d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
7040b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
7050b1fb40aSVladimir Davydov 	 * possible.
7060b1fb40aSVladimir Davydov 	 */
7070b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
708d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
70924f7c6b9SDave Chinner 		unsigned long ret;
7100b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
7111da177e4SLinus Torvalds 
7120b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
713d460acb5SChris Wilson 		shrinkctl->nr_scanned = nr_to_scan;
71424f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
71524f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
7161da177e4SLinus Torvalds 			break;
71724f7c6b9SDave Chinner 		freed += ret;
71824f7c6b9SDave Chinner 
719d460acb5SChris Wilson 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
720d460acb5SChris Wilson 		total_scan -= shrinkctl->nr_scanned;
721d460acb5SChris Wilson 		scanned += shrinkctl->nr_scanned;
7221da177e4SLinus Torvalds 
7231da177e4SLinus Torvalds 		cond_resched();
7241da177e4SLinus Torvalds 	}
7251da177e4SLinus Torvalds 
7265f33a080SShaohua Li 	if (next_deferred >= scanned)
7275f33a080SShaohua Li 		next_deferred -= scanned;
7285f33a080SShaohua Li 	else
7295f33a080SShaohua Li 		next_deferred = 0;
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);
170402c6de8dSMinchan Kim 
170502c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1706ae37c7ffSOscar Salvador 		if (!PageHuge(page) && page_is_file_lru(page) &&
1707ae37c7ffSOscar Salvador 		    !PageDirty(page) && !__PageMovable(page) &&
1708ae37c7ffSOscar Salvador 		    !PageUnevictable(page)) {
170902c6de8dSMinchan Kim 			ClearPageActive(page);
171002c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
171102c6de8dSMinchan Kim 		}
171202c6de8dSMinchan Kim 	}
171302c6de8dSMinchan Kim 
17141f318a9bSJaewon Kim 	nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1715013339dfSShakeel Butt 					&stat, true);
171602c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
17172da9f630SNicholas Piggin 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
17182da9f630SNicholas Piggin 			    -(long)nr_reclaimed);
17191f318a9bSJaewon Kim 	/*
17201f318a9bSJaewon Kim 	 * Since lazyfree pages are isolated from file LRU from the beginning,
17211f318a9bSJaewon Kim 	 * they will rotate back to anonymous LRU in the end if it failed to
17221f318a9bSJaewon Kim 	 * discard so isolated count will be mismatched.
17231f318a9bSJaewon Kim 	 * Compensate the isolated count for both LRU lists.
17241f318a9bSJaewon Kim 	 */
17251f318a9bSJaewon Kim 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
17261f318a9bSJaewon Kim 			    stat.nr_lazyfree_fail);
17271f318a9bSJaewon Kim 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
17282da9f630SNicholas Piggin 			    -(long)stat.nr_lazyfree_fail);
17291f318a9bSJaewon Kim 	return nr_reclaimed;
173002c6de8dSMinchan Kim }
173102c6de8dSMinchan Kim 
17325ad333ebSAndy Whitcroft /*
17335ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
17345ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
17355ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
17365ad333ebSAndy Whitcroft  *
17375ad333ebSAndy Whitcroft  * page:	page to consider
17385ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
17395ad333ebSAndy Whitcroft  *
1740c2135f7cSAlex Shi  * returns true on success, false on failure.
17415ad333ebSAndy Whitcroft  */
1742c2135f7cSAlex Shi bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
17435ad333ebSAndy Whitcroft {
17445ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
17455ad333ebSAndy Whitcroft 	if (!PageLRU(page))
1746c2135f7cSAlex Shi 		return false;
17475ad333ebSAndy Whitcroft 
1748e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1749e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1750c2135f7cSAlex Shi 		return false;
1751894bc310SLee Schermerhorn 
1752c8244935SMel Gorman 	/*
1753c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1754c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1755c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1756c8244935SMel Gorman 	 *
1757c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1758c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1759c8244935SMel Gorman 	 */
17601276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1761c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1762c8244935SMel Gorman 		if (PageWriteback(page))
1763c2135f7cSAlex Shi 			return false;
176439deaf85SMinchan Kim 
1765c8244935SMel Gorman 		if (PageDirty(page)) {
1766c8244935SMel Gorman 			struct address_space *mapping;
176769d763fcSMel Gorman 			bool migrate_dirty;
1768c8244935SMel Gorman 
1769c8244935SMel Gorman 			/*
1770c8244935SMel Gorman 			 * Only pages without mappings or that have a
1771c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
177269d763fcSMel Gorman 			 * without blocking. However, we can be racing with
177369d763fcSMel Gorman 			 * truncation so it's necessary to lock the page
177469d763fcSMel Gorman 			 * to stabilise the mapping as truncation holds
177569d763fcSMel Gorman 			 * the page lock until after the page is removed
177669d763fcSMel Gorman 			 * from the page cache.
1777c8244935SMel Gorman 			 */
177869d763fcSMel Gorman 			if (!trylock_page(page))
1779c2135f7cSAlex Shi 				return false;
178069d763fcSMel Gorman 
1781c8244935SMel Gorman 			mapping = page_mapping(page);
1782145e1a71SHugh Dickins 			migrate_dirty = !mapping || mapping->a_ops->migratepage;
178369d763fcSMel Gorman 			unlock_page(page);
178469d763fcSMel Gorman 			if (!migrate_dirty)
1785c2135f7cSAlex Shi 				return false;
1786c8244935SMel Gorman 		}
1787c8244935SMel Gorman 	}
1788c8244935SMel Gorman 
1789f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1790c2135f7cSAlex Shi 		return false;
1791f80c0673SMinchan Kim 
1792c2135f7cSAlex Shi 	return true;
17935ad333ebSAndy Whitcroft }
17945ad333ebSAndy Whitcroft 
17957ee36a14SMel Gorman /*
17967ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
179755b65a57SEthon Paul  * be complete before mem_cgroup_update_lru_size due to a sanity check.
17987ee36a14SMel Gorman  */
17997ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1800b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
18017ee36a14SMel Gorman {
18027ee36a14SMel Gorman 	int zid;
18037ee36a14SMel Gorman 
18047ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
18057ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
18067ee36a14SMel Gorman 			continue;
18077ee36a14SMel Gorman 
1808a892cb6bSWei Yang 		update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
18097ee36a14SMel Gorman 	}
18107ee36a14SMel Gorman 
18117ee36a14SMel Gorman }
18127ee36a14SMel Gorman 
1813f4b7e272SAndrey Ryabinin /**
181415b44736SHugh Dickins  * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
181515b44736SHugh Dickins  *
181615b44736SHugh Dickins  * lruvec->lru_lock is heavily contended.  Some of the functions that
18171da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
18181da177e4SLinus Torvalds  * and working on them outside the LRU lock.
18191da177e4SLinus Torvalds  *
18201da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
18211da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
18221da177e4SLinus Torvalds  *
182315b44736SHugh Dickins  * Lru_lock must be held before calling this function.
18241da177e4SLinus Torvalds  *
1825791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
18265dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
18271da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1828f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1829fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
18303cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
18311da177e4SLinus Torvalds  *
18321da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
18331da177e4SLinus Torvalds  */
183469e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
18355dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1836fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
1837a9e7c39fSKirill Tkhai 		enum lru_list lru)
18381da177e4SLinus Torvalds {
183975b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
184069e05944SAndrew Morton 	unsigned long nr_taken = 0;
1841599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
18427cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
18433db65812SJohannes Weiner 	unsigned long skipped = 0;
1844791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
1845b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
1846a9e7c39fSKirill Tkhai 	isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
18471da177e4SLinus Torvalds 
184898879b3bSYang Shi 	total_scan = 0;
1849791b48b6SMinchan Kim 	scan = 0;
185098879b3bSYang Shi 	while (scan < nr_to_scan && !list_empty(src)) {
18515ad333ebSAndy Whitcroft 		struct page *page;
18525ad333ebSAndy Whitcroft 
18531da177e4SLinus Torvalds 		page = lru_to_page(src);
18541da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
18551da177e4SLinus Torvalds 
1856d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
185798879b3bSYang Shi 		total_scan += nr_pages;
185898879b3bSYang Shi 
1859b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1860b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
186198879b3bSYang Shi 			nr_skipped[page_zonenum(page)] += nr_pages;
1862b2e18757SMel Gorman 			continue;
1863b2e18757SMel Gorman 		}
1864b2e18757SMel Gorman 
1865791b48b6SMinchan Kim 		/*
1866791b48b6SMinchan Kim 		 * Do not count skipped pages because that makes the function
1867791b48b6SMinchan Kim 		 * return with no isolated pages if the LRU mostly contains
1868791b48b6SMinchan Kim 		 * ineligible pages.  This causes the VM to not reclaim any
1869791b48b6SMinchan Kim 		 * pages, triggering a premature OOM.
187098879b3bSYang Shi 		 *
187198879b3bSYang Shi 		 * Account all tail pages of THP.  This would not cause
187298879b3bSYang Shi 		 * premature OOM since __isolate_lru_page() returns -EBUSY
187398879b3bSYang Shi 		 * only when the page is being freed somewhere else.
1874791b48b6SMinchan Kim 		 */
187598879b3bSYang Shi 		scan += nr_pages;
1876c2135f7cSAlex Shi 		if (!__isolate_lru_page_prepare(page, mode)) {
1877c2135f7cSAlex Shi 			/* It is being freed elsewhere */
1878c2135f7cSAlex Shi 			list_move(&page->lru, src);
1879c2135f7cSAlex Shi 			continue;
1880c2135f7cSAlex Shi 		}
18819df41314SAlex Shi 		/*
18829df41314SAlex Shi 		 * Be careful not to clear PageLRU until after we're
18839df41314SAlex Shi 		 * sure the page is not being freed elsewhere -- the
18849df41314SAlex Shi 		 * page release code relies on it.
18859df41314SAlex Shi 		 */
1886c2135f7cSAlex Shi 		if (unlikely(!get_page_unless_zero(page))) {
1887c2135f7cSAlex Shi 			list_move(&page->lru, src);
1888c2135f7cSAlex Shi 			continue;
1889c2135f7cSAlex Shi 		}
18909df41314SAlex Shi 
18919df41314SAlex Shi 		if (!TestClearPageLRU(page)) {
1892c2135f7cSAlex Shi 			/* Another thread is already isolating this page */
18939df41314SAlex Shi 			put_page(page);
1894c2135f7cSAlex Shi 			list_move(&page->lru, src);
1895c2135f7cSAlex Shi 			continue;
18969df41314SAlex Shi 		}
18979df41314SAlex Shi 
1898599d0c95SMel Gorman 		nr_taken += nr_pages;
1899599d0c95SMel Gorman 		nr_zone_taken[page_zonenum(page)] += nr_pages;
19005ad333ebSAndy Whitcroft 		list_move(&page->lru, dst);
19015ad333ebSAndy Whitcroft 	}
19021da177e4SLinus Torvalds 
1903b2e18757SMel Gorman 	/*
1904b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1905b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1906b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1907b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1908b2e18757SMel Gorman 	 * system at risk of premature OOM.
1909b2e18757SMel Gorman 	 */
19107cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
19117cc30fcfSMel Gorman 		int zid;
19127cc30fcfSMel Gorman 
19133db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
19147cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
19157cc30fcfSMel Gorman 			if (!nr_skipped[zid])
19167cc30fcfSMel Gorman 				continue;
19177cc30fcfSMel Gorman 
19187cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
19191265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
19207cc30fcfSMel Gorman 		}
19217cc30fcfSMel Gorman 	}
1922791b48b6SMinchan Kim 	*nr_scanned = total_scan;
19231265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1924791b48b6SMinchan Kim 				    total_scan, skipped, nr_taken, mode, lru);
1925b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
19261da177e4SLinus Torvalds 	return nr_taken;
19271da177e4SLinus Torvalds }
19281da177e4SLinus Torvalds 
192962695a84SNick Piggin /**
193062695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
193162695a84SNick Piggin  * @page: page to isolate from its LRU list
193262695a84SNick Piggin  *
193362695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
193462695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
193562695a84SNick Piggin  *
193662695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
193762695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
193862695a84SNick Piggin  *
193962695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1940894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1941894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1942894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
194362695a84SNick Piggin  *
194462695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
194562695a84SNick Piggin  * found will be decremented.
194662695a84SNick Piggin  *
194762695a84SNick Piggin  * Restrictions:
1948a5d09bedSMike Rapoport  *
194962695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
195001c4776bSHui Su  *     fundamental difference from isolate_lru_pages (which is called
195162695a84SNick Piggin  *     without a stable reference).
195262695a84SNick Piggin  * (2) the lru_lock must not be held.
195362695a84SNick Piggin  * (3) interrupts must be enabled.
195462695a84SNick Piggin  */
195562695a84SNick Piggin int isolate_lru_page(struct page *page)
195662695a84SNick Piggin {
195762695a84SNick Piggin 	int ret = -EBUSY;
195862695a84SNick Piggin 
1959309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1960cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
19610c917313SKonstantin Khlebnikov 
1962d25b5bd8SAlex Shi 	if (TestClearPageLRU(page)) {
1963fa9add64SHugh Dickins 		struct lruvec *lruvec;
196462695a84SNick Piggin 
19650c917313SKonstantin Khlebnikov 		get_page(page);
19666168d0daSAlex Shi 		lruvec = lock_page_lruvec_irq(page);
196746ae6b2cSYu Zhao 		del_page_from_lru_list(page, lruvec);
19686168d0daSAlex Shi 		unlock_page_lruvec_irq(lruvec);
1969fa9add64SHugh Dickins 		ret = 0;
197062695a84SNick Piggin 	}
1971d25b5bd8SAlex Shi 
197262695a84SNick Piggin 	return ret;
197362695a84SNick Piggin }
197462695a84SNick Piggin 
19755ad333ebSAndy Whitcroft /*
1976d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1977178821b8SXianting Tian  * then get rescheduled. When there are massive number of tasks doing page
1978d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1979d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1980d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
198135cd7815SRik van Riel  */
1982599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
198335cd7815SRik van Riel 		struct scan_control *sc)
198435cd7815SRik van Riel {
198535cd7815SRik van Riel 	unsigned long inactive, isolated;
198635cd7815SRik van Riel 
198735cd7815SRik van Riel 	if (current_is_kswapd())
198835cd7815SRik van Riel 		return 0;
198935cd7815SRik van Riel 
1990b5ead35eSJohannes Weiner 	if (!writeback_throttling_sane(sc))
199135cd7815SRik van Riel 		return 0;
199235cd7815SRik van Riel 
199335cd7815SRik van Riel 	if (file) {
1994599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1995599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
199635cd7815SRik van Riel 	} else {
1997599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1998599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
199935cd7815SRik van Riel 	}
200035cd7815SRik van Riel 
20013cf23841SFengguang Wu 	/*
20023cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
20033cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
20043cf23841SFengguang Wu 	 * deadlock.
20053cf23841SFengguang Wu 	 */
2006d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
20073cf23841SFengguang Wu 		inactive >>= 3;
20083cf23841SFengguang Wu 
200935cd7815SRik van Riel 	return isolated > inactive;
201035cd7815SRik van Riel }
201135cd7815SRik van Riel 
2012a222f341SKirill Tkhai /*
201315b44736SHugh Dickins  * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
201415b44736SHugh Dickins  * On return, @list is reused as a list of pages to be freed by the caller.
2015a222f341SKirill Tkhai  *
2016a222f341SKirill Tkhai  * Returns the number of pages moved to the given lruvec.
2017a222f341SKirill Tkhai  */
2018a222f341SKirill Tkhai static unsigned noinline_for_stack move_pages_to_lru(struct lruvec *lruvec,
2019a222f341SKirill Tkhai 						     struct list_head *list)
202066635629SMel Gorman {
2021a222f341SKirill Tkhai 	int nr_pages, nr_moved = 0;
20223f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
2023a222f341SKirill Tkhai 	struct page *page;
202466635629SMel Gorman 
2025a222f341SKirill Tkhai 	while (!list_empty(list)) {
2026a222f341SKirill Tkhai 		page = lru_to_page(list);
2027309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
2028a222f341SKirill Tkhai 		list_del(&page->lru);
20293d06afabSAlex Shi 		if (unlikely(!page_evictable(page))) {
20306168d0daSAlex Shi 			spin_unlock_irq(&lruvec->lru_lock);
203166635629SMel Gorman 			putback_lru_page(page);
20326168d0daSAlex Shi 			spin_lock_irq(&lruvec->lru_lock);
203366635629SMel Gorman 			continue;
203466635629SMel Gorman 		}
2035fa9add64SHugh Dickins 
20363d06afabSAlex Shi 		/*
20373d06afabSAlex Shi 		 * The SetPageLRU needs to be kept here for list integrity.
20383d06afabSAlex Shi 		 * Otherwise:
20393d06afabSAlex Shi 		 *   #0 move_pages_to_lru             #1 release_pages
20403d06afabSAlex Shi 		 *   if !put_page_testzero
20413d06afabSAlex Shi 		 *				      if (put_page_testzero())
20423d06afabSAlex Shi 		 *				        !PageLRU //skip lru_lock
20433d06afabSAlex Shi 		 *     SetPageLRU()
20443d06afabSAlex Shi 		 *     list_add(&page->lru,)
20453d06afabSAlex Shi 		 *                                        list_add(&page->lru,)
20463d06afabSAlex Shi 		 */
20477a608572SLinus Torvalds 		SetPageLRU(page);
2048a222f341SKirill Tkhai 
20493d06afabSAlex Shi 		if (unlikely(put_page_testzero(page))) {
205087560179SYu Zhao 			__clear_page_lru_flags(page);
20512bcf8879SHugh Dickins 
20522bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
20536168d0daSAlex Shi 				spin_unlock_irq(&lruvec->lru_lock);
2054ff45fc3cSMatthew Wilcox (Oracle) 				destroy_compound_page(page);
20556168d0daSAlex Shi 				spin_lock_irq(&lruvec->lru_lock);
20562bcf8879SHugh Dickins 			} else
20572bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
20583d06afabSAlex Shi 
20593d06afabSAlex Shi 			continue;
20603d06afabSAlex Shi 		}
20613d06afabSAlex Shi 
2062afca9157SAlex Shi 		/*
2063afca9157SAlex Shi 		 * All pages were isolated from the same lruvec (and isolation
2064afca9157SAlex Shi 		 * inhibits memcg migration).
2065afca9157SAlex Shi 		 */
20662a5e4e34SAlexander Duyck 		VM_BUG_ON_PAGE(!lruvec_holds_page_lru_lock(page, lruvec), page);
20673a9c9788SYu Zhao 		add_page_to_lru_list(page, lruvec);
20683d06afabSAlex Shi 		nr_pages = thp_nr_pages(page);
2069a222f341SKirill Tkhai 		nr_moved += nr_pages;
207031d8fcacSJohannes Weiner 		if (PageActive(page))
207131d8fcacSJohannes Weiner 			workingset_age_nonresident(lruvec, nr_pages);
207266635629SMel Gorman 	}
207366635629SMel Gorman 
20743f79768fSHugh Dickins 	/*
20753f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
20763f79768fSHugh Dickins 	 */
2077a222f341SKirill Tkhai 	list_splice(&pages_to_free, list);
2078a222f341SKirill Tkhai 
2079a222f341SKirill Tkhai 	return nr_moved;
208066635629SMel Gorman }
208166635629SMel Gorman 
208266635629SMel Gorman /*
2083399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
2084a37b0715SNeilBrown  * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
2085399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
2086399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
2087399ba0b9SNeilBrown  */
2088399ba0b9SNeilBrown static int current_may_throttle(void)
2089399ba0b9SNeilBrown {
2090a37b0715SNeilBrown 	return !(current->flags & PF_LOCAL_THROTTLE) ||
2091399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
2092399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
2093399ba0b9SNeilBrown }
2094399ba0b9SNeilBrown 
2095399ba0b9SNeilBrown /*
2096b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
20971742f19fSAndrew Morton  * of reclaimed pages
20981da177e4SLinus Torvalds  */
209966635629SMel Gorman static noinline_for_stack unsigned long
21001a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
21019e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
21021da177e4SLinus Torvalds {
21031da177e4SLinus Torvalds 	LIST_HEAD(page_list);
2104e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
2105730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
2106e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
2107060f005fSKirill Tkhai 	struct reclaim_stat stat;
2108497a6c1bSJohannes Weiner 	bool file = is_file_lru(lru);
2109f46b7912SKirill Tkhai 	enum vm_event_item item;
2110599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2111db73ee0dSMichal Hocko 	bool stalled = false;
211278dc583dSKOSAKI Motohiro 
2113599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
2114db73ee0dSMichal Hocko 		if (stalled)
2115db73ee0dSMichal Hocko 			return 0;
2116db73ee0dSMichal Hocko 
2117db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
2118db73ee0dSMichal Hocko 		msleep(100);
2119db73ee0dSMichal Hocko 		stalled = true;
212035cd7815SRik van Riel 
212135cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
212235cd7815SRik van Riel 		if (fatal_signal_pending(current))
212335cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
212435cd7815SRik van Riel 	}
212535cd7815SRik van Riel 
21261da177e4SLinus Torvalds 	lru_add_drain();
2127f80c0673SMinchan Kim 
21286168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
21291da177e4SLinus Torvalds 
21305dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
2131a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
213295d918fcSKonstantin Khlebnikov 
2133599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2134f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
2135b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
2136f46b7912SKirill Tkhai 		__count_vm_events(item, nr_scanned);
2137f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
2138497a6c1bSJohannes Weiner 	__count_vm_events(PGSCAN_ANON + file, nr_scanned);
2139497a6c1bSJohannes Weiner 
21406168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
2141d563c050SHillf Danton 
2142d563c050SHillf Danton 	if (nr_taken == 0)
214366635629SMel Gorman 		return 0;
2144b35ea17bSKOSAKI Motohiro 
2145013339dfSShakeel Butt 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
2146c661b078SAndy Whitcroft 
21476168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2148497a6c1bSJohannes Weiner 	move_pages_to_lru(lruvec, &page_list);
2149497a6c1bSJohannes Weiner 
2150497a6c1bSJohannes Weiner 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2151f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
2152b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
2153f46b7912SKirill Tkhai 		__count_vm_events(item, nr_reclaimed);
2154f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
2155497a6c1bSJohannes Weiner 	__count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
21566168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
21573f79768fSHugh Dickins 
215875cc3c91SAlex Shi 	lru_note_cost(lruvec, file, stat.nr_pageout);
2159747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
21602d4894b5SMel Gorman 	free_unref_page_list(&page_list);
2161e11da5b4SMel Gorman 
216292df3a72SMel Gorman 	/*
21631c610d5fSAndrey Ryabinin 	 * If dirty pages are scanned that are not queued for IO, it
21641c610d5fSAndrey Ryabinin 	 * implies that flushers are not doing their job. This can
21651c610d5fSAndrey Ryabinin 	 * happen when memory pressure pushes dirty pages to the end of
21661c610d5fSAndrey Ryabinin 	 * the LRU before the dirty limits are breached and the dirty
21671c610d5fSAndrey Ryabinin 	 * data has expired. It can also happen when the proportion of
21681c610d5fSAndrey Ryabinin 	 * dirty pages grows not through writes but through memory
21691c610d5fSAndrey Ryabinin 	 * pressure reclaiming all the clean cache. And in some cases,
21701c610d5fSAndrey Ryabinin 	 * the flushers simply cannot keep up with the allocation
21711c610d5fSAndrey Ryabinin 	 * rate. Nudge the flusher threads in case they are asleep.
21721c610d5fSAndrey Ryabinin 	 */
21731c610d5fSAndrey Ryabinin 	if (stat.nr_unqueued_dirty == nr_taken)
21741c610d5fSAndrey Ryabinin 		wakeup_flusher_threads(WB_REASON_VMSCAN);
21751c610d5fSAndrey Ryabinin 
2176d108c772SAndrey Ryabinin 	sc->nr.dirty += stat.nr_dirty;
2177d108c772SAndrey Ryabinin 	sc->nr.congested += stat.nr_congested;
2178d108c772SAndrey Ryabinin 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2179d108c772SAndrey Ryabinin 	sc->nr.writeback += stat.nr_writeback;
2180d108c772SAndrey Ryabinin 	sc->nr.immediate += stat.nr_immediate;
2181d108c772SAndrey Ryabinin 	sc->nr.taken += nr_taken;
2182d108c772SAndrey Ryabinin 	if (file)
2183d108c772SAndrey Ryabinin 		sc->nr.file_taken += nr_taken;
21848e950282SMel Gorman 
2185599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2186d51d1e64SSteven Rostedt 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
218705ff5137SAndrew Morton 	return nr_reclaimed;
21881da177e4SLinus Torvalds }
21891da177e4SLinus Torvalds 
219015b44736SHugh Dickins /*
219115b44736SHugh Dickins  * shrink_active_list() moves pages from the active LRU to the inactive LRU.
219215b44736SHugh Dickins  *
219315b44736SHugh Dickins  * We move them the other way if the page is referenced by one or more
219415b44736SHugh Dickins  * processes.
219515b44736SHugh Dickins  *
219615b44736SHugh Dickins  * If the pages are mostly unmapped, the processing is fast and it is
219715b44736SHugh Dickins  * appropriate to hold lru_lock across the whole operation.  But if
219815b44736SHugh Dickins  * the pages are mapped, the processing is slow (page_referenced()), so
219915b44736SHugh Dickins  * we should drop lru_lock around each page.  It's impossible to balance
220015b44736SHugh Dickins  * this, so instead we remove the pages from the LRU while processing them.
220115b44736SHugh Dickins  * It is safe to rely on PG_active against the non-LRU pages in here because
220215b44736SHugh Dickins  * nobody will play with that bit on a non-LRU page.
220315b44736SHugh Dickins  *
220415b44736SHugh Dickins  * The downside is that we have to touch page->_refcount against each page.
220515b44736SHugh Dickins  * But we had to alter page->flags anyway.
220615b44736SHugh Dickins  */
2207f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
22081a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
2209f16015fbSJohannes Weiner 			       struct scan_control *sc,
22109e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
22111cfb419bSKAMEZAWA Hiroyuki {
221244c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
2213f626012dSHugh Dickins 	unsigned long nr_scanned;
22146fe6b7e3SWu Fengguang 	unsigned long vm_flags;
22151cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
22168cab4754SWu Fengguang 	LIST_HEAD(l_active);
2217b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
22181cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
22199d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
22209d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
22213cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
2222599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
22231cfb419bSKAMEZAWA Hiroyuki 
22241da177e4SLinus Torvalds 	lru_add_drain();
2225f80c0673SMinchan Kim 
22266168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2227925b7673SJohannes Weiner 
22285dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2229a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
223089b5fae5SJohannes Weiner 
2231599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
22321cfb419bSKAMEZAWA Hiroyuki 
2233912c0572SShakeel Butt 	if (!cgroup_reclaim(sc))
2234599d0c95SMel Gorman 		__count_vm_events(PGREFILL, nr_scanned);
22352fa2690cSYafang Shao 	__count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
22369d5e6a9fSHugh Dickins 
22376168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
22381da177e4SLinus Torvalds 
22391da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
22401da177e4SLinus Torvalds 		cond_resched();
22411da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
22421da177e4SLinus Torvalds 		list_del(&page->lru);
22437e9cd484SRik van Riel 
224439b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
2245894bc310SLee Schermerhorn 			putback_lru_page(page);
2246894bc310SLee Schermerhorn 			continue;
2247894bc310SLee Schermerhorn 		}
2248894bc310SLee Schermerhorn 
2249cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
2250cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
2251cc715d99SMel Gorman 				if (page_has_private(page))
2252cc715d99SMel Gorman 					try_to_release_page(page, 0);
2253cc715d99SMel Gorman 				unlock_page(page);
2254cc715d99SMel Gorman 			}
2255cc715d99SMel Gorman 		}
2256cc715d99SMel Gorman 
2257c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
2258c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
22598cab4754SWu Fengguang 			/*
22608cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
22618cab4754SWu Fengguang 			 * give them one more trip around the active list. So
22628cab4754SWu Fengguang 			 * that executable code get better chances to stay in
22638cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
22648cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
22658cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
22668cab4754SWu Fengguang 			 * so we ignore them here.
22678cab4754SWu Fengguang 			 */
22689de4f22aSHuang Ying 			if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
22696c357848SMatthew Wilcox (Oracle) 				nr_rotated += thp_nr_pages(page);
22708cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
22718cab4754SWu Fengguang 				continue;
22728cab4754SWu Fengguang 			}
22738cab4754SWu Fengguang 		}
22747e9cd484SRik van Riel 
22755205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
22761899ad18SJohannes Weiner 		SetPageWorkingset(page);
22771da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
22781da177e4SLinus Torvalds 	}
22791da177e4SLinus Torvalds 
2280b555749aSAndrew Morton 	/*
22818cab4754SWu Fengguang 	 * Move pages back to the lru list.
2282b555749aSAndrew Morton 	 */
22836168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2284556adecbSRik van Riel 
2285a222f341SKirill Tkhai 	nr_activate = move_pages_to_lru(lruvec, &l_active);
2286a222f341SKirill Tkhai 	nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2287f372d89eSKirill Tkhai 	/* Keep all free pages in l_active list */
2288f372d89eSKirill Tkhai 	list_splice(&l_inactive, &l_active);
22899851ac13SKirill Tkhai 
22909851ac13SKirill Tkhai 	__count_vm_events(PGDEACTIVATE, nr_deactivate);
22919851ac13SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
22929851ac13SKirill Tkhai 
2293599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
22946168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
22952bcf8879SHugh Dickins 
2296f372d89eSKirill Tkhai 	mem_cgroup_uncharge_list(&l_active);
2297f372d89eSKirill Tkhai 	free_unref_page_list(&l_active);
22989d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
22999d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
23001da177e4SLinus Torvalds }
23011da177e4SLinus Torvalds 
23021a4e58ccSMinchan Kim unsigned long reclaim_pages(struct list_head *page_list)
23031a4e58ccSMinchan Kim {
2304f661d007SYang Shi 	int nid = NUMA_NO_NODE;
2305730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
23061a4e58ccSMinchan Kim 	LIST_HEAD(node_page_list);
23071a4e58ccSMinchan Kim 	struct reclaim_stat dummy_stat;
23081a4e58ccSMinchan Kim 	struct page *page;
23091a4e58ccSMinchan Kim 	struct scan_control sc = {
23101a4e58ccSMinchan Kim 		.gfp_mask = GFP_KERNEL,
23111a4e58ccSMinchan Kim 		.priority = DEF_PRIORITY,
23121a4e58ccSMinchan Kim 		.may_writepage = 1,
23131a4e58ccSMinchan Kim 		.may_unmap = 1,
23141a4e58ccSMinchan Kim 		.may_swap = 1,
23151a4e58ccSMinchan Kim 	};
23161a4e58ccSMinchan Kim 
23171a4e58ccSMinchan Kim 	while (!list_empty(page_list)) {
23181a4e58ccSMinchan Kim 		page = lru_to_page(page_list);
2319f661d007SYang Shi 		if (nid == NUMA_NO_NODE) {
23201a4e58ccSMinchan Kim 			nid = page_to_nid(page);
23211a4e58ccSMinchan Kim 			INIT_LIST_HEAD(&node_page_list);
23221a4e58ccSMinchan Kim 		}
23231a4e58ccSMinchan Kim 
23241a4e58ccSMinchan Kim 		if (nid == page_to_nid(page)) {
23251a4e58ccSMinchan Kim 			ClearPageActive(page);
23261a4e58ccSMinchan Kim 			list_move(&page->lru, &node_page_list);
23271a4e58ccSMinchan Kim 			continue;
23281a4e58ccSMinchan Kim 		}
23291a4e58ccSMinchan Kim 
23301a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
23311a4e58ccSMinchan Kim 						NODE_DATA(nid),
2332013339dfSShakeel Butt 						&sc, &dummy_stat, false);
23331a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
23341a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
23351a4e58ccSMinchan Kim 			list_del(&page->lru);
23361a4e58ccSMinchan Kim 			putback_lru_page(page);
23371a4e58ccSMinchan Kim 		}
23381a4e58ccSMinchan Kim 
2339f661d007SYang Shi 		nid = NUMA_NO_NODE;
23401a4e58ccSMinchan Kim 	}
23411a4e58ccSMinchan Kim 
23421a4e58ccSMinchan Kim 	if (!list_empty(&node_page_list)) {
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 	}
23521a4e58ccSMinchan Kim 
23531a4e58ccSMinchan Kim 	return nr_reclaimed;
23541a4e58ccSMinchan Kim }
23551a4e58ccSMinchan Kim 
2356b91ac374SJohannes Weiner static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2357b91ac374SJohannes Weiner 				 struct lruvec *lruvec, struct scan_control *sc)
2358b91ac374SJohannes Weiner {
2359b91ac374SJohannes Weiner 	if (is_active_lru(lru)) {
2360b91ac374SJohannes Weiner 		if (sc->may_deactivate & (1 << is_file_lru(lru)))
2361b91ac374SJohannes Weiner 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2362b91ac374SJohannes Weiner 		else
2363b91ac374SJohannes Weiner 			sc->skipped_deactivate = 1;
2364b91ac374SJohannes Weiner 		return 0;
2365b91ac374SJohannes Weiner 	}
2366b91ac374SJohannes Weiner 
2367b91ac374SJohannes Weiner 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2368b91ac374SJohannes Weiner }
2369b91ac374SJohannes Weiner 
237059dc76b0SRik van Riel /*
237159dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
237259dc76b0SRik van Riel  * to do too much work.
237314797e23SKOSAKI Motohiro  *
237459dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
237559dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
237659dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
237759dc76b0SRik van Riel  *
237859dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
237959dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
238059dc76b0SRik van Riel  *
23812a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
23822a2e4885SJohannes Weiner  *
238359dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
23843a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
238559dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
238659dc76b0SRik van Riel  *
238759dc76b0SRik van Riel  * total     target    max
238859dc76b0SRik van Riel  * memory    ratio     inactive
238959dc76b0SRik van Riel  * -------------------------------------
239059dc76b0SRik van Riel  *   10MB       1         5MB
239159dc76b0SRik van Riel  *  100MB       1        50MB
239259dc76b0SRik van Riel  *    1GB       3       250MB
239359dc76b0SRik van Riel  *   10GB      10       0.9GB
239459dc76b0SRik van Riel  *  100GB      31         3GB
239559dc76b0SRik van Riel  *    1TB     101        10GB
239659dc76b0SRik van Riel  *   10TB     320        32GB
239714797e23SKOSAKI Motohiro  */
2398b91ac374SJohannes Weiner static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
239914797e23SKOSAKI Motohiro {
2400b91ac374SJohannes Weiner 	enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
24012a2e4885SJohannes Weiner 	unsigned long inactive, active;
24022a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
240359dc76b0SRik van Riel 	unsigned long gb;
240459dc76b0SRik van Riel 
2405b91ac374SJohannes Weiner 	inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2406b91ac374SJohannes Weiner 	active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2407f8d1a311SMel Gorman 
240859dc76b0SRik van Riel 	gb = (inactive + active) >> (30 - PAGE_SHIFT);
24094002570cSJoonsoo Kim 	if (gb)
241059dc76b0SRik van Riel 		inactive_ratio = int_sqrt(10 * gb);
2411b39415b2SRik van Riel 	else
241259dc76b0SRik van Riel 		inactive_ratio = 1;
2413fd538803SMichal Hocko 
241459dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2415b39415b2SRik van Riel }
2416b39415b2SRik van Riel 
24179a265114SJohannes Weiner enum scan_balance {
24189a265114SJohannes Weiner 	SCAN_EQUAL,
24199a265114SJohannes Weiner 	SCAN_FRACT,
24209a265114SJohannes Weiner 	SCAN_ANON,
24219a265114SJohannes Weiner 	SCAN_FILE,
24229a265114SJohannes Weiner };
24239a265114SJohannes Weiner 
24241da177e4SLinus Torvalds /*
24254f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
24264f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
24274f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
24284f98a2feSRik van Riel  * onto the active list instead of evict.
24294f98a2feSRik van Riel  *
2430be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2431be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
24324f98a2feSRik van Riel  */
2433afaf07a6SJohannes Weiner static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2434afaf07a6SJohannes Weiner 			   unsigned long *nr)
24354f98a2feSRik van Riel {
2436afaf07a6SJohannes Weiner 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2437d483a5ddSJohannes Weiner 	unsigned long anon_cost, file_cost, total_cost;
243833377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
2439ed017373SYu Zhao 	u64 fraction[ANON_AND_FILE];
24409a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
24419a265114SJohannes Weiner 	enum scan_balance scan_balance;
24429a265114SJohannes Weiner 	unsigned long ap, fp;
24439a265114SJohannes Weiner 	enum lru_list lru;
244476a33fc3SShaohua Li 
244576a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2446d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
24479a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
244876a33fc3SShaohua Li 		goto out;
244976a33fc3SShaohua Li 	}
24504f98a2feSRik van Riel 
245110316b31SJohannes Weiner 	/*
245210316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
245310316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
245410316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
245510316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
245610316b31SJohannes Weiner 	 * too expensive.
245710316b31SJohannes Weiner 	 */
2458b5ead35eSJohannes Weiner 	if (cgroup_reclaim(sc) && !swappiness) {
24599a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
246010316b31SJohannes Weiner 		goto out;
246110316b31SJohannes Weiner 	}
246210316b31SJohannes Weiner 
246310316b31SJohannes Weiner 	/*
246410316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
246510316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
246610316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
246710316b31SJohannes Weiner 	 */
246802695175SJohannes Weiner 	if (!sc->priority && swappiness) {
24699a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
247010316b31SJohannes Weiner 		goto out;
247110316b31SJohannes Weiner 	}
247210316b31SJohannes Weiner 
247311d16c25SJohannes Weiner 	/*
247453138ceaSJohannes Weiner 	 * If the system is almost out of file pages, force-scan anon.
247562376251SJohannes Weiner 	 */
2476b91ac374SJohannes Weiner 	if (sc->file_is_tiny) {
247762376251SJohannes Weiner 		scan_balance = SCAN_ANON;
247862376251SJohannes Weiner 		goto out;
247962376251SJohannes Weiner 	}
248062376251SJohannes Weiner 
248162376251SJohannes Weiner 	/*
2482b91ac374SJohannes Weiner 	 * If there is enough inactive page cache, we do not reclaim
2483b91ac374SJohannes Weiner 	 * anything from the anonymous working right now.
2484e9868505SRik van Riel 	 */
2485b91ac374SJohannes Weiner 	if (sc->cache_trim_mode) {
24869a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2487e9868505SRik van Riel 		goto out;
24884f98a2feSRik van Riel 	}
24894f98a2feSRik van Riel 
24909a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
24914f98a2feSRik van Riel 	/*
2492314b57fbSJohannes Weiner 	 * Calculate the pressure balance between anon and file pages.
2493314b57fbSJohannes Weiner 	 *
2494314b57fbSJohannes Weiner 	 * The amount of pressure we put on each LRU is inversely
2495314b57fbSJohannes Weiner 	 * proportional to the cost of reclaiming each list, as
2496314b57fbSJohannes Weiner 	 * determined by the share of pages that are refaulting, times
2497314b57fbSJohannes Weiner 	 * the relative IO cost of bringing back a swapped out
2498314b57fbSJohannes Weiner 	 * anonymous page vs reloading a filesystem page (swappiness).
2499314b57fbSJohannes Weiner 	 *
2500d483a5ddSJohannes Weiner 	 * Although we limit that influence to ensure no list gets
2501d483a5ddSJohannes Weiner 	 * left behind completely: at least a third of the pressure is
2502d483a5ddSJohannes Weiner 	 * applied, before swappiness.
2503d483a5ddSJohannes Weiner 	 *
2504314b57fbSJohannes Weiner 	 * With swappiness at 100, anon and file have equal IO cost.
250558c37f6eSKOSAKI Motohiro 	 */
2506d483a5ddSJohannes Weiner 	total_cost = sc->anon_cost + sc->file_cost;
2507d483a5ddSJohannes Weiner 	anon_cost = total_cost + sc->anon_cost;
2508d483a5ddSJohannes Weiner 	file_cost = total_cost + sc->file_cost;
2509d483a5ddSJohannes Weiner 	total_cost = anon_cost + file_cost;
251058c37f6eSKOSAKI Motohiro 
2511d483a5ddSJohannes Weiner 	ap = swappiness * (total_cost + 1);
2512d483a5ddSJohannes Weiner 	ap /= anon_cost + 1;
25134f98a2feSRik van Riel 
2514d483a5ddSJohannes Weiner 	fp = (200 - swappiness) * (total_cost + 1);
2515d483a5ddSJohannes Weiner 	fp /= file_cost + 1;
25164f98a2feSRik van Riel 
251776a33fc3SShaohua Li 	fraction[0] = ap;
251876a33fc3SShaohua Li 	fraction[1] = fp;
2519a4fe1631SJohannes Weiner 	denominator = ap + fp;
252076a33fc3SShaohua Li out:
25214111304dSHugh Dickins 	for_each_evictable_lru(lru) {
25224111304dSHugh Dickins 		int file = is_file_lru(lru);
25239783aa99SChris Down 		unsigned long lruvec_size;
252476a33fc3SShaohua Li 		unsigned long scan;
25251bc63fb1SChris Down 		unsigned long protection;
252676a33fc3SShaohua Li 
25279783aa99SChris Down 		lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
252822f7496fSYafang Shao 		protection = mem_cgroup_protection(sc->target_mem_cgroup,
252922f7496fSYafang Shao 						   memcg,
25301bc63fb1SChris Down 						   sc->memcg_low_reclaim);
25319783aa99SChris Down 
25321bc63fb1SChris Down 		if (protection) {
25339783aa99SChris Down 			/*
25349783aa99SChris Down 			 * Scale a cgroup's reclaim pressure by proportioning
25359783aa99SChris Down 			 * its current usage to its memory.low or memory.min
25369783aa99SChris Down 			 * setting.
25379783aa99SChris Down 			 *
25389783aa99SChris Down 			 * This is important, as otherwise scanning aggression
25399783aa99SChris Down 			 * becomes extremely binary -- from nothing as we
25409783aa99SChris Down 			 * approach the memory protection threshold, to totally
25419783aa99SChris Down 			 * nominal as we exceed it.  This results in requiring
25429783aa99SChris Down 			 * setting extremely liberal protection thresholds. It
25439783aa99SChris Down 			 * also means we simply get no protection at all if we
25449783aa99SChris Down 			 * set it too low, which is not ideal.
25451bc63fb1SChris Down 			 *
25461bc63fb1SChris Down 			 * If there is any protection in place, we reduce scan
25471bc63fb1SChris Down 			 * pressure by how much of the total memory used is
25481bc63fb1SChris Down 			 * within protection thresholds.
25499783aa99SChris Down 			 *
25509de7ca46SChris Down 			 * There is one special case: in the first reclaim pass,
25519de7ca46SChris Down 			 * we skip over all groups that are within their low
25529de7ca46SChris Down 			 * protection. If that fails to reclaim enough pages to
25539de7ca46SChris Down 			 * satisfy the reclaim goal, we come back and override
25549de7ca46SChris Down 			 * the best-effort low protection. However, we still
25559de7ca46SChris Down 			 * ideally want to honor how well-behaved groups are in
25569de7ca46SChris Down 			 * that case instead of simply punishing them all
25579de7ca46SChris Down 			 * equally. As such, we reclaim them based on how much
25581bc63fb1SChris Down 			 * memory they are using, reducing the scan pressure
25591bc63fb1SChris Down 			 * again by how much of the total memory used is under
25601bc63fb1SChris Down 			 * hard protection.
25619783aa99SChris Down 			 */
25621bc63fb1SChris Down 			unsigned long cgroup_size = mem_cgroup_size(memcg);
25631bc63fb1SChris Down 
25641bc63fb1SChris Down 			/* Avoid TOCTOU with earlier protection check */
25651bc63fb1SChris Down 			cgroup_size = max(cgroup_size, protection);
25661bc63fb1SChris Down 
25671bc63fb1SChris Down 			scan = lruvec_size - lruvec_size * protection /
25681bc63fb1SChris Down 				cgroup_size;
25699783aa99SChris Down 
25709783aa99SChris Down 			/*
25711bc63fb1SChris Down 			 * Minimally target SWAP_CLUSTER_MAX pages to keep
257255b65a57SEthon Paul 			 * reclaim moving forwards, avoiding decrementing
25739de7ca46SChris Down 			 * sc->priority further than desirable.
25749783aa99SChris Down 			 */
25751bc63fb1SChris Down 			scan = max(scan, SWAP_CLUSTER_MAX);
25769783aa99SChris Down 		} else {
25779783aa99SChris Down 			scan = lruvec_size;
25789783aa99SChris Down 		}
25799783aa99SChris Down 
25809783aa99SChris Down 		scan >>= sc->priority;
25819783aa99SChris Down 
2582688035f7SJohannes Weiner 		/*
2583688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2584688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2585688035f7SJohannes Weiner 		 */
2586688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
25879783aa99SChris Down 			scan = min(lruvec_size, SWAP_CLUSTER_MAX);
25889a265114SJohannes Weiner 
25899a265114SJohannes Weiner 		switch (scan_balance) {
25909a265114SJohannes Weiner 		case SCAN_EQUAL:
25919a265114SJohannes Weiner 			/* Scan lists relative to size */
25929a265114SJohannes Weiner 			break;
25939a265114SJohannes Weiner 		case SCAN_FRACT:
25949a265114SJohannes Weiner 			/*
25959a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
25969a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
259776073c64SGavin Shan 			 * Make sure we don't miss the last page on
259876073c64SGavin Shan 			 * the offlined memory cgroups because of a
259976073c64SGavin Shan 			 * round-off error.
26009a265114SJohannes Weiner 			 */
260176073c64SGavin Shan 			scan = mem_cgroup_online(memcg) ?
260276073c64SGavin Shan 			       div64_u64(scan * fraction[file], denominator) :
260376073c64SGavin Shan 			       DIV64_U64_ROUND_UP(scan * fraction[file],
26046f04f48dSSuleiman Souhlal 						  denominator);
26059a265114SJohannes Weiner 			break;
26069a265114SJohannes Weiner 		case SCAN_FILE:
26079a265114SJohannes Weiner 		case SCAN_ANON:
26089a265114SJohannes Weiner 			/* Scan one type exclusively */
2609e072bff6SMateusz Nosek 			if ((scan_balance == SCAN_FILE) != file)
26109a265114SJohannes Weiner 				scan = 0;
26119a265114SJohannes Weiner 			break;
26129a265114SJohannes Weiner 		default:
26139a265114SJohannes Weiner 			/* Look ma, no brain */
26149a265114SJohannes Weiner 			BUG();
26159a265114SJohannes Weiner 		}
26166b4f7799SJohannes Weiner 
26174111304dSHugh Dickins 		nr[lru] = scan;
261876a33fc3SShaohua Li 	}
26196e08a369SWu Fengguang }
26204f98a2feSRik van Riel 
2621afaf07a6SJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
26229b4f98cdSJohannes Weiner {
26239b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2624e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
26259b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
26269b4f98cdSJohannes Weiner 	enum lru_list lru;
26279b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
26289b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
26299b4f98cdSJohannes Weiner 	struct blk_plug plug;
26301a501907SMel Gorman 	bool scan_adjusted;
26319b4f98cdSJohannes Weiner 
2632afaf07a6SJohannes Weiner 	get_scan_count(lruvec, sc, nr);
26339b4f98cdSJohannes Weiner 
2634e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2635e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2636e82e0561SMel Gorman 
26371a501907SMel Gorman 	/*
26381a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
26391a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
26401a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
26411a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
26421a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
26431a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
26441a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
26451a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
26461a501907SMel Gorman 	 * dropped to zero at the first pass.
26471a501907SMel Gorman 	 */
2648b5ead35eSJohannes Weiner 	scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
26491a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
26501a501907SMel Gorman 
26519b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
26529b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
26539b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2654e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2655e82e0561SMel Gorman 		unsigned long nr_scanned;
2656e82e0561SMel Gorman 
26579b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
26589b4f98cdSJohannes Weiner 			if (nr[lru]) {
26599b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
26609b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
26619b4f98cdSJohannes Weiner 
26629b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
26633b991208SJohannes Weiner 							    lruvec, sc);
26649b4f98cdSJohannes Weiner 			}
26659b4f98cdSJohannes Weiner 		}
2666e82e0561SMel Gorman 
2667bd041733SMichal Hocko 		cond_resched();
2668bd041733SMichal Hocko 
2669e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2670e82e0561SMel Gorman 			continue;
2671e82e0561SMel Gorman 
26729b4f98cdSJohannes Weiner 		/*
2673e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
26741a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2675e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2676e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2677e82e0561SMel Gorman 		 * proportional to the original scan target.
2678e82e0561SMel Gorman 		 */
2679e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2680e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2681e82e0561SMel Gorman 
26821a501907SMel Gorman 		/*
26831a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
26841a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
26851a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
26861a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
26871a501907SMel Gorman 		 */
26881a501907SMel Gorman 		if (!nr_file || !nr_anon)
26891a501907SMel Gorman 			break;
26901a501907SMel Gorman 
2691e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2692e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2693e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2694e82e0561SMel Gorman 			lru = LRU_BASE;
2695e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2696e82e0561SMel Gorman 		} else {
2697e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2698e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2699e82e0561SMel Gorman 			lru = LRU_FILE;
2700e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2701e82e0561SMel Gorman 		}
2702e82e0561SMel Gorman 
2703e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2704e82e0561SMel Gorman 		nr[lru] = 0;
2705e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2706e82e0561SMel Gorman 
2707e82e0561SMel Gorman 		/*
2708e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2709e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2710e82e0561SMel Gorman 		 */
2711e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2712e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2713e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2714e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2715e82e0561SMel Gorman 
2716e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2717e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2718e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2719e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2720e82e0561SMel Gorman 
2721e82e0561SMel Gorman 		scan_adjusted = true;
27229b4f98cdSJohannes Weiner 	}
27239b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
27249b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
27259b4f98cdSJohannes Weiner 
27269b4f98cdSJohannes Weiner 	/*
27279b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
27289b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
27299b4f98cdSJohannes Weiner 	 */
2730b91ac374SJohannes Weiner 	if (total_swap_pages && inactive_is_low(lruvec, LRU_INACTIVE_ANON))
27319b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
27329b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
27339b4f98cdSJohannes Weiner }
27349b4f98cdSJohannes Weiner 
273523b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
27369e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
273723b9da55SMel Gorman {
2738d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
273923b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
27409e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
274123b9da55SMel Gorman 		return true;
274223b9da55SMel Gorman 
274323b9da55SMel Gorman 	return false;
274423b9da55SMel Gorman }
274523b9da55SMel Gorman 
27464f98a2feSRik van Riel /*
274723b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
274823b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
274923b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
2750df3a45f9SQiwu Chen  * calls try_to_compact_pages() that it will have enough free pages to succeed.
275123b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
27523e7d3449SMel Gorman  */
2753a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
27543e7d3449SMel Gorman 					unsigned long nr_reclaimed,
27553e7d3449SMel Gorman 					struct scan_control *sc)
27563e7d3449SMel Gorman {
27573e7d3449SMel Gorman 	unsigned long pages_for_compaction;
27583e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2759a9dd0a83SMel Gorman 	int z;
27603e7d3449SMel Gorman 
27613e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
27629e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
27633e7d3449SMel Gorman 		return false;
27643e7d3449SMel Gorman 
27653e7d3449SMel Gorman 	/*
27665ee04716SVlastimil Babka 	 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
27675ee04716SVlastimil Babka 	 * number of pages that were scanned. This will return to the caller
27685ee04716SVlastimil Babka 	 * with the risk reclaim/compaction and the resulting allocation attempt
27695ee04716SVlastimil Babka 	 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
27705ee04716SVlastimil Babka 	 * allocations through requiring that the full LRU list has been scanned
27715ee04716SVlastimil Babka 	 * first, by assuming that zero delta of sc->nr_scanned means full LRU
27725ee04716SVlastimil Babka 	 * scan, but that approximation was wrong, and there were corner cases
27735ee04716SVlastimil Babka 	 * where always a non-zero amount of pages were scanned.
27742876592fSMel Gorman 	 */
27752876592fSMel Gorman 	if (!nr_reclaimed)
27762876592fSMel Gorman 		return false;
27773e7d3449SMel Gorman 
27783e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2779a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2780a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
27816aa303deSMel Gorman 		if (!managed_zone(zone))
2782a9dd0a83SMel Gorman 			continue;
2783a9dd0a83SMel Gorman 
2784a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2785cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
27863e7d3449SMel Gorman 		case COMPACT_CONTINUE:
27873e7d3449SMel Gorman 			return false;
27883e7d3449SMel Gorman 		default:
2789a9dd0a83SMel Gorman 			/* check next zone */
2790a9dd0a83SMel Gorman 			;
27913e7d3449SMel Gorman 		}
27923e7d3449SMel Gorman 	}
27931c6c1597SHillf Danton 
27941c6c1597SHillf Danton 	/*
27951c6c1597SHillf Danton 	 * If we have not reclaimed enough pages for compaction and the
27961c6c1597SHillf Danton 	 * inactive lists are large enough, continue reclaiming
27971c6c1597SHillf Danton 	 */
27981c6c1597SHillf Danton 	pages_for_compaction = compact_gap(sc->order);
27991c6c1597SHillf Danton 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
28001c6c1597SHillf Danton 	if (get_nr_swap_pages() > 0)
28011c6c1597SHillf Danton 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
28021c6c1597SHillf Danton 
28035ee04716SVlastimil Babka 	return inactive_lru_pages > pages_for_compaction;
2804a9dd0a83SMel Gorman }
28053e7d3449SMel Gorman 
28060f6a5cffSJohannes Weiner static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
2807f16015fbSJohannes Weiner {
28080f6a5cffSJohannes Weiner 	struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
2809694fbc0fSAndrew Morton 	struct mem_cgroup *memcg;
2810d108c772SAndrey Ryabinin 
28110f6a5cffSJohannes Weiner 	memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
2812694fbc0fSAndrew Morton 	do {
2813afaf07a6SJohannes Weiner 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
28148e8ae645SJohannes Weiner 		unsigned long reclaimed;
2815cb731d6cSVladimir Davydov 		unsigned long scanned;
28169b4f98cdSJohannes Weiner 
2817e3336cabSXunlei Pang 		/*
2818e3336cabSXunlei Pang 		 * This loop can become CPU-bound when target memcgs
2819e3336cabSXunlei Pang 		 * aren't eligible for reclaim - either because they
2820e3336cabSXunlei Pang 		 * don't have any reclaimable pages, or because their
2821e3336cabSXunlei Pang 		 * memory is explicitly protected. Avoid soft lockups.
2822e3336cabSXunlei Pang 		 */
2823e3336cabSXunlei Pang 		cond_resched();
2824e3336cabSXunlei Pang 
282545c7f7e1SChris Down 		mem_cgroup_calculate_protection(target_memcg, memcg);
282645c7f7e1SChris Down 
282745c7f7e1SChris Down 		if (mem_cgroup_below_min(memcg)) {
2828bf8d5d52SRoman Gushchin 			/*
2829bf8d5d52SRoman Gushchin 			 * Hard protection.
2830bf8d5d52SRoman Gushchin 			 * If there is no reclaimable memory, OOM.
2831bf8d5d52SRoman Gushchin 			 */
2832bf8d5d52SRoman Gushchin 			continue;
283345c7f7e1SChris Down 		} else if (mem_cgroup_below_low(memcg)) {
2834bf8d5d52SRoman Gushchin 			/*
2835bf8d5d52SRoman Gushchin 			 * Soft protection.
2836bf8d5d52SRoman Gushchin 			 * Respect the protection only as long as
2837bf8d5d52SRoman Gushchin 			 * there is an unprotected supply
2838bf8d5d52SRoman Gushchin 			 * of reclaimable memory from other cgroups.
2839bf8d5d52SRoman Gushchin 			 */
2840d6622f63SYisheng Xie 			if (!sc->memcg_low_reclaim) {
2841d6622f63SYisheng Xie 				sc->memcg_low_skipped = 1;
2842241994edSJohannes Weiner 				continue;
2843d6622f63SYisheng Xie 			}
2844e27be240SJohannes Weiner 			memcg_memory_event(memcg, MEMCG_LOW);
2845241994edSJohannes Weiner 		}
2846241994edSJohannes Weiner 
28478e8ae645SJohannes Weiner 		reclaimed = sc->nr_reclaimed;
2848cb731d6cSVladimir Davydov 		scanned = sc->nr_scanned;
2849afaf07a6SJohannes Weiner 
2850afaf07a6SJohannes Weiner 		shrink_lruvec(lruvec, sc);
2851f9be23d6SKonstantin Khlebnikov 
285228360f39SMel Gorman 		shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
285328360f39SMel Gorman 			    sc->priority);
2854cb731d6cSVladimir Davydov 
28558e8ae645SJohannes Weiner 		/* Record the group's reclaim efficiency */
28568e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, memcg, false,
28578e8ae645SJohannes Weiner 			   sc->nr_scanned - scanned,
28588e8ae645SJohannes Weiner 			   sc->nr_reclaimed - reclaimed);
28598e8ae645SJohannes Weiner 
28600f6a5cffSJohannes Weiner 	} while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
28610f6a5cffSJohannes Weiner }
28620f6a5cffSJohannes Weiner 
28636c9e0907SLiu Song static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
28640f6a5cffSJohannes Weiner {
28650f6a5cffSJohannes Weiner 	struct reclaim_state *reclaim_state = current->reclaim_state;
28660f6a5cffSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
28671b05117dSJohannes Weiner 	struct lruvec *target_lruvec;
28680f6a5cffSJohannes Weiner 	bool reclaimable = false;
2869b91ac374SJohannes Weiner 	unsigned long file;
28700f6a5cffSJohannes Weiner 
28711b05117dSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
28721b05117dSJohannes Weiner 
28730f6a5cffSJohannes Weiner again:
28740f6a5cffSJohannes Weiner 	memset(&sc->nr, 0, sizeof(sc->nr));
28750f6a5cffSJohannes Weiner 
28760f6a5cffSJohannes Weiner 	nr_reclaimed = sc->nr_reclaimed;
28770f6a5cffSJohannes Weiner 	nr_scanned = sc->nr_scanned;
28780f6a5cffSJohannes Weiner 
287953138ceaSJohannes Weiner 	/*
28807cf111bcSJohannes Weiner 	 * Determine the scan balance between anon and file LRUs.
28817cf111bcSJohannes Weiner 	 */
28826168d0daSAlex Shi 	spin_lock_irq(&target_lruvec->lru_lock);
28837cf111bcSJohannes Weiner 	sc->anon_cost = target_lruvec->anon_cost;
28847cf111bcSJohannes Weiner 	sc->file_cost = target_lruvec->file_cost;
28856168d0daSAlex Shi 	spin_unlock_irq(&target_lruvec->lru_lock);
28867cf111bcSJohannes Weiner 
28877cf111bcSJohannes Weiner 	/*
2888b91ac374SJohannes Weiner 	 * Target desirable inactive:active list ratios for the anon
2889b91ac374SJohannes Weiner 	 * and file LRU lists.
2890b91ac374SJohannes Weiner 	 */
2891b91ac374SJohannes Weiner 	if (!sc->force_deactivate) {
2892b91ac374SJohannes Weiner 		unsigned long refaults;
2893b91ac374SJohannes Weiner 
2894170b04b7SJoonsoo Kim 		refaults = lruvec_page_state(target_lruvec,
2895170b04b7SJoonsoo Kim 				WORKINGSET_ACTIVATE_ANON);
2896170b04b7SJoonsoo Kim 		if (refaults != target_lruvec->refaults[0] ||
2897170b04b7SJoonsoo Kim 			inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2898b91ac374SJohannes Weiner 			sc->may_deactivate |= DEACTIVATE_ANON;
2899b91ac374SJohannes Weiner 		else
2900b91ac374SJohannes Weiner 			sc->may_deactivate &= ~DEACTIVATE_ANON;
2901b91ac374SJohannes Weiner 
2902b91ac374SJohannes Weiner 		/*
2903b91ac374SJohannes Weiner 		 * When refaults are being observed, it means a new
2904b91ac374SJohannes Weiner 		 * workingset is being established. Deactivate to get
2905b91ac374SJohannes Weiner 		 * rid of any stale active pages quickly.
2906b91ac374SJohannes Weiner 		 */
2907b91ac374SJohannes Weiner 		refaults = lruvec_page_state(target_lruvec,
2908170b04b7SJoonsoo Kim 				WORKINGSET_ACTIVATE_FILE);
2909170b04b7SJoonsoo Kim 		if (refaults != target_lruvec->refaults[1] ||
2910b91ac374SJohannes Weiner 		    inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2911b91ac374SJohannes Weiner 			sc->may_deactivate |= DEACTIVATE_FILE;
2912b91ac374SJohannes Weiner 		else
2913b91ac374SJohannes Weiner 			sc->may_deactivate &= ~DEACTIVATE_FILE;
2914b91ac374SJohannes Weiner 	} else
2915b91ac374SJohannes Weiner 		sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2916b91ac374SJohannes Weiner 
2917b91ac374SJohannes Weiner 	/*
2918b91ac374SJohannes Weiner 	 * If we have plenty of inactive file pages that aren't
2919b91ac374SJohannes Weiner 	 * thrashing, try to reclaim those first before touching
2920b91ac374SJohannes Weiner 	 * anonymous pages.
2921b91ac374SJohannes Weiner 	 */
2922b91ac374SJohannes Weiner 	file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2923b91ac374SJohannes Weiner 	if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2924b91ac374SJohannes Weiner 		sc->cache_trim_mode = 1;
2925b91ac374SJohannes Weiner 	else
2926b91ac374SJohannes Weiner 		sc->cache_trim_mode = 0;
2927b91ac374SJohannes Weiner 
2928b91ac374SJohannes Weiner 	/*
292953138ceaSJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
293053138ceaSJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
293153138ceaSJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
293253138ceaSJohannes Weiner 	 * shrinks, so does the window for rotation from references.
293353138ceaSJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
293453138ceaSJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
293553138ceaSJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
293653138ceaSJohannes Weiner 	 */
293753138ceaSJohannes Weiner 	if (!cgroup_reclaim(sc)) {
293853138ceaSJohannes Weiner 		unsigned long total_high_wmark = 0;
2939b91ac374SJohannes Weiner 		unsigned long free, anon;
2940b91ac374SJohannes Weiner 		int z;
294153138ceaSJohannes Weiner 
294253138ceaSJohannes Weiner 		free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
294353138ceaSJohannes Weiner 		file = node_page_state(pgdat, NR_ACTIVE_FILE) +
294453138ceaSJohannes Weiner 			   node_page_state(pgdat, NR_INACTIVE_FILE);
294553138ceaSJohannes Weiner 
294653138ceaSJohannes Weiner 		for (z = 0; z < MAX_NR_ZONES; z++) {
294753138ceaSJohannes Weiner 			struct zone *zone = &pgdat->node_zones[z];
294853138ceaSJohannes Weiner 			if (!managed_zone(zone))
294953138ceaSJohannes Weiner 				continue;
295053138ceaSJohannes Weiner 
295153138ceaSJohannes Weiner 			total_high_wmark += high_wmark_pages(zone);
295253138ceaSJohannes Weiner 		}
295353138ceaSJohannes Weiner 
2954b91ac374SJohannes Weiner 		/*
2955b91ac374SJohannes Weiner 		 * Consider anon: if that's low too, this isn't a
2956b91ac374SJohannes Weiner 		 * runaway file reclaim problem, but rather just
2957b91ac374SJohannes Weiner 		 * extreme pressure. Reclaim as per usual then.
2958b91ac374SJohannes Weiner 		 */
2959b91ac374SJohannes Weiner 		anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2960b91ac374SJohannes Weiner 
2961b91ac374SJohannes Weiner 		sc->file_is_tiny =
2962b91ac374SJohannes Weiner 			file + free <= total_high_wmark &&
2963b91ac374SJohannes Weiner 			!(sc->may_deactivate & DEACTIVATE_ANON) &&
2964b91ac374SJohannes Weiner 			anon >> sc->priority;
296553138ceaSJohannes Weiner 	}
296653138ceaSJohannes Weiner 
29670f6a5cffSJohannes Weiner 	shrink_node_memcgs(pgdat, sc);
296870ddf637SAnton Vorontsov 
29696b4f7799SJohannes Weiner 	if (reclaim_state) {
2970cb731d6cSVladimir Davydov 		sc->nr_reclaimed += reclaim_state->reclaimed_slab;
29716b4f7799SJohannes Weiner 		reclaim_state->reclaimed_slab = 0;
29726b4f7799SJohannes Weiner 	}
29736b4f7799SJohannes Weiner 
29748e8ae645SJohannes Weiner 	/* Record the subtree's reclaim efficiency */
29751b05117dSJohannes Weiner 	vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
297670ddf637SAnton Vorontsov 		   sc->nr_scanned - nr_scanned,
297770ddf637SAnton Vorontsov 		   sc->nr_reclaimed - nr_reclaimed);
297870ddf637SAnton Vorontsov 
29792344d7e4SJohannes Weiner 	if (sc->nr_reclaimed - nr_reclaimed)
29802344d7e4SJohannes Weiner 		reclaimable = true;
29812344d7e4SJohannes Weiner 
2982e3c1ac58SAndrey Ryabinin 	if (current_is_kswapd()) {
2983d108c772SAndrey Ryabinin 		/*
2984e3c1ac58SAndrey Ryabinin 		 * If reclaim is isolating dirty pages under writeback,
2985e3c1ac58SAndrey Ryabinin 		 * it implies that the long-lived page allocation rate
2986e3c1ac58SAndrey Ryabinin 		 * is exceeding the page laundering rate. Either the
2987e3c1ac58SAndrey Ryabinin 		 * global limits are not being effective at throttling
2988e3c1ac58SAndrey Ryabinin 		 * processes due to the page distribution throughout
2989e3c1ac58SAndrey Ryabinin 		 * zones or there is heavy usage of a slow backing
2990e3c1ac58SAndrey Ryabinin 		 * device. The only option is to throttle from reclaim
2991e3c1ac58SAndrey Ryabinin 		 * context which is not ideal as there is no guarantee
2992d108c772SAndrey Ryabinin 		 * the dirtying process is throttled in the same way
2993d108c772SAndrey Ryabinin 		 * balance_dirty_pages() manages.
2994d108c772SAndrey Ryabinin 		 *
2995e3c1ac58SAndrey Ryabinin 		 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
2996e3c1ac58SAndrey Ryabinin 		 * count the number of pages under pages flagged for
2997e3c1ac58SAndrey Ryabinin 		 * immediate reclaim and stall if any are encountered
2998e3c1ac58SAndrey Ryabinin 		 * in the nr_immediate check below.
2999d108c772SAndrey Ryabinin 		 */
3000d108c772SAndrey Ryabinin 		if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
3001d108c772SAndrey Ryabinin 			set_bit(PGDAT_WRITEBACK, &pgdat->flags);
3002d108c772SAndrey Ryabinin 
3003d108c772SAndrey Ryabinin 		/* Allow kswapd to start writing pages during reclaim.*/
3004d108c772SAndrey Ryabinin 		if (sc->nr.unqueued_dirty == sc->nr.file_taken)
3005d108c772SAndrey Ryabinin 			set_bit(PGDAT_DIRTY, &pgdat->flags);
3006d108c772SAndrey Ryabinin 
3007d108c772SAndrey Ryabinin 		/*
30081eba09c1SRandy Dunlap 		 * If kswapd scans pages marked for immediate
3009d108c772SAndrey Ryabinin 		 * reclaim and under writeback (nr_immediate), it
3010d108c772SAndrey Ryabinin 		 * implies that pages are cycling through the LRU
3011d108c772SAndrey Ryabinin 		 * faster than they are written so also forcibly stall.
3012d108c772SAndrey Ryabinin 		 */
3013d108c772SAndrey Ryabinin 		if (sc->nr.immediate)
3014d108c772SAndrey Ryabinin 			congestion_wait(BLK_RW_ASYNC, HZ/10);
3015d108c772SAndrey Ryabinin 	}
3016d108c772SAndrey Ryabinin 
3017d108c772SAndrey Ryabinin 	/*
30181b05117dSJohannes Weiner 	 * Tag a node/memcg as congested if all the dirty pages
30191b05117dSJohannes Weiner 	 * scanned were backed by a congested BDI and
30201b05117dSJohannes Weiner 	 * wait_iff_congested will stall.
30211b05117dSJohannes Weiner 	 *
3022e3c1ac58SAndrey Ryabinin 	 * Legacy memcg will stall in page writeback so avoid forcibly
3023e3c1ac58SAndrey Ryabinin 	 * stalling in wait_iff_congested().
3024e3c1ac58SAndrey Ryabinin 	 */
30251b05117dSJohannes Weiner 	if ((current_is_kswapd() ||
30261b05117dSJohannes Weiner 	     (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
3027e3c1ac58SAndrey Ryabinin 	    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
30281b05117dSJohannes Weiner 		set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
3029e3c1ac58SAndrey Ryabinin 
3030e3c1ac58SAndrey Ryabinin 	/*
3031d108c772SAndrey Ryabinin 	 * Stall direct reclaim for IO completions if underlying BDIs
3032d108c772SAndrey Ryabinin 	 * and node is congested. Allow kswapd to continue until it
3033d108c772SAndrey Ryabinin 	 * starts encountering unqueued dirty pages or cycling through
3034d108c772SAndrey Ryabinin 	 * the LRU too quickly.
3035d108c772SAndrey Ryabinin 	 */
30361b05117dSJohannes Weiner 	if (!current_is_kswapd() && current_may_throttle() &&
30371b05117dSJohannes Weiner 	    !sc->hibernation_mode &&
30381b05117dSJohannes Weiner 	    test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
3039e3c1ac58SAndrey Ryabinin 		wait_iff_congested(BLK_RW_ASYNC, HZ/10);
3040d108c772SAndrey Ryabinin 
3041d2af3397SJohannes Weiner 	if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
3042d2af3397SJohannes Weiner 				    sc))
3043d2af3397SJohannes Weiner 		goto again;
30442344d7e4SJohannes Weiner 
3045c73322d0SJohannes Weiner 	/*
3046c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
3047c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
3048c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
3049c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
3050c73322d0SJohannes Weiner 	 */
3051c73322d0SJohannes Weiner 	if (reclaimable)
3052c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
3053f16015fbSJohannes Weiner }
3054f16015fbSJohannes Weiner 
305553853e2dSVlastimil Babka /*
3056fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
3057fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
3058fdd4c614SVlastimil Babka  * should reclaim first.
305953853e2dSVlastimil Babka  */
30604f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
3061fe4b1b24SMel Gorman {
306231483b6aSMel Gorman 	unsigned long watermark;
3063fdd4c614SVlastimil Babka 	enum compact_result suitable;
3064fe4b1b24SMel Gorman 
3065fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
3066fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
3067fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
3068fdd4c614SVlastimil Babka 		return true;
3069fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
3070fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
3071fe4b1b24SMel Gorman 		return false;
3072fe4b1b24SMel Gorman 
3073fdd4c614SVlastimil Babka 	/*
3074fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
3075fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
3076fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
3077fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
3078fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
3079fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
3080fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
3081fdd4c614SVlastimil Babka 	 */
3082fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
3083fdd4c614SVlastimil Babka 
3084fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
3085fe4b1b24SMel Gorman }
3086fe4b1b24SMel Gorman 
30871da177e4SLinus Torvalds /*
30881da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
30891da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
30901da177e4SLinus Torvalds  * request.
30911da177e4SLinus Torvalds  *
30921da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
30931da177e4SLinus Torvalds  * scan then give up on it.
30941da177e4SLinus Torvalds  */
30950a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
30961da177e4SLinus Torvalds {
3097dd1a239fSMel Gorman 	struct zoneref *z;
309854a6eb5cSMel Gorman 	struct zone *zone;
30990608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
31000608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3101619d0d76SWeijie Yang 	gfp_t orig_mask;
310279dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
31031cfb419bSKAMEZAWA Hiroyuki 
3104cc715d99SMel Gorman 	/*
3105cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
3106cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
3107cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
3108cc715d99SMel Gorman 	 */
3109619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
3110b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
3111cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
31124f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
3113b2e18757SMel Gorman 	}
3114cc715d99SMel Gorman 
3115d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
3116b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
3117b2e18757SMel Gorman 		/*
31181cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
31191cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
31201cfb419bSKAMEZAWA Hiroyuki 		 */
3121b5ead35eSJohannes Weiner 		if (!cgroup_reclaim(sc)) {
3122344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
3123344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
31241da177e4SLinus Torvalds 				continue;
312565ec02cbSVladimir Davydov 
3126e0887c19SRik van Riel 			/*
3127e0c23279SMel Gorman 			 * If we already have plenty of memory free for
3128e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
3129e0c23279SMel Gorman 			 * Even though compaction is invoked for any
3130e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
3131e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
3132c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
3133c7cfa37bSCopot Alexandru 			 * page allocations.
3134e0887c19SRik van Riel 			 */
31350b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
31360b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
31374f588331SMel Gorman 			    compaction_ready(zone, sc)) {
31380b06496aSJohannes Weiner 				sc->compaction_ready = true;
3139e0887c19SRik van Riel 				continue;
3140e0887c19SRik van Riel 			}
31410b06496aSJohannes Weiner 
31420608f43dSAndrew Morton 			/*
314379dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
314479dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
314579dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
314679dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
314779dafcdcSMel Gorman 			 */
314879dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
314979dafcdcSMel Gorman 				continue;
315079dafcdcSMel Gorman 
315179dafcdcSMel Gorman 			/*
31520608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
31530608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
31540608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
31550608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
31560608f43dSAndrew Morton 			 */
31570608f43dSAndrew Morton 			nr_soft_scanned = 0;
3158ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
31590608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
31600608f43dSAndrew Morton 						&nr_soft_scanned);
31610608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
31620608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
3163ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
3164ac34a1a3SKAMEZAWA Hiroyuki 		}
3165d149e3b2SYing Han 
316679dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
316779dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
316879dafcdcSMel Gorman 			continue;
316979dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
3170970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
31711da177e4SLinus Torvalds 	}
3172e0c23279SMel Gorman 
317365ec02cbSVladimir Davydov 	/*
3174619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
3175619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
3176619d0d76SWeijie Yang 	 */
3177619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
31781da177e4SLinus Torvalds }
31791da177e4SLinus Torvalds 
3180b910718aSJohannes Weiner static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
31812a2e4885SJohannes Weiner {
3182b910718aSJohannes Weiner 	struct lruvec *target_lruvec;
31832a2e4885SJohannes Weiner 	unsigned long refaults;
31842a2e4885SJohannes Weiner 
3185b910718aSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
3186170b04b7SJoonsoo Kim 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
3187170b04b7SJoonsoo Kim 	target_lruvec->refaults[0] = refaults;
3188170b04b7SJoonsoo Kim 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
3189170b04b7SJoonsoo Kim 	target_lruvec->refaults[1] = refaults;
31902a2e4885SJohannes Weiner }
31912a2e4885SJohannes Weiner 
31921da177e4SLinus Torvalds /*
31931da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
31941da177e4SLinus Torvalds  *
31951da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
31961da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
31971da177e4SLinus Torvalds  *
31981da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
31991da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
32005b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
32015b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
32025b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
32035b0830cbSJens Axboe  * work, and the allocation attempt will fail.
3204a41f24eaSNishanth Aravamudan  *
3205a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
3206a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
32071da177e4SLinus Torvalds  */
3208dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
32093115cd91SVladimir Davydov 					  struct scan_control *sc)
32101da177e4SLinus Torvalds {
3211241994edSJohannes Weiner 	int initial_priority = sc->priority;
32122a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
32132a2e4885SJohannes Weiner 	struct zoneref *z;
32142a2e4885SJohannes Weiner 	struct zone *zone;
3215241994edSJohannes Weiner retry:
3216873b4771SKeika Kobayashi 	delayacct_freepages_start();
3217873b4771SKeika Kobayashi 
3218b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
32197cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
32201da177e4SLinus Torvalds 
32219e3b2f8cSKonstantin Khlebnikov 	do {
322270ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
322370ddf637SAnton Vorontsov 				sc->priority);
322466e1707bSBalbir Singh 		sc->nr_scanned = 0;
32250a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
3226e0c23279SMel Gorman 
3227bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
32280b06496aSJohannes Weiner 			break;
32290b06496aSJohannes Weiner 
32300b06496aSJohannes Weiner 		if (sc->compaction_ready)
32310b06496aSJohannes Weiner 			break;
32321da177e4SLinus Torvalds 
32331da177e4SLinus Torvalds 		/*
32340e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
32350e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
32360e50ce3bSMinchan Kim 		 */
32370e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
32380e50ce3bSMinchan Kim 			sc->may_writepage = 1;
32390b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
3240bb21c7ceSKOSAKI Motohiro 
32412a2e4885SJohannes Weiner 	last_pgdat = NULL;
32422a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
32432a2e4885SJohannes Weiner 					sc->nodemask) {
32442a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
32452a2e4885SJohannes Weiner 			continue;
32462a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
32471b05117dSJohannes Weiner 
32482a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
32491b05117dSJohannes Weiner 
32501b05117dSJohannes Weiner 		if (cgroup_reclaim(sc)) {
32511b05117dSJohannes Weiner 			struct lruvec *lruvec;
32521b05117dSJohannes Weiner 
32531b05117dSJohannes Weiner 			lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
32541b05117dSJohannes Weiner 						   zone->zone_pgdat);
32551b05117dSJohannes Weiner 			clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
32561b05117dSJohannes Weiner 		}
32572a2e4885SJohannes Weiner 	}
32582a2e4885SJohannes Weiner 
3259873b4771SKeika Kobayashi 	delayacct_freepages_end();
3260873b4771SKeika Kobayashi 
3261bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
3262bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
3263bb21c7ceSKOSAKI Motohiro 
32640cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
32650b06496aSJohannes Weiner 	if (sc->compaction_ready)
32667335084dSMel Gorman 		return 1;
32677335084dSMel Gorman 
3268b91ac374SJohannes Weiner 	/*
3269b91ac374SJohannes Weiner 	 * We make inactive:active ratio decisions based on the node's
3270b91ac374SJohannes Weiner 	 * composition of memory, but a restrictive reclaim_idx or a
3271b91ac374SJohannes Weiner 	 * memory.low cgroup setting can exempt large amounts of
3272b91ac374SJohannes Weiner 	 * memory from reclaim. Neither of which are very common, so
3273b91ac374SJohannes Weiner 	 * instead of doing costly eligibility calculations of the
3274b91ac374SJohannes Weiner 	 * entire cgroup subtree up front, we assume the estimates are
3275b91ac374SJohannes Weiner 	 * good, and retry with forcible deactivation if that fails.
3276b91ac374SJohannes Weiner 	 */
3277b91ac374SJohannes Weiner 	if (sc->skipped_deactivate) {
3278b91ac374SJohannes Weiner 		sc->priority = initial_priority;
3279b91ac374SJohannes Weiner 		sc->force_deactivate = 1;
3280b91ac374SJohannes Weiner 		sc->skipped_deactivate = 0;
3281b91ac374SJohannes Weiner 		goto retry;
3282b91ac374SJohannes Weiner 	}
3283b91ac374SJohannes Weiner 
3284241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
3285d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
3286241994edSJohannes Weiner 		sc->priority = initial_priority;
3287b91ac374SJohannes Weiner 		sc->force_deactivate = 0;
3288d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
3289d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
3290241994edSJohannes Weiner 		goto retry;
3291241994edSJohannes Weiner 	}
3292241994edSJohannes Weiner 
3293bb21c7ceSKOSAKI Motohiro 	return 0;
32941da177e4SLinus Torvalds }
32951da177e4SLinus Torvalds 
3296c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
32975515061dSMel Gorman {
32985515061dSMel Gorman 	struct zone *zone;
32995515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
33005515061dSMel Gorman 	unsigned long free_pages = 0;
33015515061dSMel Gorman 	int i;
33025515061dSMel Gorman 	bool wmark_ok;
33035515061dSMel Gorman 
3304c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3305c73322d0SJohannes Weiner 		return true;
3306c73322d0SJohannes Weiner 
33075515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
33085515061dSMel Gorman 		zone = &pgdat->node_zones[i];
3309d450abd8SJohannes Weiner 		if (!managed_zone(zone))
3310d450abd8SJohannes Weiner 			continue;
3311d450abd8SJohannes Weiner 
3312d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
3313675becceSMel Gorman 			continue;
3314675becceSMel Gorman 
33155515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
33165515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
33175515061dSMel Gorman 	}
33185515061dSMel Gorman 
3319675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
3320675becceSMel Gorman 	if (!pfmemalloc_reserve)
3321675becceSMel Gorman 		return true;
3322675becceSMel Gorman 
33235515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
33245515061dSMel Gorman 
33255515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
33265515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
332797a225e6SJoonsoo Kim 		if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
332897a225e6SJoonsoo Kim 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
33295644e1fbSQian Cai 
33305515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
33315515061dSMel Gorman 	}
33325515061dSMel Gorman 
33335515061dSMel Gorman 	return wmark_ok;
33345515061dSMel Gorman }
33355515061dSMel Gorman 
33365515061dSMel Gorman /*
33375515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
33385515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
33395515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
334050694c28SMel Gorman  * when the low watermark is reached.
334150694c28SMel Gorman  *
334250694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
334350694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
33445515061dSMel Gorman  */
334550694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
33465515061dSMel Gorman 					nodemask_t *nodemask)
33475515061dSMel Gorman {
3348675becceSMel Gorman 	struct zoneref *z;
33495515061dSMel Gorman 	struct zone *zone;
3350675becceSMel Gorman 	pg_data_t *pgdat = NULL;
33515515061dSMel Gorman 
33525515061dSMel Gorman 	/*
33535515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
33545515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
33555515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
33565515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
33575515061dSMel Gorman 	 * processes to block on log_wait_commit().
33585515061dSMel Gorman 	 */
33595515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
336050694c28SMel Gorman 		goto out;
336150694c28SMel Gorman 
336250694c28SMel Gorman 	/*
336350694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
336450694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
336550694c28SMel Gorman 	 */
336650694c28SMel Gorman 	if (fatal_signal_pending(current))
336750694c28SMel Gorman 		goto out;
33685515061dSMel Gorman 
3369675becceSMel Gorman 	/*
3370675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
3371675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3372675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
3373675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
3374675becceSMel Gorman 	 *
3375675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
3376675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
3377675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
3378675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
3379675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
3380675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
3381675becceSMel Gorman 	 * should make reasonable progress.
3382675becceSMel Gorman 	 */
3383675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
338417636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
3385675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
3386675becceSMel Gorman 			continue;
3387675becceSMel Gorman 
3388675becceSMel Gorman 		/* Throttle based on the first usable node */
33895515061dSMel Gorman 		pgdat = zone->zone_pgdat;
3390c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
339150694c28SMel Gorman 			goto out;
3392675becceSMel Gorman 		break;
3393675becceSMel Gorman 	}
3394675becceSMel Gorman 
3395675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
3396675becceSMel Gorman 	if (!pgdat)
3397675becceSMel Gorman 		goto out;
33985515061dSMel Gorman 
339968243e76SMel Gorman 	/* Account for the throttling */
340068243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
340168243e76SMel Gorman 
34025515061dSMel Gorman 	/*
34035515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
34045515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
34055515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
34065515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
34075515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
34085515061dSMel Gorman 	 * second before continuing.
34095515061dSMel Gorman 	 */
34105515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
34115515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3412c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
341350694c28SMel Gorman 
341450694c28SMel Gorman 		goto check_pending;
34155515061dSMel Gorman 	}
34165515061dSMel Gorman 
34175515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
34185515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3419c73322d0SJohannes Weiner 		allow_direct_reclaim(pgdat));
342050694c28SMel Gorman 
342150694c28SMel Gorman check_pending:
342250694c28SMel Gorman 	if (fatal_signal_pending(current))
342350694c28SMel Gorman 		return true;
342450694c28SMel Gorman 
342550694c28SMel Gorman out:
342650694c28SMel Gorman 	return false;
34275515061dSMel Gorman }
34285515061dSMel Gorman 
3429dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3430327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
343166e1707bSBalbir Singh {
343233906bc5SMel Gorman 	unsigned long nr_reclaimed;
343366e1707bSBalbir Singh 	struct scan_control sc = {
343422fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3435f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3436b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
3437ee814fe2SJohannes Weiner 		.order = order,
3438ee814fe2SJohannes Weiner 		.nodemask = nodemask,
3439ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
3440ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3441a6dc60f8SJohannes Weiner 		.may_unmap = 1,
34422e2e4259SKOSAKI Motohiro 		.may_swap = 1,
344366e1707bSBalbir Singh 	};
344466e1707bSBalbir Singh 
34455515061dSMel Gorman 	/*
3446bb451fdfSGreg Thelen 	 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3447bb451fdfSGreg Thelen 	 * Confirm they are large enough for max values.
3448bb451fdfSGreg Thelen 	 */
3449bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3450bb451fdfSGreg Thelen 	BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3451bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3452bb451fdfSGreg Thelen 
3453bb451fdfSGreg Thelen 	/*
345450694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
345550694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
345650694c28SMel Gorman 	 * point.
34575515061dSMel Gorman 	 */
3458f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
34595515061dSMel Gorman 		return 1;
34605515061dSMel Gorman 
34611732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
34623481c37fSYafang Shao 	trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
346333906bc5SMel Gorman 
34643115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
346533906bc5SMel Gorman 
346633906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
34671732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
346833906bc5SMel Gorman 
346933906bc5SMel Gorman 	return nr_reclaimed;
347066e1707bSBalbir Singh }
347166e1707bSBalbir Singh 
3472c255a458SAndrew Morton #ifdef CONFIG_MEMCG
347366e1707bSBalbir Singh 
3474d2e5fb92SMichal Hocko /* Only used by soft limit reclaim. Do not reuse for anything else. */
3475a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
34764e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
3477ef8f2327SMel Gorman 						pg_data_t *pgdat,
34780ae5e89cSYing Han 						unsigned long *nr_scanned)
34794e416953SBalbir Singh {
3480afaf07a6SJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
34814e416953SBalbir Singh 	struct scan_control sc = {
3482b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3483ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
34844e416953SBalbir Singh 		.may_writepage = !laptop_mode,
34854e416953SBalbir Singh 		.may_unmap = 1,
3486b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
34874e416953SBalbir Singh 		.may_swap = !noswap,
34884e416953SBalbir Singh 	};
34890ae5e89cSYing Han 
3490d2e5fb92SMichal Hocko 	WARN_ON_ONCE(!current->reclaim_state);
3491d2e5fb92SMichal Hocko 
34924e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
34934e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3494bdce6d9eSKOSAKI Motohiro 
34959e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
34963481c37fSYafang Shao 						      sc.gfp_mask);
3497bdce6d9eSKOSAKI Motohiro 
34984e416953SBalbir Singh 	/*
34994e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
35004e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3501a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
35024e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
35034e416953SBalbir Singh 	 * the priority and make it zero.
35044e416953SBalbir Singh 	 */
3505afaf07a6SJohannes Weiner 	shrink_lruvec(lruvec, &sc);
3506bdce6d9eSKOSAKI Motohiro 
3507bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3508bdce6d9eSKOSAKI Motohiro 
35090ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
35100308f7cfSYafang Shao 
35114e416953SBalbir Singh 	return sc.nr_reclaimed;
35124e416953SBalbir Singh }
35134e416953SBalbir Singh 
351472835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3515b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
35168c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3517b70a2a21SJohannes Weiner 					   bool may_swap)
351866e1707bSBalbir Singh {
3519bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3520499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
352166e1707bSBalbir Singh 	struct scan_control sc = {
3522b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
35237dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3524ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3525b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3526ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3527ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
352866e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3529a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3530b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3531a09ed5e0SYing Han 	};
3532fa40d1eeSShakeel Butt 	/*
3533fa40d1eeSShakeel Butt 	 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
3534fa40d1eeSShakeel Butt 	 * equal pressure on all the nodes. This is based on the assumption that
3535fa40d1eeSShakeel Butt 	 * the reclaim does not bail out early.
3536fa40d1eeSShakeel Butt 	 */
3537fa40d1eeSShakeel Butt 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
353866e1707bSBalbir Singh 
35391732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
35403481c37fSYafang Shao 	trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
3541499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3542eb414681SJohannes Weiner 
35433115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3544eb414681SJohannes Weiner 
3545499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3546bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
35471732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3548bdce6d9eSKOSAKI Motohiro 
3549bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
355066e1707bSBalbir Singh }
355166e1707bSBalbir Singh #endif
355266e1707bSBalbir Singh 
35531d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3554ef8f2327SMel Gorman 				struct scan_control *sc)
3555f16015fbSJohannes Weiner {
3556b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3557b91ac374SJohannes Weiner 	struct lruvec *lruvec;
3558b95a2f2dSJohannes Weiner 
3559b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3560b95a2f2dSJohannes Weiner 		return;
3561b95a2f2dSJohannes Weiner 
3562b91ac374SJohannes Weiner 	lruvec = mem_cgroup_lruvec(NULL, pgdat);
3563b91ac374SJohannes Weiner 	if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
3564b91ac374SJohannes Weiner 		return;
3565b91ac374SJohannes Weiner 
3566b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3567b95a2f2dSJohannes Weiner 	do {
3568b91ac374SJohannes Weiner 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
35691a93be0eSKonstantin Khlebnikov 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
35709e3b2f8cSKonstantin Khlebnikov 				   sc, LRU_ACTIVE_ANON);
3571b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3572b95a2f2dSJohannes Weiner 	} while (memcg);
3573f16015fbSJohannes Weiner }
3574f16015fbSJohannes Weiner 
357597a225e6SJoonsoo Kim static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
35761c30844dSMel Gorman {
35771c30844dSMel Gorman 	int i;
35781c30844dSMel Gorman 	struct zone *zone;
35791c30844dSMel Gorman 
35801c30844dSMel Gorman 	/*
35811c30844dSMel Gorman 	 * Check for watermark boosts top-down as the higher zones
35821c30844dSMel Gorman 	 * are more likely to be boosted. Both watermarks and boosts
35831eba09c1SRandy Dunlap 	 * should not be checked at the same time as reclaim would
35841c30844dSMel Gorman 	 * start prematurely when there is no boosting and a lower
35851c30844dSMel Gorman 	 * zone is balanced.
35861c30844dSMel Gorman 	 */
358797a225e6SJoonsoo Kim 	for (i = highest_zoneidx; i >= 0; i--) {
35881c30844dSMel Gorman 		zone = pgdat->node_zones + i;
35891c30844dSMel Gorman 		if (!managed_zone(zone))
35901c30844dSMel Gorman 			continue;
35911c30844dSMel Gorman 
35921c30844dSMel Gorman 		if (zone->watermark_boost)
35931c30844dSMel Gorman 			return true;
35941c30844dSMel Gorman 	}
35951c30844dSMel Gorman 
35961c30844dSMel Gorman 	return false;
35971c30844dSMel Gorman }
35981c30844dSMel Gorman 
3599e716f2ebSMel Gorman /*
3600e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
360197a225e6SJoonsoo Kim  * and highest_zoneidx
3602e716f2ebSMel Gorman  */
360397a225e6SJoonsoo Kim static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
360460cefed4SJohannes Weiner {
3605e716f2ebSMel Gorman 	int i;
3606e716f2ebSMel Gorman 	unsigned long mark = -1;
3607e716f2ebSMel Gorman 	struct zone *zone;
360860cefed4SJohannes Weiner 
36091c30844dSMel Gorman 	/*
36101c30844dSMel Gorman 	 * Check watermarks bottom-up as lower zones are more likely to
36111c30844dSMel Gorman 	 * meet watermarks.
36121c30844dSMel Gorman 	 */
361397a225e6SJoonsoo Kim 	for (i = 0; i <= highest_zoneidx; i++) {
3614e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
36156256c6b4SMel Gorman 
3616e716f2ebSMel Gorman 		if (!managed_zone(zone))
3617e716f2ebSMel Gorman 			continue;
3618e716f2ebSMel Gorman 
3619e716f2ebSMel Gorman 		mark = high_wmark_pages(zone);
362097a225e6SJoonsoo Kim 		if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
36216256c6b4SMel Gorman 			return true;
362260cefed4SJohannes Weiner 	}
362360cefed4SJohannes Weiner 
3624e716f2ebSMel Gorman 	/*
362597a225e6SJoonsoo Kim 	 * If a node has no populated zone within highest_zoneidx, it does not
3626e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3627e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3628e716f2ebSMel Gorman 	 */
3629e716f2ebSMel Gorman 	if (mark == -1)
3630e716f2ebSMel Gorman 		return true;
3631e716f2ebSMel Gorman 
3632e716f2ebSMel Gorman 	return false;
3633e716f2ebSMel Gorman }
3634e716f2ebSMel Gorman 
3635631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
3636631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
3637631b6e08SMel Gorman {
36381b05117dSJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
36391b05117dSJohannes Weiner 
36401b05117dSJohannes Weiner 	clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3641631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
3642631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3643631b6e08SMel Gorman }
3644631b6e08SMel Gorman 
36451741c877SMel Gorman /*
36465515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
36475515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
36485515061dSMel Gorman  *
36495515061dSMel Gorman  * Returns true if kswapd is ready to sleep
36505515061dSMel Gorman  */
365197a225e6SJoonsoo Kim static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
365297a225e6SJoonsoo Kim 				int highest_zoneidx)
3653f50de2d3SMel Gorman {
36545515061dSMel Gorman 	/*
36559e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3656c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
36579e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
36589e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
36599e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
36609e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
36619e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
36629e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
36639e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
36649e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
36659e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
36665515061dSMel Gorman 	 */
36679e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
36689e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3669f50de2d3SMel Gorman 
3670c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3671c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3672c73322d0SJohannes Weiner 		return true;
3673c73322d0SJohannes Weiner 
367497a225e6SJoonsoo Kim 	if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
3675631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
3676333b0a45SShantanu Goel 		return true;
36771d82de61SMel Gorman 	}
36781d82de61SMel Gorman 
3679333b0a45SShantanu Goel 	return false;
3680f50de2d3SMel Gorman }
3681f50de2d3SMel Gorman 
36821da177e4SLinus Torvalds /*
36831d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
36841d82de61SMel Gorman  * zone that is currently unbalanced.
3685b8e83b94SMel Gorman  *
3686b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3687283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3688283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
368975485363SMel Gorman  */
36901d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3691accf6242SVlastimil Babka 			       struct scan_control *sc)
369275485363SMel Gorman {
36931d82de61SMel Gorman 	struct zone *zone;
36941d82de61SMel Gorman 	int z;
369575485363SMel Gorman 
36961d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
36971d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3698970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
36991d82de61SMel Gorman 		zone = pgdat->node_zones + z;
37006aa303deSMel Gorman 		if (!managed_zone(zone))
37011d82de61SMel Gorman 			continue;
37027c954f6dSMel Gorman 
37031d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
37047c954f6dSMel Gorman 	}
37057c954f6dSMel Gorman 
37061d82de61SMel Gorman 	/*
37071d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
37081d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
37091d82de61SMel Gorman 	 */
3710970a39a3SMel Gorman 	shrink_node(pgdat, sc);
37111d82de61SMel Gorman 
37121d82de61SMel Gorman 	/*
37131d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
37141d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
37151d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
37161d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
37171d82de61SMel Gorman 	 * can direct reclaim/compact.
37181d82de61SMel Gorman 	 */
37199861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
37201d82de61SMel Gorman 		sc->order = 0;
37211d82de61SMel Gorman 
3722b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
372375485363SMel Gorman }
372475485363SMel Gorman 
372575485363SMel Gorman /*
37261d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
37271d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
37281d82de61SMel Gorman  * balanced.
37291da177e4SLinus Torvalds  *
37301d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
37311da177e4SLinus Torvalds  *
37321da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
373341858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
37348bb4e7a2SWei Yang  * found to have free_pages <= high_wmark_pages(zone), any page in that zone
37351d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
37361d82de61SMel Gorman  * balanced.
37371da177e4SLinus Torvalds  */
373897a225e6SJoonsoo Kim static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
37391da177e4SLinus Torvalds {
37401da177e4SLinus Torvalds 	int i;
37410608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
37420608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3743eb414681SJohannes Weiner 	unsigned long pflags;
37441c30844dSMel Gorman 	unsigned long nr_boost_reclaim;
37451c30844dSMel Gorman 	unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
37461c30844dSMel Gorman 	bool boosted;
37471d82de61SMel Gorman 	struct zone *zone;
3748179e9639SAndrew Morton 	struct scan_control sc = {
3749179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3750ee814fe2SJohannes Weiner 		.order = order,
3751a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3752179e9639SAndrew Morton 	};
375393781325SOmar Sandoval 
37541732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
3755eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
375693781325SOmar Sandoval 	__fs_reclaim_acquire();
375793781325SOmar Sandoval 
3758f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
37591da177e4SLinus Torvalds 
37601c30844dSMel Gorman 	/*
37611c30844dSMel Gorman 	 * Account for the reclaim boost. Note that the zone boost is left in
37621c30844dSMel Gorman 	 * place so that parallel allocations that are near the watermark will
37631c30844dSMel Gorman 	 * stall or direct reclaim until kswapd is finished.
37641c30844dSMel Gorman 	 */
37651c30844dSMel Gorman 	nr_boost_reclaim = 0;
376697a225e6SJoonsoo Kim 	for (i = 0; i <= highest_zoneidx; i++) {
37671c30844dSMel Gorman 		zone = pgdat->node_zones + i;
37681c30844dSMel Gorman 		if (!managed_zone(zone))
37691c30844dSMel Gorman 			continue;
37701c30844dSMel Gorman 
37711c30844dSMel Gorman 		nr_boost_reclaim += zone->watermark_boost;
37721c30844dSMel Gorman 		zone_boosts[i] = zone->watermark_boost;
37731c30844dSMel Gorman 	}
37741c30844dSMel Gorman 	boosted = nr_boost_reclaim;
37751c30844dSMel Gorman 
37761c30844dSMel Gorman restart:
37771c30844dSMel Gorman 	sc.priority = DEF_PRIORITY;
37789e3b2f8cSKonstantin Khlebnikov 	do {
3779c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
3780b8e83b94SMel Gorman 		bool raise_priority = true;
37811c30844dSMel Gorman 		bool balanced;
378293781325SOmar Sandoval 		bool ret;
3783b8e83b94SMel Gorman 
378497a225e6SJoonsoo Kim 		sc.reclaim_idx = highest_zoneidx;
37851da177e4SLinus Torvalds 
378686c79f6bSMel Gorman 		/*
378784c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
378884c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
378984c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
379084c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
379184c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
379284c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
379384c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
379484c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
379586c79f6bSMel Gorman 		 */
379686c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
379786c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
379886c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
37996aa303deSMel Gorman 				if (!managed_zone(zone))
380086c79f6bSMel Gorman 					continue;
380186c79f6bSMel Gorman 
3802970a39a3SMel Gorman 				sc.reclaim_idx = i;
380386c79f6bSMel Gorman 				break;
380486c79f6bSMel Gorman 			}
380586c79f6bSMel Gorman 		}
380686c79f6bSMel Gorman 
380786c79f6bSMel Gorman 		/*
38081c30844dSMel Gorman 		 * If the pgdat is imbalanced then ignore boosting and preserve
38091c30844dSMel Gorman 		 * the watermarks for a later time and restart. Note that the
38101c30844dSMel Gorman 		 * zone watermarks will be still reset at the end of balancing
38111c30844dSMel Gorman 		 * on the grounds that the normal reclaim should be enough to
38121c30844dSMel Gorman 		 * re-evaluate if boosting is required when kswapd next wakes.
381386c79f6bSMel Gorman 		 */
381497a225e6SJoonsoo Kim 		balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
38151c30844dSMel Gorman 		if (!balanced && nr_boost_reclaim) {
38161c30844dSMel Gorman 			nr_boost_reclaim = 0;
38171c30844dSMel Gorman 			goto restart;
38181c30844dSMel Gorman 		}
38191c30844dSMel Gorman 
38201c30844dSMel Gorman 		/*
38211c30844dSMel Gorman 		 * If boosting is not active then only reclaim if there are no
38221c30844dSMel Gorman 		 * eligible zones. Note that sc.reclaim_idx is not used as
38231c30844dSMel Gorman 		 * buffer_heads_over_limit may have adjusted it.
38241c30844dSMel Gorman 		 */
38251c30844dSMel Gorman 		if (!nr_boost_reclaim && balanced)
38261da177e4SLinus Torvalds 			goto out;
3827e1dbeda6SAndrew Morton 
38281c30844dSMel Gorman 		/* Limit the priority of boosting to avoid reclaim writeback */
38291c30844dSMel Gorman 		if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
38301c30844dSMel Gorman 			raise_priority = false;
38311c30844dSMel Gorman 
38321c30844dSMel Gorman 		/*
38331c30844dSMel Gorman 		 * Do not writeback or swap pages for boosted reclaim. The
38341c30844dSMel Gorman 		 * intent is to relieve pressure not issue sub-optimal IO
38351c30844dSMel Gorman 		 * from reclaim context. If no pages are reclaimed, the
38361c30844dSMel Gorman 		 * reclaim will be aborted.
38371c30844dSMel Gorman 		 */
38381c30844dSMel Gorman 		sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
38391c30844dSMel Gorman 		sc.may_swap = !nr_boost_reclaim;
38401c30844dSMel Gorman 
38411da177e4SLinus Torvalds 		/*
38421d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
38431d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
38441d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
38451d82de61SMel Gorman 		 * about consistent aging.
38461d82de61SMel Gorman 		 */
3847ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
38481d82de61SMel Gorman 
38491d82de61SMel Gorman 		/*
3850b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3851b7ea3c41SMel Gorman 		 * even in laptop mode.
3852b7ea3c41SMel Gorman 		 */
3853047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
3854b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3855b7ea3c41SMel Gorman 
38561d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
38571da177e4SLinus Torvalds 		sc.nr_scanned = 0;
38580608f43dSAndrew Morton 		nr_soft_scanned = 0;
3859ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
38601d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
38610608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
38620608f43dSAndrew Morton 
386332a4330dSRik van Riel 		/*
38641d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
38651d82de61SMel Gorman 		 * enough pages are already being scanned that that high
38661d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
386732a4330dSRik van Riel 		 */
3868970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3869b8e83b94SMel Gorman 			raise_priority = false;
3870d7868daeSMel Gorman 
38715515061dSMel Gorman 		/*
38725515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
38735515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
38745515061dSMel Gorman 		 * able to safely make forward progress. Wake them
38755515061dSMel Gorman 		 */
38765515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3877c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
3878cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
38795515061dSMel Gorman 
3880b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
388193781325SOmar Sandoval 		__fs_reclaim_release();
388293781325SOmar Sandoval 		ret = try_to_freeze();
388393781325SOmar Sandoval 		__fs_reclaim_acquire();
388493781325SOmar Sandoval 		if (ret || kthread_should_stop())
3885b8e83b94SMel Gorman 			break;
3886b8e83b94SMel Gorman 
3887b8e83b94SMel Gorman 		/*
3888b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3889b8e83b94SMel Gorman 		 * progress in reclaiming pages
3890b8e83b94SMel Gorman 		 */
3891c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
38921c30844dSMel Gorman 		nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
38931c30844dSMel Gorman 
38941c30844dSMel Gorman 		/*
38951c30844dSMel Gorman 		 * If reclaim made no progress for a boost, stop reclaim as
38961c30844dSMel Gorman 		 * IO cannot be queued and it could be an infinite loop in
38971c30844dSMel Gorman 		 * extreme circumstances.
38981c30844dSMel Gorman 		 */
38991c30844dSMel Gorman 		if (nr_boost_reclaim && !nr_reclaimed)
39001c30844dSMel Gorman 			break;
39011c30844dSMel Gorman 
3902c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
3903b8e83b94SMel Gorman 			sc.priority--;
39041d82de61SMel Gorman 	} while (sc.priority >= 1);
39051da177e4SLinus Torvalds 
3906c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
3907c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
3908c73322d0SJohannes Weiner 
3909b8e83b94SMel Gorman out:
39101c30844dSMel Gorman 	/* If reclaim was boosted, account for the reclaim done in this pass */
39111c30844dSMel Gorman 	if (boosted) {
39121c30844dSMel Gorman 		unsigned long flags;
39131c30844dSMel Gorman 
391497a225e6SJoonsoo Kim 		for (i = 0; i <= highest_zoneidx; i++) {
39151c30844dSMel Gorman 			if (!zone_boosts[i])
39161c30844dSMel Gorman 				continue;
39171c30844dSMel Gorman 
39181c30844dSMel Gorman 			/* Increments are under the zone lock */
39191c30844dSMel Gorman 			zone = pgdat->node_zones + i;
39201c30844dSMel Gorman 			spin_lock_irqsave(&zone->lock, flags);
39211c30844dSMel Gorman 			zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
39221c30844dSMel Gorman 			spin_unlock_irqrestore(&zone->lock, flags);
39231c30844dSMel Gorman 		}
39241c30844dSMel Gorman 
39251c30844dSMel Gorman 		/*
39261c30844dSMel Gorman 		 * As there is now likely space, wakeup kcompact to defragment
39271c30844dSMel Gorman 		 * pageblocks.
39281c30844dSMel Gorman 		 */
392997a225e6SJoonsoo Kim 		wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
39301c30844dSMel Gorman 	}
39311c30844dSMel Gorman 
39322a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
393393781325SOmar Sandoval 	__fs_reclaim_release();
3934eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
39351732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3936e5ca8071SYafang Shao 
39370abdee2bSMel Gorman 	/*
39381d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
39391d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
39401d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
39411d82de61SMel Gorman 	 * remain at the higher level.
39420abdee2bSMel Gorman 	 */
39431d82de61SMel Gorman 	return sc.order;
39441da177e4SLinus Torvalds }
39451da177e4SLinus Torvalds 
3946e716f2ebSMel Gorman /*
394797a225e6SJoonsoo Kim  * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
394897a225e6SJoonsoo Kim  * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
394997a225e6SJoonsoo Kim  * not a valid index then either kswapd runs for first time or kswapd couldn't
395097a225e6SJoonsoo Kim  * sleep after previous reclaim attempt (node is still unbalanced). In that
395197a225e6SJoonsoo Kim  * case return the zone index of the previous kswapd reclaim cycle.
3952e716f2ebSMel Gorman  */
395397a225e6SJoonsoo Kim static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
395497a225e6SJoonsoo Kim 					   enum zone_type prev_highest_zoneidx)
3955e716f2ebSMel Gorman {
395697a225e6SJoonsoo Kim 	enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
39575644e1fbSQian Cai 
395897a225e6SJoonsoo Kim 	return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
3959e716f2ebSMel Gorman }
3960e716f2ebSMel Gorman 
396138087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
396297a225e6SJoonsoo Kim 				unsigned int highest_zoneidx)
3963f0bc0a60SKOSAKI Motohiro {
3964f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3965f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3966f0bc0a60SKOSAKI Motohiro 
3967f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3968f0bc0a60SKOSAKI Motohiro 		return;
3969f0bc0a60SKOSAKI Motohiro 
3970f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3971f0bc0a60SKOSAKI Motohiro 
3972333b0a45SShantanu Goel 	/*
3973333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
3974333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
3975333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
3976333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
3977333b0a45SShantanu Goel 	 * succeed.
3978333b0a45SShantanu Goel 	 */
397997a225e6SJoonsoo Kim 	if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
3980fd901c95SVlastimil Babka 		/*
3981fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3982fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3983fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3984fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3985fd901c95SVlastimil Babka 		 */
3986fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3987fd901c95SVlastimil Babka 
3988fd901c95SVlastimil Babka 		/*
3989fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3990fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3991fd901c95SVlastimil Babka 		 */
399297a225e6SJoonsoo Kim 		wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
3993fd901c95SVlastimil Babka 
3994f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
399538087d9bSMel Gorman 
399638087d9bSMel Gorman 		/*
399797a225e6SJoonsoo Kim 		 * If woken prematurely then reset kswapd_highest_zoneidx and
399838087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
399938087d9bSMel Gorman 		 * the previous request that slept prematurely.
400038087d9bSMel Gorman 		 */
400138087d9bSMel Gorman 		if (remaining) {
400297a225e6SJoonsoo Kim 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
400397a225e6SJoonsoo Kim 					kswapd_highest_zoneidx(pgdat,
400497a225e6SJoonsoo Kim 							highest_zoneidx));
40055644e1fbSQian Cai 
40065644e1fbSQian Cai 			if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
40075644e1fbSQian Cai 				WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
400838087d9bSMel Gorman 		}
400938087d9bSMel Gorman 
4010f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
4011f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
4012f0bc0a60SKOSAKI Motohiro 	}
4013f0bc0a60SKOSAKI Motohiro 
4014f0bc0a60SKOSAKI Motohiro 	/*
4015f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
4016f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
4017f0bc0a60SKOSAKI Motohiro 	 */
4018d9f21d42SMel Gorman 	if (!remaining &&
401997a225e6SJoonsoo Kim 	    prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
4020f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
4021f0bc0a60SKOSAKI Motohiro 
4022f0bc0a60SKOSAKI Motohiro 		/*
4023f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
4024f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
4025f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
4026f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
4027f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
4028f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
4029f0bc0a60SKOSAKI Motohiro 		 */
4030f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
40311c7e7f6cSAaditya Kumar 
40321c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
4033f0bc0a60SKOSAKI Motohiro 			schedule();
40341c7e7f6cSAaditya Kumar 
4035f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
4036f0bc0a60SKOSAKI Motohiro 	} else {
4037f0bc0a60SKOSAKI Motohiro 		if (remaining)
4038f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
4039f0bc0a60SKOSAKI Motohiro 		else
4040f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
4041f0bc0a60SKOSAKI Motohiro 	}
4042f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
4043f0bc0a60SKOSAKI Motohiro }
4044f0bc0a60SKOSAKI Motohiro 
40451da177e4SLinus Torvalds /*
40461da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
40471da177e4SLinus Torvalds  * from the init process.
40481da177e4SLinus Torvalds  *
40491da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
40501da177e4SLinus Torvalds  * free memory available even if there is no other activity
40511da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
40521da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
40531da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
40541da177e4SLinus Torvalds  *
40551da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
40561da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
40571da177e4SLinus Torvalds  */
40581da177e4SLinus Torvalds static int kswapd(void *p)
40591da177e4SLinus Torvalds {
4060e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
406197a225e6SJoonsoo Kim 	unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
40621da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
40631da177e4SLinus Torvalds 	struct task_struct *tsk = current;
4064a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
40651da177e4SLinus Torvalds 
4066174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
4067c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
40681da177e4SLinus Torvalds 
40691da177e4SLinus Torvalds 	/*
40701da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
40711da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
40721da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
40731da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
40741da177e4SLinus Torvalds 	 *
40751da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
40761da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
40771da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
40781da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
40791da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
40801da177e4SLinus Torvalds 	 */
4081930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
408283144186SRafael J. Wysocki 	set_freezable();
40831da177e4SLinus Torvalds 
40845644e1fbSQian Cai 	WRITE_ONCE(pgdat->kswapd_order, 0);
408597a225e6SJoonsoo Kim 	WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
40861da177e4SLinus Torvalds 	for ( ; ; ) {
40876f6313d4SJeff Liu 		bool ret;
40883e1d1d28SChristoph Lameter 
40895644e1fbSQian Cai 		alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
409097a225e6SJoonsoo Kim 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
409197a225e6SJoonsoo Kim 							highest_zoneidx);
4092e716f2ebSMel Gorman 
409338087d9bSMel Gorman kswapd_try_sleep:
409438087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
409597a225e6SJoonsoo Kim 					highest_zoneidx);
4096215ddd66SMel Gorman 
409797a225e6SJoonsoo Kim 		/* Read the new order and highest_zoneidx */
40982b47a24cSLukas Bulwahn 		alloc_order = READ_ONCE(pgdat->kswapd_order);
409997a225e6SJoonsoo Kim 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
410097a225e6SJoonsoo Kim 							highest_zoneidx);
41015644e1fbSQian Cai 		WRITE_ONCE(pgdat->kswapd_order, 0);
410297a225e6SJoonsoo Kim 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
41031da177e4SLinus Torvalds 
41048fe23e05SDavid Rientjes 		ret = try_to_freeze();
41058fe23e05SDavid Rientjes 		if (kthread_should_stop())
41068fe23e05SDavid Rientjes 			break;
41078fe23e05SDavid Rientjes 
41088fe23e05SDavid Rientjes 		/*
41098fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
41108fe23e05SDavid Rientjes 		 * after returning from the refrigerator
4111b1296cc4SRafael J. Wysocki 		 */
411238087d9bSMel Gorman 		if (ret)
411338087d9bSMel Gorman 			continue;
41141d82de61SMel Gorman 
411538087d9bSMel Gorman 		/*
411638087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
411738087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
411838087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
411938087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
412038087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
412138087d9bSMel Gorman 		 * request (alloc_order).
412238087d9bSMel Gorman 		 */
412397a225e6SJoonsoo Kim 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
4124e5146b12SMel Gorman 						alloc_order);
412597a225e6SJoonsoo Kim 		reclaim_order = balance_pgdat(pgdat, alloc_order,
412697a225e6SJoonsoo Kim 						highest_zoneidx);
412738087d9bSMel Gorman 		if (reclaim_order < alloc_order)
412838087d9bSMel Gorman 			goto kswapd_try_sleep;
412933906bc5SMel Gorman 	}
4130b0a8cc58STakamori Yamaguchi 
413171abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
413271abdc15SJohannes Weiner 
41331da177e4SLinus Torvalds 	return 0;
41341da177e4SLinus Torvalds }
41351da177e4SLinus Torvalds 
41361da177e4SLinus Torvalds /*
41375ecd9d40SDavid Rientjes  * A zone is low on free memory or too fragmented for high-order memory.  If
41385ecd9d40SDavid Rientjes  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
41395ecd9d40SDavid Rientjes  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
41405ecd9d40SDavid Rientjes  * has failed or is not needed, still wake up kcompactd if only compaction is
41415ecd9d40SDavid Rientjes  * needed.
41421da177e4SLinus Torvalds  */
41435ecd9d40SDavid Rientjes void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
414497a225e6SJoonsoo Kim 		   enum zone_type highest_zoneidx)
41451da177e4SLinus Torvalds {
41461da177e4SLinus Torvalds 	pg_data_t *pgdat;
41475644e1fbSQian Cai 	enum zone_type curr_idx;
41481da177e4SLinus Torvalds 
41496aa303deSMel Gorman 	if (!managed_zone(zone))
41501da177e4SLinus Torvalds 		return;
41511da177e4SLinus Torvalds 
41525ecd9d40SDavid Rientjes 	if (!cpuset_zone_allowed(zone, gfp_flags))
41531da177e4SLinus Torvalds 		return;
4154dffcac2cSShakeel Butt 
41555644e1fbSQian Cai 	pgdat = zone->zone_pgdat;
415697a225e6SJoonsoo Kim 	curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
41575644e1fbSQian Cai 
415897a225e6SJoonsoo Kim 	if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
415997a225e6SJoonsoo Kim 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
41605644e1fbSQian Cai 
41615644e1fbSQian Cai 	if (READ_ONCE(pgdat->kswapd_order) < order)
41625644e1fbSQian Cai 		WRITE_ONCE(pgdat->kswapd_order, order);
41635644e1fbSQian Cai 
41648d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
41651da177e4SLinus Torvalds 		return;
4166e1a55637SMel Gorman 
41675ecd9d40SDavid Rientjes 	/* Hopeless node, leave it to direct reclaim if possible */
41685ecd9d40SDavid Rientjes 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
416997a225e6SJoonsoo Kim 	    (pgdat_balanced(pgdat, order, highest_zoneidx) &&
417097a225e6SJoonsoo Kim 	     !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
41715ecd9d40SDavid Rientjes 		/*
41725ecd9d40SDavid Rientjes 		 * There may be plenty of free memory available, but it's too
41735ecd9d40SDavid Rientjes 		 * fragmented for high-order allocations.  Wake up kcompactd
41745ecd9d40SDavid Rientjes 		 * and rely on compaction_suitable() to determine if it's
41755ecd9d40SDavid Rientjes 		 * needed.  If it fails, it will defer subsequent attempts to
41765ecd9d40SDavid Rientjes 		 * ratelimit its work.
41775ecd9d40SDavid Rientjes 		 */
41785ecd9d40SDavid Rientjes 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
417997a225e6SJoonsoo Kim 			wakeup_kcompactd(pgdat, order, highest_zoneidx);
4180c73322d0SJohannes Weiner 		return;
41815ecd9d40SDavid Rientjes 	}
4182c73322d0SJohannes Weiner 
418397a225e6SJoonsoo Kim 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
41845ecd9d40SDavid Rientjes 				      gfp_flags);
41858d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
41861da177e4SLinus Torvalds }
41871da177e4SLinus Torvalds 
4188c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
41891da177e4SLinus Torvalds /*
41907b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
4191d6277db4SRafael J. Wysocki  * freed pages.
4192d6277db4SRafael J. Wysocki  *
4193d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
4194d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
4195d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
41961da177e4SLinus Torvalds  */
41977b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
41981da177e4SLinus Torvalds {
4199d6277db4SRafael J. Wysocki 	struct scan_control sc = {
42007b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
4201ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
4202b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
42039e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
4204ee814fe2SJohannes Weiner 		.may_writepage = 1,
4205ee814fe2SJohannes Weiner 		.may_unmap = 1,
4206ee814fe2SJohannes Weiner 		.may_swap = 1,
4207ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
42081da177e4SLinus Torvalds 	};
42097b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
42107b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
4211499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
42121da177e4SLinus Torvalds 
4213d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
421493781325SOmar Sandoval 	noreclaim_flag = memalloc_noreclaim_save();
42151732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
4216d6277db4SRafael J. Wysocki 
42173115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4218d6277db4SRafael J. Wysocki 
42191732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
4220499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
422193781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4222d6277db4SRafael J. Wysocki 
42237b51755cSKOSAKI Motohiro 	return nr_reclaimed;
42241da177e4SLinus Torvalds }
4225c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
42261da177e4SLinus Torvalds 
42273218ae14SYasunori Goto /*
42283218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
42293218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
42303218ae14SYasunori Goto  */
42313218ae14SYasunori Goto int kswapd_run(int nid)
42323218ae14SYasunori Goto {
42333218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
42343218ae14SYasunori Goto 	int ret = 0;
42353218ae14SYasunori Goto 
42363218ae14SYasunori Goto 	if (pgdat->kswapd)
42373218ae14SYasunori Goto 		return 0;
42383218ae14SYasunori Goto 
42393218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
42403218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
42413218ae14SYasunori Goto 		/* failure at boot is fatal */
4242c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
4243d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
4244d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
4245d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
42463218ae14SYasunori Goto 	}
42473218ae14SYasunori Goto 	return ret;
42483218ae14SYasunori Goto }
42493218ae14SYasunori Goto 
42508fe23e05SDavid Rientjes /*
4251d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
4252bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
42538fe23e05SDavid Rientjes  */
42548fe23e05SDavid Rientjes void kswapd_stop(int nid)
42558fe23e05SDavid Rientjes {
42568fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
42578fe23e05SDavid Rientjes 
4258d8adde17SJiang Liu 	if (kswapd) {
42598fe23e05SDavid Rientjes 		kthread_stop(kswapd);
4260d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
4261d8adde17SJiang Liu 	}
42628fe23e05SDavid Rientjes }
42638fe23e05SDavid Rientjes 
42641da177e4SLinus Torvalds static int __init kswapd_init(void)
42651da177e4SLinus Torvalds {
42666b700b5bSWei Yang 	int nid;
426769e05944SAndrew Morton 
42681da177e4SLinus Torvalds 	swap_setup();
426948fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
42703218ae14SYasunori Goto  		kswapd_run(nid);
42711da177e4SLinus Torvalds 	return 0;
42721da177e4SLinus Torvalds }
42731da177e4SLinus Torvalds 
42741da177e4SLinus Torvalds module_init(kswapd_init)
42759eeff239SChristoph Lameter 
42769eeff239SChristoph Lameter #ifdef CONFIG_NUMA
42779eeff239SChristoph Lameter /*
4278a5f5f91dSMel Gorman  * Node reclaim mode
42799eeff239SChristoph Lameter  *
4280a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
42819eeff239SChristoph Lameter  * the watermarks.
42829eeff239SChristoph Lameter  */
4283a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
42849eeff239SChristoph Lameter 
428551998364SDave Hansen /*
4286a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
4287a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
4288a92f7126SChristoph Lameter  * a zone.
4289a92f7126SChristoph Lameter  */
4290a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
4291a92f7126SChristoph Lameter 
42929eeff239SChristoph Lameter /*
4293a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
42949614634fSChristoph Lameter  * occur.
42959614634fSChristoph Lameter  */
42969614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
42979614634fSChristoph Lameter 
42989614634fSChristoph Lameter /*
42990ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
43000ff38490SChristoph Lameter  * slab reclaim needs to occur.
43010ff38490SChristoph Lameter  */
43020ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
43030ff38490SChristoph Lameter 
430411fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
430590afa5deSMel Gorman {
430611fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
430711fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
430811fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
430990afa5deSMel Gorman 
431090afa5deSMel Gorman 	/*
431190afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
431290afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
431390afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
431490afa5deSMel Gorman 	 */
431590afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
431690afa5deSMel Gorman }
431790afa5deSMel Gorman 
431890afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4319a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
432090afa5deSMel Gorman {
4321d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
4322d031a157SAlexandru Moise 	unsigned long delta = 0;
432390afa5deSMel Gorman 
432490afa5deSMel Gorman 	/*
432595bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
432690afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
432711fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
432890afa5deSMel Gorman 	 * a better estimate
432990afa5deSMel Gorman 	 */
4330a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
4331a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
433290afa5deSMel Gorman 	else
4333a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
433490afa5deSMel Gorman 
433590afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
4336a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
4337a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
433890afa5deSMel Gorman 
433990afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
434090afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
434190afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
434290afa5deSMel Gorman 
434390afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
434490afa5deSMel Gorman }
434590afa5deSMel Gorman 
43460ff38490SChristoph Lameter /*
4347a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
43489eeff239SChristoph Lameter  */
4349a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
43509eeff239SChristoph Lameter {
43517fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
435269e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
43539eeff239SChristoph Lameter 	struct task_struct *p = current;
4354499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
4355179e9639SAndrew Morton 	struct scan_control sc = {
435662b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4357f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
4358bd2f6199SJohannes Weiner 		.order = order,
4359a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
4360a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4361a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4362ee814fe2SJohannes Weiner 		.may_swap = 1,
4363f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
4364179e9639SAndrew Morton 	};
43659eeff239SChristoph Lameter 
4366132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4367132bb8cfSYafang Shao 					   sc.gfp_mask);
4368132bb8cfSYafang Shao 
43699eeff239SChristoph Lameter 	cond_resched();
437093781325SOmar Sandoval 	fs_reclaim_acquire(sc.gfp_mask);
4371d4f7796eSChristoph Lameter 	/*
437295bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4373d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
437495bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
4375d4f7796eSChristoph Lameter 	 */
4376499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
4377499118e9SVlastimil Babka 	p->flags |= PF_SWAPWRITE;
43781732d2b0SAndrew Morton 	set_task_reclaim_state(p, &sc.reclaim_state);
4379c84db23cSChristoph Lameter 
4380a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
4381a92f7126SChristoph Lameter 		/*
4382894befecSAndrey Ryabinin 		 * Free memory by calling shrink node with increasing
43830ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
4384a92f7126SChristoph Lameter 		 */
4385a92f7126SChristoph Lameter 		do {
4386970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
43879e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
43880ff38490SChristoph Lameter 	}
4389a92f7126SChristoph Lameter 
43901732d2b0SAndrew Morton 	set_task_reclaim_state(p, NULL);
4391499118e9SVlastimil Babka 	current->flags &= ~PF_SWAPWRITE;
4392499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
439393781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4394132bb8cfSYafang Shao 
4395132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4396132bb8cfSYafang Shao 
4397a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
43989eeff239SChristoph Lameter }
4399179e9639SAndrew Morton 
4400a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4401179e9639SAndrew Morton {
4402d773ed6bSDavid Rientjes 	int ret;
4403179e9639SAndrew Morton 
4404179e9639SAndrew Morton 	/*
4405a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
44060ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
440734aa1330SChristoph Lameter 	 *
44089614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
44099614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
4410a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
4411a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
44129614634fSChristoph Lameter 	 * unmapped file backed pages.
4413179e9639SAndrew Morton 	 */
4414a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4415d42f3245SRoman Gushchin 	    node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
4416d42f3245SRoman Gushchin 	    pgdat->min_slab_pages)
4417a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
4418179e9639SAndrew Morton 
4419179e9639SAndrew Morton 	/*
4420d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
4421179e9639SAndrew Morton 	 */
4422d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4423a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4424179e9639SAndrew Morton 
4425179e9639SAndrew Morton 	/*
4426a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
4427179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
4428179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
4429179e9639SAndrew Morton 	 * as wide as possible.
4430179e9639SAndrew Morton 	 */
4431a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4432a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4433d773ed6bSDavid Rientjes 
4434a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4435a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4436fa5e084eSMel Gorman 
4437a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
4438a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4439d773ed6bSDavid Rientjes 
444024cf7251SMel Gorman 	if (!ret)
444124cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
444224cf7251SMel Gorman 
4443d773ed6bSDavid Rientjes 	return ret;
4444179e9639SAndrew Morton }
44459eeff239SChristoph Lameter #endif
4446894bc310SLee Schermerhorn 
444789e004eaSLee Schermerhorn /**
444864e3d12fSKuo-Hsin Yang  * check_move_unevictable_pages - check pages for evictability and move to
444964e3d12fSKuo-Hsin Yang  * appropriate zone lru list
445064e3d12fSKuo-Hsin Yang  * @pvec: pagevec with lru pages to check
445189e004eaSLee Schermerhorn  *
445264e3d12fSKuo-Hsin Yang  * Checks pages for evictability, if an evictable page is in the unevictable
445364e3d12fSKuo-Hsin Yang  * lru list, moves it to the appropriate evictable lru list. This function
445464e3d12fSKuo-Hsin Yang  * should be only used for lru pages.
445589e004eaSLee Schermerhorn  */
445664e3d12fSKuo-Hsin Yang void check_move_unevictable_pages(struct pagevec *pvec)
445789e004eaSLee Schermerhorn {
44586168d0daSAlex Shi 	struct lruvec *lruvec = NULL;
445924513264SHugh Dickins 	int pgscanned = 0;
446024513264SHugh Dickins 	int pgrescued = 0;
446189e004eaSLee Schermerhorn 	int i;
446289e004eaSLee Schermerhorn 
446364e3d12fSKuo-Hsin Yang 	for (i = 0; i < pvec->nr; i++) {
446464e3d12fSKuo-Hsin Yang 		struct page *page = pvec->pages[i];
44658d8869caSHugh Dickins 		int nr_pages;
446689e004eaSLee Schermerhorn 
44678d8869caSHugh Dickins 		if (PageTransTail(page))
44688d8869caSHugh Dickins 			continue;
44698d8869caSHugh Dickins 
44708d8869caSHugh Dickins 		nr_pages = thp_nr_pages(page);
44718d8869caSHugh Dickins 		pgscanned += nr_pages;
44728d8869caSHugh Dickins 
4473d25b5bd8SAlex Shi 		/* block memcg migration during page moving between lru */
4474d25b5bd8SAlex Shi 		if (!TestClearPageLRU(page))
4475d25b5bd8SAlex Shi 			continue;
4476d25b5bd8SAlex Shi 
44772a5e4e34SAlexander Duyck 		lruvec = relock_page_lruvec_irq(page, lruvec);
4478d25b5bd8SAlex Shi 		if (page_evictable(page) && PageUnevictable(page)) {
447946ae6b2cSYu Zhao 			del_page_from_lru_list(page, lruvec);
448024513264SHugh Dickins 			ClearPageUnevictable(page);
44813a9c9788SYu Zhao 			add_page_to_lru_list(page, lruvec);
44828d8869caSHugh Dickins 			pgrescued += nr_pages;
448389e004eaSLee Schermerhorn 		}
4484d25b5bd8SAlex Shi 		SetPageLRU(page);
448589e004eaSLee Schermerhorn 	}
448624513264SHugh Dickins 
44876168d0daSAlex Shi 	if (lruvec) {
448824513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
448924513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
44906168d0daSAlex Shi 		unlock_page_lruvec_irq(lruvec);
4491d25b5bd8SAlex Shi 	} else if (pgscanned) {
4492d25b5bd8SAlex Shi 		count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
449324513264SHugh Dickins 	}
449485046579SHugh Dickins }
449564e3d12fSKuo-Hsin Yang EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
4496