xref: /openbmc/linux/mm/vmscan.c (revision a2fb12619f202dcec83f22accc09d48347fd9138)
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
188*a2fb1261SYang Shi static int shrinker_nr_max;
1892bfd3637SYang Shi 
190*a2fb1261SYang Shi static inline int shrinker_map_size(int nr_items)
191*a2fb1261SYang Shi {
192*a2fb1261SYang Shi 	return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
193*a2fb1261SYang Shi }
1942bfd3637SYang Shi 
1952bfd3637SYang Shi static void free_shrinker_map_rcu(struct rcu_head *head)
1962bfd3637SYang Shi {
1972bfd3637SYang Shi 	kvfree(container_of(head, struct memcg_shrinker_map, rcu));
1982bfd3637SYang Shi }
1992bfd3637SYang Shi 
2002bfd3637SYang Shi static int expand_one_shrinker_map(struct mem_cgroup *memcg,
2012bfd3637SYang Shi 				   int size, int old_size)
2022bfd3637SYang Shi {
2032bfd3637SYang Shi 	struct memcg_shrinker_map *new, *old;
2042bfd3637SYang Shi 	struct mem_cgroup_per_node *pn;
2052bfd3637SYang Shi 	int nid;
2062bfd3637SYang Shi 
2072bfd3637SYang Shi 	for_each_node(nid) {
2082bfd3637SYang Shi 		pn = memcg->nodeinfo[nid];
2092bfd3637SYang Shi 		old = rcu_dereference_protected(pn->shrinker_map, true);
2102bfd3637SYang Shi 		/* Not yet online memcg */
2112bfd3637SYang Shi 		if (!old)
2122bfd3637SYang Shi 			return 0;
2132bfd3637SYang Shi 
2142bfd3637SYang Shi 		new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
2152bfd3637SYang Shi 		if (!new)
2162bfd3637SYang Shi 			return -ENOMEM;
2172bfd3637SYang Shi 
2182bfd3637SYang Shi 		/* Set all old bits, clear all new bits */
2192bfd3637SYang Shi 		memset(new->map, (int)0xff, old_size);
2202bfd3637SYang Shi 		memset((void *)new->map + old_size, 0, size - old_size);
2212bfd3637SYang Shi 
2222bfd3637SYang Shi 		rcu_assign_pointer(pn->shrinker_map, new);
2232bfd3637SYang Shi 		call_rcu(&old->rcu, free_shrinker_map_rcu);
2242bfd3637SYang Shi 	}
2252bfd3637SYang Shi 
2262bfd3637SYang Shi 	return 0;
2272bfd3637SYang Shi }
2282bfd3637SYang Shi 
2292bfd3637SYang Shi void free_shrinker_maps(struct mem_cgroup *memcg)
2302bfd3637SYang Shi {
2312bfd3637SYang Shi 	struct mem_cgroup_per_node *pn;
2322bfd3637SYang Shi 	struct memcg_shrinker_map *map;
2332bfd3637SYang Shi 	int nid;
2342bfd3637SYang Shi 
2352bfd3637SYang Shi 	if (mem_cgroup_is_root(memcg))
2362bfd3637SYang Shi 		return;
2372bfd3637SYang Shi 
2382bfd3637SYang Shi 	for_each_node(nid) {
2392bfd3637SYang Shi 		pn = memcg->nodeinfo[nid];
2402bfd3637SYang Shi 		map = rcu_dereference_protected(pn->shrinker_map, true);
2412bfd3637SYang Shi 		kvfree(map);
2422bfd3637SYang Shi 		rcu_assign_pointer(pn->shrinker_map, NULL);
2432bfd3637SYang Shi 	}
2442bfd3637SYang Shi }
2452bfd3637SYang Shi 
2462bfd3637SYang Shi int alloc_shrinker_maps(struct mem_cgroup *memcg)
2472bfd3637SYang Shi {
2482bfd3637SYang Shi 	struct memcg_shrinker_map *map;
2492bfd3637SYang Shi 	int nid, size, ret = 0;
2502bfd3637SYang Shi 
2512bfd3637SYang Shi 	if (mem_cgroup_is_root(memcg))
2522bfd3637SYang Shi 		return 0;
2532bfd3637SYang Shi 
254d27cf2aaSYang Shi 	down_write(&shrinker_rwsem);
255*a2fb1261SYang Shi 	size = shrinker_map_size(shrinker_nr_max);
2562bfd3637SYang Shi 	for_each_node(nid) {
2572bfd3637SYang Shi 		map = kvzalloc_node(sizeof(*map) + size, GFP_KERNEL, nid);
2582bfd3637SYang Shi 		if (!map) {
2592bfd3637SYang Shi 			free_shrinker_maps(memcg);
2602bfd3637SYang Shi 			ret = -ENOMEM;
2612bfd3637SYang Shi 			break;
2622bfd3637SYang Shi 		}
2632bfd3637SYang Shi 		rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, map);
2642bfd3637SYang Shi 	}
265d27cf2aaSYang Shi 	up_write(&shrinker_rwsem);
2662bfd3637SYang Shi 
2672bfd3637SYang Shi 	return ret;
2682bfd3637SYang Shi }
2692bfd3637SYang Shi 
2702bfd3637SYang Shi static int expand_shrinker_maps(int new_id)
2712bfd3637SYang Shi {
2722bfd3637SYang Shi 	int size, old_size, ret = 0;
273*a2fb1261SYang Shi 	int new_nr_max = new_id + 1;
2742bfd3637SYang Shi 	struct mem_cgroup *memcg;
2752bfd3637SYang Shi 
276*a2fb1261SYang Shi 	size = shrinker_map_size(new_nr_max);
277*a2fb1261SYang Shi 	old_size = shrinker_map_size(shrinker_nr_max);
2782bfd3637SYang Shi 	if (size <= old_size)
279*a2fb1261SYang Shi 		goto out;
2802bfd3637SYang Shi 
2812bfd3637SYang Shi 	if (!root_mem_cgroup)
282d27cf2aaSYang Shi 		goto out;
283d27cf2aaSYang Shi 
284d27cf2aaSYang Shi 	lockdep_assert_held(&shrinker_rwsem);
2852bfd3637SYang Shi 
2862bfd3637SYang Shi 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
2872bfd3637SYang Shi 	do {
2882bfd3637SYang Shi 		if (mem_cgroup_is_root(memcg))
2892bfd3637SYang Shi 			continue;
2902bfd3637SYang Shi 		ret = expand_one_shrinker_map(memcg, size, old_size);
2912bfd3637SYang Shi 		if (ret) {
2922bfd3637SYang Shi 			mem_cgroup_iter_break(NULL, memcg);
293d27cf2aaSYang Shi 			goto out;
2942bfd3637SYang Shi 		}
2952bfd3637SYang Shi 	} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
296d27cf2aaSYang Shi out:
2972bfd3637SYang Shi 	if (!ret)
298*a2fb1261SYang Shi 		shrinker_nr_max = new_nr_max;
299d27cf2aaSYang Shi 
3002bfd3637SYang Shi 	return ret;
3012bfd3637SYang Shi }
3022bfd3637SYang Shi 
3032bfd3637SYang Shi void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
3042bfd3637SYang Shi {
3052bfd3637SYang Shi 	if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
3062bfd3637SYang Shi 		struct memcg_shrinker_map *map;
3072bfd3637SYang Shi 
3082bfd3637SYang Shi 		rcu_read_lock();
3092bfd3637SYang Shi 		map = rcu_dereference(memcg->nodeinfo[nid]->shrinker_map);
3102bfd3637SYang Shi 		/* Pairs with smp mb in shrink_slab() */
3112bfd3637SYang Shi 		smp_mb__before_atomic();
3122bfd3637SYang Shi 		set_bit(shrinker_id, map->map);
3132bfd3637SYang Shi 		rcu_read_unlock();
3142bfd3637SYang Shi 	}
3152bfd3637SYang Shi }
3162bfd3637SYang Shi 
3177e010df5SKirill Tkhai /*
3187e010df5SKirill Tkhai  * We allow subsystems to populate their shrinker-related
3197e010df5SKirill Tkhai  * LRU lists before register_shrinker_prepared() is called
3207e010df5SKirill Tkhai  * for the shrinker, since we don't want to impose
3217e010df5SKirill Tkhai  * restrictions on their internal registration order.
3227e010df5SKirill Tkhai  * In this case shrink_slab_memcg() may find corresponding
3237e010df5SKirill Tkhai  * bit is set in the shrinkers map.
3247e010df5SKirill Tkhai  *
3257e010df5SKirill Tkhai  * This value is used by the function to detect registering
3267e010df5SKirill Tkhai  * shrinkers and to skip do_shrink_slab() calls for them.
3277e010df5SKirill Tkhai  */
3287e010df5SKirill Tkhai #define SHRINKER_REGISTERING ((struct shrinker *)~0UL)
3297e010df5SKirill Tkhai 
330b4c2b231SKirill Tkhai static DEFINE_IDR(shrinker_idr);
331b4c2b231SKirill Tkhai 
332b4c2b231SKirill Tkhai static int prealloc_memcg_shrinker(struct shrinker *shrinker)
333b4c2b231SKirill Tkhai {
334b4c2b231SKirill Tkhai 	int id, ret = -ENOMEM;
335b4c2b231SKirill Tkhai 
336b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
337b4c2b231SKirill Tkhai 	/* This may call shrinker, so it must use down_read_trylock() */
3387e010df5SKirill Tkhai 	id = idr_alloc(&shrinker_idr, SHRINKER_REGISTERING, 0, 0, GFP_KERNEL);
339b4c2b231SKirill Tkhai 	if (id < 0)
340b4c2b231SKirill Tkhai 		goto unlock;
341b4c2b231SKirill Tkhai 
3420a4465d3SKirill Tkhai 	if (id >= shrinker_nr_max) {
3432bfd3637SYang Shi 		if (expand_shrinker_maps(id)) {
3440a4465d3SKirill Tkhai 			idr_remove(&shrinker_idr, id);
3450a4465d3SKirill Tkhai 			goto unlock;
3460a4465d3SKirill Tkhai 		}
3470a4465d3SKirill Tkhai 	}
348b4c2b231SKirill Tkhai 	shrinker->id = id;
349b4c2b231SKirill Tkhai 	ret = 0;
350b4c2b231SKirill Tkhai unlock:
351b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
352b4c2b231SKirill Tkhai 	return ret;
353b4c2b231SKirill Tkhai }
354b4c2b231SKirill Tkhai 
355b4c2b231SKirill Tkhai static void unregister_memcg_shrinker(struct shrinker *shrinker)
356b4c2b231SKirill Tkhai {
357b4c2b231SKirill Tkhai 	int id = shrinker->id;
358b4c2b231SKirill Tkhai 
359b4c2b231SKirill Tkhai 	BUG_ON(id < 0);
360b4c2b231SKirill Tkhai 
361b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
362b4c2b231SKirill Tkhai 	idr_remove(&shrinker_idr, id);
363b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
364b4c2b231SKirill Tkhai }
365b4c2b231SKirill Tkhai 
366b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
36789b5fae5SJohannes Weiner {
368b5ead35eSJohannes Weiner 	return sc->target_mem_cgroup;
36989b5fae5SJohannes Weiner }
37097c9341fSTejun Heo 
37197c9341fSTejun Heo /**
372b5ead35eSJohannes Weiner  * writeback_throttling_sane - is the usual dirty throttling mechanism available?
37397c9341fSTejun Heo  * @sc: scan_control in question
37497c9341fSTejun Heo  *
37597c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
37697c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
37797c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
37897c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
37997c9341fSTejun Heo  * allocation and configurability.
38097c9341fSTejun Heo  *
38197c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
38297c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
38397c9341fSTejun Heo  */
384b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
38597c9341fSTejun Heo {
386b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
38797c9341fSTejun Heo 		return true;
38897c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
38969234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
39097c9341fSTejun Heo 		return true;
39197c9341fSTejun Heo #endif
39297c9341fSTejun Heo 	return false;
39397c9341fSTejun Heo }
39491a45470SKAMEZAWA Hiroyuki #else
3950a432dcbSYang Shi static int prealloc_memcg_shrinker(struct shrinker *shrinker)
3960a432dcbSYang Shi {
3970a432dcbSYang Shi 	return 0;
3980a432dcbSYang Shi }
3990a432dcbSYang Shi 
4000a432dcbSYang Shi static void unregister_memcg_shrinker(struct shrinker *shrinker)
4010a432dcbSYang Shi {
4020a432dcbSYang Shi }
4030a432dcbSYang Shi 
404b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
40589b5fae5SJohannes Weiner {
406b5ead35eSJohannes Weiner 	return false;
40789b5fae5SJohannes Weiner }
40897c9341fSTejun Heo 
409b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
41097c9341fSTejun Heo {
41197c9341fSTejun Heo 	return true;
41297c9341fSTejun Heo }
41391a45470SKAMEZAWA Hiroyuki #endif
41491a45470SKAMEZAWA Hiroyuki 
4155a1c84b4SMel Gorman /*
4165a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
4175a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
4185a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
4195a1c84b4SMel Gorman  */
4205a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
4215a1c84b4SMel Gorman {
4225a1c84b4SMel Gorman 	unsigned long nr;
4235a1c84b4SMel Gorman 
4245a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
4255a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
4265a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
4275a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
4285a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
4295a1c84b4SMel Gorman 
4305a1c84b4SMel Gorman 	return nr;
4315a1c84b4SMel Gorman }
4325a1c84b4SMel Gorman 
433fd538803SMichal Hocko /**
434fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
435fd538803SMichal Hocko  * @lruvec: lru vector
436fd538803SMichal Hocko  * @lru: lru to use
437fd538803SMichal Hocko  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
438fd538803SMichal Hocko  */
4392091339dSYu Zhao static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
4402091339dSYu Zhao 				     int zone_idx)
441c9f299d9SKOSAKI Motohiro {
442de3b0150SJohannes Weiner 	unsigned long size = 0;
443fd538803SMichal Hocko 	int zid;
444a3d8e054SKOSAKI Motohiro 
445de3b0150SJohannes Weiner 	for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
446fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
447fd538803SMichal Hocko 
448fd538803SMichal Hocko 		if (!managed_zone(zone))
449fd538803SMichal Hocko 			continue;
450fd538803SMichal Hocko 
451fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
452de3b0150SJohannes Weiner 			size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
453fd538803SMichal Hocko 		else
454de3b0150SJohannes Weiner 			size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
455c9f299d9SKOSAKI Motohiro 	}
456de3b0150SJohannes Weiner 	return size;
457b4536f0cSMichal Hocko }
458b4536f0cSMichal Hocko 
4591da177e4SLinus Torvalds /*
4601d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
4611da177e4SLinus Torvalds  */
4628e04944fSTetsuo Handa int prealloc_shrinker(struct shrinker *shrinker)
4631da177e4SLinus Torvalds {
464b9726c26SAlexey Dobriyan 	unsigned int size = sizeof(*shrinker->nr_deferred);
4651d3d4437SGlauber Costa 
4661d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
4671d3d4437SGlauber Costa 		size *= nr_node_ids;
4681d3d4437SGlauber Costa 
4691d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
4701d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
4711d3d4437SGlauber Costa 		return -ENOMEM;
472b4c2b231SKirill Tkhai 
473b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
474b4c2b231SKirill Tkhai 		if (prealloc_memcg_shrinker(shrinker))
475b4c2b231SKirill Tkhai 			goto free_deferred;
476b4c2b231SKirill Tkhai 	}
477b4c2b231SKirill Tkhai 
4788e04944fSTetsuo Handa 	return 0;
479b4c2b231SKirill Tkhai 
480b4c2b231SKirill Tkhai free_deferred:
481b4c2b231SKirill Tkhai 	kfree(shrinker->nr_deferred);
482b4c2b231SKirill Tkhai 	shrinker->nr_deferred = NULL;
483b4c2b231SKirill Tkhai 	return -ENOMEM;
4848e04944fSTetsuo Handa }
4851d3d4437SGlauber Costa 
4868e04944fSTetsuo Handa void free_prealloced_shrinker(struct shrinker *shrinker)
4878e04944fSTetsuo Handa {
488b4c2b231SKirill Tkhai 	if (!shrinker->nr_deferred)
489b4c2b231SKirill Tkhai 		return;
490b4c2b231SKirill Tkhai 
491b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
492b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
493b4c2b231SKirill Tkhai 
4948e04944fSTetsuo Handa 	kfree(shrinker->nr_deferred);
4958e04944fSTetsuo Handa 	shrinker->nr_deferred = NULL;
4968e04944fSTetsuo Handa }
4978e04944fSTetsuo Handa 
4988e04944fSTetsuo Handa void register_shrinker_prepared(struct shrinker *shrinker)
4998e04944fSTetsuo Handa {
5001da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
5011da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
50242a9a53bSYang Shi #ifdef CONFIG_MEMCG
5038df4a44cSKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
5047e010df5SKirill Tkhai 		idr_replace(&shrinker_idr, shrinker, shrinker->id);
5057e010df5SKirill Tkhai #endif
5061da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
5078e04944fSTetsuo Handa }
5088e04944fSTetsuo Handa 
5098e04944fSTetsuo Handa int register_shrinker(struct shrinker *shrinker)
5108e04944fSTetsuo Handa {
5118e04944fSTetsuo Handa 	int err = prealloc_shrinker(shrinker);
5128e04944fSTetsuo Handa 
5138e04944fSTetsuo Handa 	if (err)
5148e04944fSTetsuo Handa 		return err;
5158e04944fSTetsuo Handa 	register_shrinker_prepared(shrinker);
5161d3d4437SGlauber Costa 	return 0;
5171da177e4SLinus Torvalds }
5188e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
5191da177e4SLinus Torvalds 
5201da177e4SLinus Torvalds /*
5211da177e4SLinus Torvalds  * Remove one
5221da177e4SLinus Torvalds  */
5238e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
5241da177e4SLinus Torvalds {
525bb422a73STetsuo Handa 	if (!shrinker->nr_deferred)
526bb422a73STetsuo Handa 		return;
527b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
528b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
5291da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
5301da177e4SLinus Torvalds 	list_del(&shrinker->list);
5311da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
532ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
533bb422a73STetsuo Handa 	shrinker->nr_deferred = NULL;
5341da177e4SLinus Torvalds }
5358e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
5361da177e4SLinus Torvalds 
5371da177e4SLinus Torvalds #define SHRINK_BATCH 128
5381d3d4437SGlauber Costa 
539cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
5409092c71bSJosef Bacik 				    struct shrinker *shrinker, int priority)
5411da177e4SLinus Torvalds {
54224f7c6b9SDave Chinner 	unsigned long freed = 0;
5431da177e4SLinus Torvalds 	unsigned long long delta;
544635697c6SKonstantin Khlebnikov 	long total_scan;
545d5bc5fd3SVladimir Davydov 	long freeable;
546acf92b48SDave Chinner 	long nr;
547acf92b48SDave Chinner 	long new_nr;
5481d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
549e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
550e9299f50SDave Chinner 					  : SHRINK_BATCH;
5515f33a080SShaohua Li 	long scanned = 0, next_deferred;
5521da177e4SLinus Torvalds 
553ac7fb3adSKirill Tkhai 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
554ac7fb3adSKirill Tkhai 		nid = 0;
555ac7fb3adSKirill Tkhai 
556d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
5579b996468SKirill Tkhai 	if (freeable == 0 || freeable == SHRINK_EMPTY)
5589b996468SKirill Tkhai 		return freeable;
559635697c6SKonstantin Khlebnikov 
560acf92b48SDave Chinner 	/*
561acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
562acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
563acf92b48SDave Chinner 	 * don't also do this scanning work.
564acf92b48SDave Chinner 	 */
5651d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
566acf92b48SDave Chinner 
567acf92b48SDave Chinner 	total_scan = nr;
5684b85afbdSJohannes Weiner 	if (shrinker->seeks) {
5699092c71bSJosef Bacik 		delta = freeable >> priority;
5709092c71bSJosef Bacik 		delta *= 4;
5719092c71bSJosef Bacik 		do_div(delta, shrinker->seeks);
5724b85afbdSJohannes Weiner 	} else {
5734b85afbdSJohannes Weiner 		/*
5744b85afbdSJohannes Weiner 		 * These objects don't require any IO to create. Trim
5754b85afbdSJohannes Weiner 		 * them aggressively under memory pressure to keep
5764b85afbdSJohannes Weiner 		 * them from causing refetches in the IO caches.
5774b85afbdSJohannes Weiner 		 */
5784b85afbdSJohannes Weiner 		delta = freeable / 2;
5794b85afbdSJohannes Weiner 	}
580172b06c3SRoman Gushchin 
581acf92b48SDave Chinner 	total_scan += delta;
582acf92b48SDave Chinner 	if (total_scan < 0) {
583d75f773cSSakari Ailus 		pr_err("shrink_slab: %pS negative objects to delete nr=%ld\n",
584a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
585d5bc5fd3SVladimir Davydov 		total_scan = freeable;
5865f33a080SShaohua Li 		next_deferred = nr;
5875f33a080SShaohua Li 	} else
5885f33a080SShaohua Li 		next_deferred = total_scan;
589ea164d73SAndrea Arcangeli 
590ea164d73SAndrea Arcangeli 	/*
5913567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
5923567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
5933567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
5943567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
5953567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
596d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
5973567b59aSDave Chinner 	 * memory.
5983567b59aSDave Chinner 	 *
5993567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
6003567b59aSDave Chinner 	 * a large delta change is calculated directly.
6013567b59aSDave Chinner 	 */
602d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
603d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
6043567b59aSDave Chinner 
6053567b59aSDave Chinner 	/*
606ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
607ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
608ea164d73SAndrea Arcangeli 	 * freeable entries.
609ea164d73SAndrea Arcangeli 	 */
610d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
611d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
6121da177e4SLinus Torvalds 
61324f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
6149092c71bSJosef Bacik 				   freeable, delta, total_scan, priority);
61509576073SDave Chinner 
6160b1fb40aSVladimir Davydov 	/*
6170b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
6180b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
6190b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
6200b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
6210b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
6220b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
6230b1fb40aSVladimir Davydov 	 * batch_size.
6240b1fb40aSVladimir Davydov 	 *
6250b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
6260b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
627d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
6280b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
6290b1fb40aSVladimir Davydov 	 * possible.
6300b1fb40aSVladimir Davydov 	 */
6310b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
632d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
63324f7c6b9SDave Chinner 		unsigned long ret;
6340b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
6351da177e4SLinus Torvalds 
6360b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
637d460acb5SChris Wilson 		shrinkctl->nr_scanned = nr_to_scan;
63824f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
63924f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
6401da177e4SLinus Torvalds 			break;
64124f7c6b9SDave Chinner 		freed += ret;
64224f7c6b9SDave Chinner 
643d460acb5SChris Wilson 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
644d460acb5SChris Wilson 		total_scan -= shrinkctl->nr_scanned;
645d460acb5SChris Wilson 		scanned += shrinkctl->nr_scanned;
6461da177e4SLinus Torvalds 
6471da177e4SLinus Torvalds 		cond_resched();
6481da177e4SLinus Torvalds 	}
6491da177e4SLinus Torvalds 
6505f33a080SShaohua Li 	if (next_deferred >= scanned)
6515f33a080SShaohua Li 		next_deferred -= scanned;
6525f33a080SShaohua Li 	else
6535f33a080SShaohua Li 		next_deferred = 0;
654acf92b48SDave Chinner 	/*
655acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
656acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
657acf92b48SDave Chinner 	 * scan, there is no need to do an update.
658acf92b48SDave Chinner 	 */
6595f33a080SShaohua Li 	if (next_deferred > 0)
6605f33a080SShaohua Li 		new_nr = atomic_long_add_return(next_deferred,
6611d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
66283aeeadaSKonstantin Khlebnikov 	else
6631d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
664acf92b48SDave Chinner 
6658efb4b59SYang Shi 	trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
6661d3d4437SGlauber Costa 	return freed;
6671d3d4437SGlauber Costa }
6681d3d4437SGlauber Costa 
6690a432dcbSYang Shi #ifdef CONFIG_MEMCG
670b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
671b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
672b0dedc49SKirill Tkhai {
673b0dedc49SKirill Tkhai 	struct memcg_shrinker_map *map;
674b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
675b8e57efaSKirill Tkhai 	int i;
676b0dedc49SKirill Tkhai 
6770a432dcbSYang Shi 	if (!mem_cgroup_online(memcg))
678b0dedc49SKirill Tkhai 		return 0;
679b0dedc49SKirill Tkhai 
680b0dedc49SKirill Tkhai 	if (!down_read_trylock(&shrinker_rwsem))
681b0dedc49SKirill Tkhai 		return 0;
682b0dedc49SKirill Tkhai 
683b0dedc49SKirill Tkhai 	map = rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_map,
684b0dedc49SKirill Tkhai 					true);
685b0dedc49SKirill Tkhai 	if (unlikely(!map))
686b0dedc49SKirill Tkhai 		goto unlock;
687b0dedc49SKirill Tkhai 
688b0dedc49SKirill Tkhai 	for_each_set_bit(i, map->map, shrinker_nr_max) {
689b0dedc49SKirill Tkhai 		struct shrink_control sc = {
690b0dedc49SKirill Tkhai 			.gfp_mask = gfp_mask,
691b0dedc49SKirill Tkhai 			.nid = nid,
692b0dedc49SKirill Tkhai 			.memcg = memcg,
693b0dedc49SKirill Tkhai 		};
694b0dedc49SKirill Tkhai 		struct shrinker *shrinker;
695b0dedc49SKirill Tkhai 
696b0dedc49SKirill Tkhai 		shrinker = idr_find(&shrinker_idr, i);
6977e010df5SKirill Tkhai 		if (unlikely(!shrinker || shrinker == SHRINKER_REGISTERING)) {
6987e010df5SKirill Tkhai 			if (!shrinker)
699b0dedc49SKirill Tkhai 				clear_bit(i, map->map);
700b0dedc49SKirill Tkhai 			continue;
701b0dedc49SKirill Tkhai 		}
702b0dedc49SKirill Tkhai 
7030a432dcbSYang Shi 		/* Call non-slab shrinkers even though kmem is disabled */
7040a432dcbSYang Shi 		if (!memcg_kmem_enabled() &&
7050a432dcbSYang Shi 		    !(shrinker->flags & SHRINKER_NONSLAB))
7060a432dcbSYang Shi 			continue;
7070a432dcbSYang Shi 
708b0dedc49SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
709f90280d6SKirill Tkhai 		if (ret == SHRINK_EMPTY) {
710f90280d6SKirill Tkhai 			clear_bit(i, map->map);
711f90280d6SKirill Tkhai 			/*
712f90280d6SKirill Tkhai 			 * After the shrinker reported that it had no objects to
713f90280d6SKirill Tkhai 			 * free, but before we cleared the corresponding bit in
714f90280d6SKirill Tkhai 			 * the memcg shrinker map, a new object might have been
715f90280d6SKirill Tkhai 			 * added. To make sure, we have the bit set in this
716f90280d6SKirill Tkhai 			 * case, we invoke the shrinker one more time and reset
717f90280d6SKirill Tkhai 			 * the bit if it reports that it is not empty anymore.
718f90280d6SKirill Tkhai 			 * The memory barrier here pairs with the barrier in
7192bfd3637SYang Shi 			 * set_shrinker_bit():
720f90280d6SKirill Tkhai 			 *
721f90280d6SKirill Tkhai 			 * list_lru_add()     shrink_slab_memcg()
722f90280d6SKirill Tkhai 			 *   list_add_tail()    clear_bit()
723f90280d6SKirill Tkhai 			 *   <MB>               <MB>
724f90280d6SKirill Tkhai 			 *   set_bit()          do_shrink_slab()
725f90280d6SKirill Tkhai 			 */
726f90280d6SKirill Tkhai 			smp_mb__after_atomic();
727f90280d6SKirill Tkhai 			ret = do_shrink_slab(&sc, shrinker, priority);
7289b996468SKirill Tkhai 			if (ret == SHRINK_EMPTY)
7299b996468SKirill Tkhai 				ret = 0;
730f90280d6SKirill Tkhai 			else
7312bfd3637SYang Shi 				set_shrinker_bit(memcg, nid, i);
732f90280d6SKirill Tkhai 		}
733b0dedc49SKirill Tkhai 		freed += ret;
734b0dedc49SKirill Tkhai 
735b0dedc49SKirill Tkhai 		if (rwsem_is_contended(&shrinker_rwsem)) {
736b0dedc49SKirill Tkhai 			freed = freed ? : 1;
737b0dedc49SKirill Tkhai 			break;
738b0dedc49SKirill Tkhai 		}
739b0dedc49SKirill Tkhai 	}
740b0dedc49SKirill Tkhai unlock:
741b0dedc49SKirill Tkhai 	up_read(&shrinker_rwsem);
742b0dedc49SKirill Tkhai 	return freed;
743b0dedc49SKirill Tkhai }
7440a432dcbSYang Shi #else /* CONFIG_MEMCG */
745b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
746b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
747b0dedc49SKirill Tkhai {
748b0dedc49SKirill Tkhai 	return 0;
749b0dedc49SKirill Tkhai }
7500a432dcbSYang Shi #endif /* CONFIG_MEMCG */
751b0dedc49SKirill Tkhai 
7526b4f7799SJohannes Weiner /**
753cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
7546b4f7799SJohannes Weiner  * @gfp_mask: allocation context
7556b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
756cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
7579092c71bSJosef Bacik  * @priority: the reclaim priority
7581d3d4437SGlauber Costa  *
7596b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
7601d3d4437SGlauber Costa  *
7616b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
7626b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
7631d3d4437SGlauber Costa  *
764aeed1d32SVladimir Davydov  * @memcg specifies the memory cgroup to target. Unaware shrinkers
765aeed1d32SVladimir Davydov  * are called only if it is the root cgroup.
766cb731d6cSVladimir Davydov  *
7679092c71bSJosef Bacik  * @priority is sc->priority, we take the number of objects and >> by priority
7689092c71bSJosef Bacik  * in order to get the scan target.
7691d3d4437SGlauber Costa  *
7706b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
7711d3d4437SGlauber Costa  */
772cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
773cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
7749092c71bSJosef Bacik 				 int priority)
7751d3d4437SGlauber Costa {
776b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
7771d3d4437SGlauber Costa 	struct shrinker *shrinker;
7781d3d4437SGlauber Costa 
779fa1e512fSYang Shi 	/*
780fa1e512fSYang Shi 	 * The root memcg might be allocated even though memcg is disabled
781fa1e512fSYang Shi 	 * via "cgroup_disable=memory" boot parameter.  This could make
782fa1e512fSYang Shi 	 * mem_cgroup_is_root() return false, then just run memcg slab
783fa1e512fSYang Shi 	 * shrink, but skip global shrink.  This may result in premature
784fa1e512fSYang Shi 	 * oom.
785fa1e512fSYang Shi 	 */
786fa1e512fSYang Shi 	if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
787b0dedc49SKirill Tkhai 		return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
788cb731d6cSVladimir Davydov 
789e830c63aSTetsuo Handa 	if (!down_read_trylock(&shrinker_rwsem))
7901d3d4437SGlauber Costa 		goto out;
7911d3d4437SGlauber Costa 
7921d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
7936b4f7799SJohannes Weiner 		struct shrink_control sc = {
7946b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
7956b4f7799SJohannes Weiner 			.nid = nid,
796cb731d6cSVladimir Davydov 			.memcg = memcg,
7976b4f7799SJohannes Weiner 		};
7986b4f7799SJohannes Weiner 
7999b996468SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
8009b996468SKirill Tkhai 		if (ret == SHRINK_EMPTY)
8019b996468SKirill Tkhai 			ret = 0;
8029b996468SKirill Tkhai 		freed += ret;
803e496612cSMinchan Kim 		/*
804e496612cSMinchan Kim 		 * Bail out if someone want to register a new shrinker to
80555b65a57SEthon Paul 		 * prevent the registration from being stalled for long periods
806e496612cSMinchan Kim 		 * by parallel ongoing shrinking.
807e496612cSMinchan Kim 		 */
808e496612cSMinchan Kim 		if (rwsem_is_contended(&shrinker_rwsem)) {
809e496612cSMinchan Kim 			freed = freed ? : 1;
810e496612cSMinchan Kim 			break;
811e496612cSMinchan Kim 		}
812ec97097bSVladimir Davydov 	}
8131d3d4437SGlauber Costa 
8141da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
815f06590bdSMinchan Kim out:
816f06590bdSMinchan Kim 	cond_resched();
81724f7c6b9SDave Chinner 	return freed;
8181da177e4SLinus Torvalds }
8191da177e4SLinus Torvalds 
820cb731d6cSVladimir Davydov void drop_slab_node(int nid)
821cb731d6cSVladimir Davydov {
822cb731d6cSVladimir Davydov 	unsigned long freed;
823cb731d6cSVladimir Davydov 
824cb731d6cSVladimir Davydov 	do {
825cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
826cb731d6cSVladimir Davydov 
827069c411dSChunxin Zang 		if (fatal_signal_pending(current))
828069c411dSChunxin Zang 			return;
829069c411dSChunxin Zang 
830cb731d6cSVladimir Davydov 		freed = 0;
831aeed1d32SVladimir Davydov 		memcg = mem_cgroup_iter(NULL, NULL, NULL);
832cb731d6cSVladimir Davydov 		do {
8339092c71bSJosef Bacik 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
834cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
835cb731d6cSVladimir Davydov 	} while (freed > 10);
836cb731d6cSVladimir Davydov }
837cb731d6cSVladimir Davydov 
838cb731d6cSVladimir Davydov void drop_slab(void)
839cb731d6cSVladimir Davydov {
840cb731d6cSVladimir Davydov 	int nid;
841cb731d6cSVladimir Davydov 
842cb731d6cSVladimir Davydov 	for_each_online_node(nid)
843cb731d6cSVladimir Davydov 		drop_slab_node(nid);
844cb731d6cSVladimir Davydov }
845cb731d6cSVladimir Davydov 
8461da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
8471da177e4SLinus Torvalds {
848ceddc3a5SJohannes Weiner 	/*
849ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
85067891fffSMatthew Wilcox 	 * that isolated the page, the page cache and optional buffer
85167891fffSMatthew Wilcox 	 * heads at page->private.
852ceddc3a5SJohannes Weiner 	 */
8533efe62e4SMatthew Wilcox (Oracle) 	int page_cache_pins = thp_nr_pages(page);
85467891fffSMatthew Wilcox 	return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
8551da177e4SLinus Torvalds }
8561da177e4SLinus Torvalds 
857cb16556dSYang Shi static int may_write_to_inode(struct inode *inode)
8581da177e4SLinus Torvalds {
859930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
8601da177e4SLinus Torvalds 		return 1;
861703c2708STejun Heo 	if (!inode_write_congested(inode))
8621da177e4SLinus Torvalds 		return 1;
863703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
8641da177e4SLinus Torvalds 		return 1;
8651da177e4SLinus Torvalds 	return 0;
8661da177e4SLinus Torvalds }
8671da177e4SLinus Torvalds 
8681da177e4SLinus Torvalds /*
8691da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
8701da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
8711da177e4SLinus Torvalds  * fsync(), msync() or close().
8721da177e4SLinus Torvalds  *
8731da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
8741da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
8751da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
8761da177e4SLinus Torvalds  *
8771da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
8781da177e4SLinus Torvalds  * __GFP_FS.
8791da177e4SLinus Torvalds  */
8801da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
8811da177e4SLinus Torvalds 				struct page *page, int error)
8821da177e4SLinus Torvalds {
8837eaceaccSJens Axboe 	lock_page(page);
8843e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
8853e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
8861da177e4SLinus Torvalds 	unlock_page(page);
8871da177e4SLinus Torvalds }
8881da177e4SLinus Torvalds 
88904e62a29SChristoph Lameter /* possible outcome of pageout() */
89004e62a29SChristoph Lameter typedef enum {
89104e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
89204e62a29SChristoph Lameter 	PAGE_KEEP,
89304e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
89404e62a29SChristoph Lameter 	PAGE_ACTIVATE,
89504e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
89604e62a29SChristoph Lameter 	PAGE_SUCCESS,
89704e62a29SChristoph Lameter 	/* page is clean and locked */
89804e62a29SChristoph Lameter 	PAGE_CLEAN,
89904e62a29SChristoph Lameter } pageout_t;
90004e62a29SChristoph Lameter 
9011da177e4SLinus Torvalds /*
9021742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
9031742f19fSAndrew Morton  * Calls ->writepage().
9041da177e4SLinus Torvalds  */
905cb16556dSYang Shi static pageout_t pageout(struct page *page, struct address_space *mapping)
9061da177e4SLinus Torvalds {
9071da177e4SLinus Torvalds 	/*
9081da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
9091da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
9101da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
9111da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
9121da177e4SLinus Torvalds 	 * PagePrivate for that.
9131da177e4SLinus Torvalds 	 *
9148174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
9151da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
9161da177e4SLinus Torvalds 	 * will block.
9171da177e4SLinus Torvalds 	 *
9181da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
9191da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
9201da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
9211da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
9221da177e4SLinus Torvalds 	 */
9231da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
9241da177e4SLinus Torvalds 		return PAGE_KEEP;
9251da177e4SLinus Torvalds 	if (!mapping) {
9261da177e4SLinus Torvalds 		/*
9271da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
9281da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
9291da177e4SLinus Torvalds 		 */
930266cf658SDavid Howells 		if (page_has_private(page)) {
9311da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
9321da177e4SLinus Torvalds 				ClearPageDirty(page);
933b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
9341da177e4SLinus Torvalds 				return PAGE_CLEAN;
9351da177e4SLinus Torvalds 			}
9361da177e4SLinus Torvalds 		}
9371da177e4SLinus Torvalds 		return PAGE_KEEP;
9381da177e4SLinus Torvalds 	}
9391da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
9401da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
941cb16556dSYang Shi 	if (!may_write_to_inode(mapping->host))
9421da177e4SLinus Torvalds 		return PAGE_KEEP;
9431da177e4SLinus Torvalds 
9441da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
9451da177e4SLinus Torvalds 		int res;
9461da177e4SLinus Torvalds 		struct writeback_control wbc = {
9471da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
9481da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
949111ebb6eSOGAWA Hirofumi 			.range_start = 0,
950111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
9511da177e4SLinus Torvalds 			.for_reclaim = 1,
9521da177e4SLinus Torvalds 		};
9531da177e4SLinus Torvalds 
9541da177e4SLinus Torvalds 		SetPageReclaim(page);
9551da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
9561da177e4SLinus Torvalds 		if (res < 0)
9571da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
958994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
9591da177e4SLinus Torvalds 			ClearPageReclaim(page);
9601da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
9611da177e4SLinus Torvalds 		}
962c661b078SAndy Whitcroft 
9631da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
9641da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
9651da177e4SLinus Torvalds 			ClearPageReclaim(page);
9661da177e4SLinus Torvalds 		}
9673aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
968c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
9691da177e4SLinus Torvalds 		return PAGE_SUCCESS;
9701da177e4SLinus Torvalds 	}
9711da177e4SLinus Torvalds 
9721da177e4SLinus Torvalds 	return PAGE_CLEAN;
9731da177e4SLinus Torvalds }
9741da177e4SLinus Torvalds 
975a649fd92SAndrew Morton /*
976e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
977e286781dSNick Piggin  * gets returned with a refcount of 0.
978a649fd92SAndrew Morton  */
979a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
980b910718aSJohannes Weiner 			    bool reclaimed, struct mem_cgroup *target_memcg)
98149d2e9ccSChristoph Lameter {
982c4843a75SGreg Thelen 	unsigned long flags;
983bd4c82c2SHuang Ying 	int refcount;
984aae466b0SJoonsoo Kim 	void *shadow = NULL;
985c4843a75SGreg Thelen 
98628e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
98728e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
98849d2e9ccSChristoph Lameter 
989b93b0163SMatthew Wilcox 	xa_lock_irqsave(&mapping->i_pages, flags);
99049d2e9ccSChristoph Lameter 	/*
9910fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
9920fd0e6b0SNick Piggin 	 *
9930fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
9940fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
9950fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
9960fd0e6b0SNick Piggin 	 * here, then the following race may occur:
9970fd0e6b0SNick Piggin 	 *
9980fd0e6b0SNick Piggin 	 * get_user_pages(&page);
9990fd0e6b0SNick Piggin 	 * [user mapping goes away]
10000fd0e6b0SNick Piggin 	 * write_to(page);
10010fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
10020fd0e6b0SNick Piggin 	 * SetPageDirty(page);
10030fd0e6b0SNick Piggin 	 * put_page(page);
10040fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
10050fd0e6b0SNick Piggin 	 *
10060fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
10070fd0e6b0SNick Piggin 	 *
10080fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
10090fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
10100139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
10110fd0e6b0SNick Piggin 	 *
10120fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
1013b93b0163SMatthew Wilcox 	 * and thus under the i_pages lock, then this ordering is not required.
101449d2e9ccSChristoph Lameter 	 */
1015906d278dSWilliam Kucharski 	refcount = 1 + compound_nr(page);
1016bd4c82c2SHuang Ying 	if (!page_ref_freeze(page, refcount))
101749d2e9ccSChristoph Lameter 		goto cannot_free;
10181c4c3b99SJiang Biao 	/* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
1019e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
1020bd4c82c2SHuang Ying 		page_ref_unfreeze(page, refcount);
102149d2e9ccSChristoph Lameter 		goto cannot_free;
1022e286781dSNick Piggin 	}
102349d2e9ccSChristoph Lameter 
102449d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
102549d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
10260a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
1027aae466b0SJoonsoo Kim 		if (reclaimed && !mapping_exiting(mapping))
1028aae466b0SJoonsoo Kim 			shadow = workingset_eviction(page, target_memcg);
1029aae466b0SJoonsoo Kim 		__delete_from_swap_cache(page, swap, shadow);
1030b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
103175f6d6d2SMinchan Kim 		put_swap_page(page, swap);
1032e286781dSNick Piggin 	} else {
10336072d13cSLinus Torvalds 		void (*freepage)(struct page *);
10346072d13cSLinus Torvalds 
10356072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
1036a528910eSJohannes Weiner 		/*
1037a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
1038a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
1039a528910eSJohannes Weiner 		 *
1040a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
1041238c3046Sdylan-meiners 		 * already exiting.  This is not just an optimization,
1042a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
1043a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
1044a528910eSJohannes Weiner 		 * back.
1045f9fe48beSRoss Zwisler 		 *
1046f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
1047f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
1048f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
1049f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
1050b93b0163SMatthew Wilcox 		 * same address_space.
1051a528910eSJohannes Weiner 		 */
10529de4f22aSHuang Ying 		if (reclaimed && page_is_file_lru(page) &&
1053f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
1054b910718aSJohannes Weiner 			shadow = workingset_eviction(page, target_memcg);
105562cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
1056b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
10576072d13cSLinus Torvalds 
10586072d13cSLinus Torvalds 		if (freepage != NULL)
10596072d13cSLinus Torvalds 			freepage(page);
1060e286781dSNick Piggin 	}
1061e286781dSNick Piggin 
106249d2e9ccSChristoph Lameter 	return 1;
106349d2e9ccSChristoph Lameter 
106449d2e9ccSChristoph Lameter cannot_free:
1065b93b0163SMatthew Wilcox 	xa_unlock_irqrestore(&mapping->i_pages, flags);
106649d2e9ccSChristoph Lameter 	return 0;
106749d2e9ccSChristoph Lameter }
106849d2e9ccSChristoph Lameter 
10691da177e4SLinus Torvalds /*
1070e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
1071e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
1072e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
1073e286781dSNick Piggin  * this page.
1074e286781dSNick Piggin  */
1075e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
1076e286781dSNick Piggin {
1077b910718aSJohannes Weiner 	if (__remove_mapping(mapping, page, false, NULL)) {
1078e286781dSNick Piggin 		/*
1079e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
1080e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
1081e286781dSNick Piggin 		 * atomic operation.
1082e286781dSNick Piggin 		 */
1083fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
1084e286781dSNick Piggin 		return 1;
1085e286781dSNick Piggin 	}
1086e286781dSNick Piggin 	return 0;
1087e286781dSNick Piggin }
1088e286781dSNick Piggin 
1089894bc310SLee Schermerhorn /**
1090894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
1091894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
1092894bc310SLee Schermerhorn  *
1093894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
1094894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
1095894bc310SLee Schermerhorn  *
1096894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
1097894bc310SLee Schermerhorn  */
1098894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
1099894bc310SLee Schermerhorn {
1100c53954a0SMel Gorman 	lru_cache_add(page);
1101894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
1102894bc310SLee Schermerhorn }
1103894bc310SLee Schermerhorn 
1104dfc8d636SJohannes Weiner enum page_references {
1105dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
1106dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
110764574746SJohannes Weiner 	PAGEREF_KEEP,
1108dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
1109dfc8d636SJohannes Weiner };
1110dfc8d636SJohannes Weiner 
1111dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
1112dfc8d636SJohannes Weiner 						  struct scan_control *sc)
1113dfc8d636SJohannes Weiner {
111464574746SJohannes Weiner 	int referenced_ptes, referenced_page;
1115dfc8d636SJohannes Weiner 	unsigned long vm_flags;
1116dfc8d636SJohannes Weiner 
1117c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1118c3ac9a8aSJohannes Weiner 					  &vm_flags);
111964574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
1120dfc8d636SJohannes Weiner 
1121dfc8d636SJohannes Weiner 	/*
1122dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
1123dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
1124dfc8d636SJohannes Weiner 	 */
1125dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
1126dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
1127dfc8d636SJohannes Weiner 
112864574746SJohannes Weiner 	if (referenced_ptes) {
112964574746SJohannes Weiner 		/*
113064574746SJohannes Weiner 		 * All mapped pages start out with page table
113164574746SJohannes Weiner 		 * references from the instantiating fault, so we need
113264574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
113364574746SJohannes Weiner 		 * than once.
113464574746SJohannes Weiner 		 *
113564574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
113664574746SJohannes Weiner 		 * inactive list.  Another page table reference will
113764574746SJohannes Weiner 		 * lead to its activation.
113864574746SJohannes Weiner 		 *
113964574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
114064574746SJohannes Weiner 		 * so that recently deactivated but used pages are
114164574746SJohannes Weiner 		 * quickly recovered.
114264574746SJohannes Weiner 		 */
114364574746SJohannes Weiner 		SetPageReferenced(page);
114464574746SJohannes Weiner 
114534dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
1146dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
1147dfc8d636SJohannes Weiner 
1148c909e993SKonstantin Khlebnikov 		/*
1149c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
1150c909e993SKonstantin Khlebnikov 		 */
1151b518154eSJoonsoo Kim 		if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
1152c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
1153c909e993SKonstantin Khlebnikov 
115464574746SJohannes Weiner 		return PAGEREF_KEEP;
115564574746SJohannes Weiner 	}
115664574746SJohannes Weiner 
1157dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
11582e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
1159dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
116064574746SJohannes Weiner 
116164574746SJohannes Weiner 	return PAGEREF_RECLAIM;
1162dfc8d636SJohannes Weiner }
1163dfc8d636SJohannes Weiner 
1164e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
1165e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
1166e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
1167e2be15f6SMel Gorman {
1168b4597226SMel Gorman 	struct address_space *mapping;
1169b4597226SMel Gorman 
1170e2be15f6SMel Gorman 	/*
1171e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
1172e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
1173e2be15f6SMel Gorman 	 */
11749de4f22aSHuang Ying 	if (!page_is_file_lru(page) ||
1175802a3a92SShaohua Li 	    (PageAnon(page) && !PageSwapBacked(page))) {
1176e2be15f6SMel Gorman 		*dirty = false;
1177e2be15f6SMel Gorman 		*writeback = false;
1178e2be15f6SMel Gorman 		return;
1179e2be15f6SMel Gorman 	}
1180e2be15f6SMel Gorman 
1181e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
1182e2be15f6SMel Gorman 	*dirty = PageDirty(page);
1183e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
1184b4597226SMel Gorman 
1185b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
1186b4597226SMel Gorman 	if (!page_has_private(page))
1187b4597226SMel Gorman 		return;
1188b4597226SMel Gorman 
1189b4597226SMel Gorman 	mapping = page_mapping(page);
1190b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
1191b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1192e2be15f6SMel Gorman }
1193e2be15f6SMel Gorman 
1194e286781dSNick Piggin /*
11951742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
11961da177e4SLinus Torvalds  */
1197730ec8c0SManinder Singh static unsigned int shrink_page_list(struct list_head *page_list,
1198599d0c95SMel Gorman 				     struct pglist_data *pgdat,
1199f84f6e2bSMel Gorman 				     struct scan_control *sc,
12003c710c1aSMichal Hocko 				     struct reclaim_stat *stat,
12018940b34aSMinchan Kim 				     bool ignore_references)
12021da177e4SLinus Torvalds {
12031da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
1204abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
1205730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
1206730ec8c0SManinder Singh 	unsigned int pgactivate = 0;
12071da177e4SLinus Torvalds 
1208060f005fSKirill Tkhai 	memset(stat, 0, sizeof(*stat));
12091da177e4SLinus Torvalds 	cond_resched();
12101da177e4SLinus Torvalds 
12111da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
12121da177e4SLinus Torvalds 		struct address_space *mapping;
12131da177e4SLinus Torvalds 		struct page *page;
12148940b34aSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM;
12154b793062SKirill Tkhai 		bool dirty, writeback, may_enter_fs;
121698879b3bSYang Shi 		unsigned int nr_pages;
12171da177e4SLinus Torvalds 
12181da177e4SLinus Torvalds 		cond_resched();
12191da177e4SLinus Torvalds 
12201da177e4SLinus Torvalds 		page = lru_to_page(page_list);
12211da177e4SLinus Torvalds 		list_del(&page->lru);
12221da177e4SLinus Torvalds 
1223529ae9aaSNick Piggin 		if (!trylock_page(page))
12241da177e4SLinus Torvalds 			goto keep;
12251da177e4SLinus Torvalds 
1226309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
12271da177e4SLinus Torvalds 
1228d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
122998879b3bSYang Shi 
123098879b3bSYang Shi 		/* Account the number of base pages even though THP */
123198879b3bSYang Shi 		sc->nr_scanned += nr_pages;
123280e43426SChristoph Lameter 
123339b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
1234ad6b6704SMinchan Kim 			goto activate_locked;
1235894bc310SLee Schermerhorn 
1236a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
123780e43426SChristoph Lameter 			goto keep_locked;
123880e43426SChristoph Lameter 
1239c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1240c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1241c661b078SAndy Whitcroft 
1242e62e384eSMichal Hocko 		/*
1243894befecSAndrey Ryabinin 		 * The number of dirty pages determines if a node is marked
1244e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
1245e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
1246e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
1247e2be15f6SMel Gorman 		 */
1248e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
1249e2be15f6SMel Gorman 		if (dirty || writeback)
1250060f005fSKirill Tkhai 			stat->nr_dirty++;
1251e2be15f6SMel Gorman 
1252e2be15f6SMel Gorman 		if (dirty && !writeback)
1253060f005fSKirill Tkhai 			stat->nr_unqueued_dirty++;
1254e2be15f6SMel Gorman 
1255d04e8acdSMel Gorman 		/*
1256d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
1257d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
1258d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
1259d04e8acdSMel Gorman 		 * end of the LRU a second time.
1260d04e8acdSMel Gorman 		 */
1261e2be15f6SMel Gorman 		mapping = page_mapping(page);
12621da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
1263703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
1264d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
1265060f005fSKirill Tkhai 			stat->nr_congested++;
1266e2be15f6SMel Gorman 
1267e2be15f6SMel Gorman 		/*
1268283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
1269283aba9fSMel Gorman 		 * are three cases to consider.
1270e62e384eSMichal Hocko 		 *
1271283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
1272283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
1273283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
1274283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
1275283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
1276283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
1277283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
1278b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
1279b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
1280c3b94f44SHugh Dickins 		 *
128197c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
1282ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1283ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1284ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
128597c9341fSTejun Heo 		 *    reclaim and continue scanning.
1286283aba9fSMel Gorman 		 *
1287ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1288ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1289283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1290283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1291283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1292283aba9fSMel Gorman 		 *    would probably show more reasons.
1293283aba9fSMel Gorman 		 *
12947fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1295283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1296283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1297283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1298283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1299c55e8d03SJohannes Weiner 		 *
1300c55e8d03SJohannes Weiner 		 * In cases 1) and 2) we activate the pages to get them out of
1301c55e8d03SJohannes Weiner 		 * the way while we continue scanning for clean pages on the
1302c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1303c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1304c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1305c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1306c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1307c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1308e62e384eSMichal Hocko 		 */
1309283aba9fSMel Gorman 		if (PageWriteback(page)) {
1310283aba9fSMel Gorman 			/* Case 1 above */
1311283aba9fSMel Gorman 			if (current_is_kswapd() &&
1312283aba9fSMel Gorman 			    PageReclaim(page) &&
1313599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1314060f005fSKirill Tkhai 				stat->nr_immediate++;
1315c55e8d03SJohannes Weiner 				goto activate_locked;
1316283aba9fSMel Gorman 
1317283aba9fSMel Gorman 			/* Case 2 above */
1318b5ead35eSJohannes Weiner 			} else if (writeback_throttling_sane(sc) ||
1319ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1320c3b94f44SHugh Dickins 				/*
1321c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1322c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1323c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1324c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1325c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1326c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1327c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1328c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1329c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1330c3b94f44SHugh Dickins 				 */
1331c3b94f44SHugh Dickins 				SetPageReclaim(page);
1332060f005fSKirill Tkhai 				stat->nr_writeback++;
1333c55e8d03SJohannes Weiner 				goto activate_locked;
1334283aba9fSMel Gorman 
1335283aba9fSMel Gorman 			/* Case 3 above */
1336283aba9fSMel Gorman 			} else {
13377fadc820SHugh Dickins 				unlock_page(page);
1338c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
13397fadc820SHugh Dickins 				/* then go back and try same page again */
13407fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
13417fadc820SHugh Dickins 				continue;
1342e62e384eSMichal Hocko 			}
1343283aba9fSMel Gorman 		}
13441da177e4SLinus Torvalds 
13458940b34aSMinchan Kim 		if (!ignore_references)
13466a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
134702c6de8dSMinchan Kim 
1348dfc8d636SJohannes Weiner 		switch (references) {
1349dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
13501da177e4SLinus Torvalds 			goto activate_locked;
135164574746SJohannes Weiner 		case PAGEREF_KEEP:
135298879b3bSYang Shi 			stat->nr_ref_keep += nr_pages;
135364574746SJohannes Weiner 			goto keep_locked;
1354dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1355dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1356dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1357dfc8d636SJohannes Weiner 		}
13581da177e4SLinus Torvalds 
13591da177e4SLinus Torvalds 		/*
13601da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
13611da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1362802a3a92SShaohua Li 		 * Lazyfree page could be freed directly
13631da177e4SLinus Torvalds 		 */
1364bd4c82c2SHuang Ying 		if (PageAnon(page) && PageSwapBacked(page)) {
1365bd4c82c2SHuang Ying 			if (!PageSwapCache(page)) {
136663eb6b93SHugh Dickins 				if (!(sc->gfp_mask & __GFP_IO))
136763eb6b93SHugh Dickins 					goto keep_locked;
1368feb889fbSLinus Torvalds 				if (page_maybe_dma_pinned(page))
1369feb889fbSLinus Torvalds 					goto keep_locked;
1370747552b1SHuang Ying 				if (PageTransHuge(page)) {
1371b8f593cdSHuang Ying 					/* cannot split THP, skip it */
1372747552b1SHuang Ying 					if (!can_split_huge_page(page, NULL))
1373b8f593cdSHuang Ying 						goto activate_locked;
1374747552b1SHuang Ying 					/*
1375747552b1SHuang Ying 					 * Split pages without a PMD map right
1376747552b1SHuang Ying 					 * away. Chances are some or all of the
1377747552b1SHuang Ying 					 * tail pages can be freed without IO.
1378747552b1SHuang Ying 					 */
1379747552b1SHuang Ying 					if (!compound_mapcount(page) &&
1380bd4c82c2SHuang Ying 					    split_huge_page_to_list(page,
1381bd4c82c2SHuang Ying 								    page_list))
1382747552b1SHuang Ying 						goto activate_locked;
1383747552b1SHuang Ying 				}
13840f074658SMinchan Kim 				if (!add_to_swap(page)) {
13850f074658SMinchan Kim 					if (!PageTransHuge(page))
138698879b3bSYang Shi 						goto activate_locked_split;
1387bd4c82c2SHuang Ying 					/* Fallback to swap normal pages */
1388bd4c82c2SHuang Ying 					if (split_huge_page_to_list(page,
1389bd4c82c2SHuang Ying 								    page_list))
13900f074658SMinchan Kim 						goto activate_locked;
1391fe490cc0SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1392fe490cc0SHuang Ying 					count_vm_event(THP_SWPOUT_FALLBACK);
1393fe490cc0SHuang Ying #endif
13940f074658SMinchan Kim 					if (!add_to_swap(page))
139598879b3bSYang Shi 						goto activate_locked_split;
13960f074658SMinchan Kim 				}
13970f074658SMinchan Kim 
13984b793062SKirill Tkhai 				may_enter_fs = true;
13991da177e4SLinus Torvalds 
1400e2be15f6SMel Gorman 				/* Adding to swap updated mapping */
14011da177e4SLinus Torvalds 				mapping = page_mapping(page);
1402bd4c82c2SHuang Ying 			}
14037751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
14047751b2daSKirill A. Shutemov 			/* Split file THP */
14057751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
14067751b2daSKirill A. Shutemov 				goto keep_locked;
1407e2be15f6SMel Gorman 		}
14081da177e4SLinus Torvalds 
14091da177e4SLinus Torvalds 		/*
141098879b3bSYang Shi 		 * THP may get split above, need minus tail pages and update
141198879b3bSYang Shi 		 * nr_pages to avoid accounting tail pages twice.
141298879b3bSYang Shi 		 *
141398879b3bSYang Shi 		 * The tail pages that are added into swap cache successfully
141498879b3bSYang Shi 		 * reach here.
141598879b3bSYang Shi 		 */
141698879b3bSYang Shi 		if ((nr_pages > 1) && !PageTransHuge(page)) {
141798879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
141898879b3bSYang Shi 			nr_pages = 1;
141998879b3bSYang Shi 		}
142098879b3bSYang Shi 
142198879b3bSYang Shi 		/*
14221da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
14231da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
14241da177e4SLinus Torvalds 		 */
1425802a3a92SShaohua Li 		if (page_mapped(page)) {
1426013339dfSShakeel Butt 			enum ttu_flags flags = TTU_BATCH_FLUSH;
14271f318a9bSJaewon Kim 			bool was_swapbacked = PageSwapBacked(page);
1428bd4c82c2SHuang Ying 
1429bd4c82c2SHuang Ying 			if (unlikely(PageTransHuge(page)))
1430bd4c82c2SHuang Ying 				flags |= TTU_SPLIT_HUGE_PMD;
14311f318a9bSJaewon Kim 
1432bd4c82c2SHuang Ying 			if (!try_to_unmap(page, flags)) {
143398879b3bSYang Shi 				stat->nr_unmap_fail += nr_pages;
14341f318a9bSJaewon Kim 				if (!was_swapbacked && PageSwapBacked(page))
14351f318a9bSJaewon Kim 					stat->nr_lazyfree_fail += nr_pages;
14361da177e4SLinus Torvalds 				goto activate_locked;
14371da177e4SLinus Torvalds 			}
14381da177e4SLinus Torvalds 		}
14391da177e4SLinus Torvalds 
14401da177e4SLinus Torvalds 		if (PageDirty(page)) {
1441ee72886dSMel Gorman 			/*
14424eda4823SJohannes Weiner 			 * Only kswapd can writeback filesystem pages
14434eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
14444eda4823SJohannes Weiner 			 * injecting inefficient single-page IO into
14454eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
14464eda4823SJohannes Weiner 			 * write pages when we've encountered many
14474eda4823SJohannes Weiner 			 * dirty pages, and when we've already scanned
14484eda4823SJohannes Weiner 			 * the rest of the LRU for clean pages and see
14494eda4823SJohannes Weiner 			 * the same dirty pages again (PageReclaim).
1450ee72886dSMel Gorman 			 */
14519de4f22aSHuang Ying 			if (page_is_file_lru(page) &&
14524eda4823SJohannes Weiner 			    (!current_is_kswapd() || !PageReclaim(page) ||
1453599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
145449ea7eb6SMel Gorman 				/*
145549ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
145649ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
145749ea7eb6SMel Gorman 				 * except we already have the page isolated
145849ea7eb6SMel Gorman 				 * and know it's dirty
145949ea7eb6SMel Gorman 				 */
1460c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
146149ea7eb6SMel Gorman 				SetPageReclaim(page);
146249ea7eb6SMel Gorman 
1463c55e8d03SJohannes Weiner 				goto activate_locked;
1464ee72886dSMel Gorman 			}
1465ee72886dSMel Gorman 
1466dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
14671da177e4SLinus Torvalds 				goto keep_locked;
14684dd4b920SAndrew Morton 			if (!may_enter_fs)
14691da177e4SLinus Torvalds 				goto keep_locked;
147052a8363eSChristoph Lameter 			if (!sc->may_writepage)
14711da177e4SLinus Torvalds 				goto keep_locked;
14721da177e4SLinus Torvalds 
1473d950c947SMel Gorman 			/*
1474d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1475d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1476d950c947SMel Gorman 			 * starts and then write it out here.
1477d950c947SMel Gorman 			 */
1478d950c947SMel Gorman 			try_to_unmap_flush_dirty();
1479cb16556dSYang Shi 			switch (pageout(page, mapping)) {
14801da177e4SLinus Torvalds 			case PAGE_KEEP:
14811da177e4SLinus Torvalds 				goto keep_locked;
14821da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
14831da177e4SLinus Torvalds 				goto activate_locked;
14841da177e4SLinus Torvalds 			case PAGE_SUCCESS:
14856c357848SMatthew Wilcox (Oracle) 				stat->nr_pageout += thp_nr_pages(page);
148696f8bf4fSJohannes Weiner 
14877d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
148841ac1999SMel Gorman 					goto keep;
14897d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
14901da177e4SLinus Torvalds 					goto keep;
14917d3579e8SKOSAKI Motohiro 
14921da177e4SLinus Torvalds 				/*
14931da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
14941da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
14951da177e4SLinus Torvalds 				 */
1496529ae9aaSNick Piggin 				if (!trylock_page(page))
14971da177e4SLinus Torvalds 					goto keep;
14981da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
14991da177e4SLinus Torvalds 					goto keep_locked;
15001da177e4SLinus Torvalds 				mapping = page_mapping(page);
150101359eb2SGustavo A. R. Silva 				fallthrough;
15021da177e4SLinus Torvalds 			case PAGE_CLEAN:
15031da177e4SLinus Torvalds 				; /* try to free the page below */
15041da177e4SLinus Torvalds 			}
15051da177e4SLinus Torvalds 		}
15061da177e4SLinus Torvalds 
15071da177e4SLinus Torvalds 		/*
15081da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
15091da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
15101da177e4SLinus Torvalds 		 * the page as well.
15111da177e4SLinus Torvalds 		 *
15121da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
15131da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
15141da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
15151da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
15161da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
15171da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
15181da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
15191da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
15201da177e4SLinus Torvalds 		 *
15211da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
15221da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
1523d12b8951SYang Shi 		 * truncate_cleanup_page().  We try to drop those buffers here
15241da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
15251da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
15261da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
15271da177e4SLinus Torvalds 		 */
1528266cf658SDavid Howells 		if (page_has_private(page)) {
15291da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
15301da177e4SLinus Torvalds 				goto activate_locked;
1531e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1532e286781dSNick Piggin 				unlock_page(page);
1533e286781dSNick Piggin 				if (put_page_testzero(page))
15341da177e4SLinus Torvalds 					goto free_it;
1535e286781dSNick Piggin 				else {
1536e286781dSNick Piggin 					/*
1537e286781dSNick Piggin 					 * rare race with speculative reference.
1538e286781dSNick Piggin 					 * the speculative reference will free
1539e286781dSNick Piggin 					 * this page shortly, so we may
1540e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1541e286781dSNick Piggin 					 * leave it off the LRU).
1542e286781dSNick Piggin 					 */
1543e286781dSNick Piggin 					nr_reclaimed++;
1544e286781dSNick Piggin 					continue;
1545e286781dSNick Piggin 				}
1546e286781dSNick Piggin 			}
15471da177e4SLinus Torvalds 		}
15481da177e4SLinus Torvalds 
1549802a3a92SShaohua Li 		if (PageAnon(page) && !PageSwapBacked(page)) {
1550802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
1551802a3a92SShaohua Li 			if (!page_ref_freeze(page, 1))
155249d2e9ccSChristoph Lameter 				goto keep_locked;
1553802a3a92SShaohua Li 			if (PageDirty(page)) {
1554802a3a92SShaohua Li 				page_ref_unfreeze(page, 1);
1555802a3a92SShaohua Li 				goto keep_locked;
1556802a3a92SShaohua Li 			}
15571da177e4SLinus Torvalds 
1558802a3a92SShaohua Li 			count_vm_event(PGLAZYFREED);
15592262185cSRoman Gushchin 			count_memcg_page_event(page, PGLAZYFREED);
1560b910718aSJohannes Weiner 		} else if (!mapping || !__remove_mapping(mapping, page, true,
1561b910718aSJohannes Weiner 							 sc->target_mem_cgroup))
1562802a3a92SShaohua Li 			goto keep_locked;
15639a1ea439SHugh Dickins 
15649a1ea439SHugh Dickins 		unlock_page(page);
1565e286781dSNick Piggin free_it:
156698879b3bSYang Shi 		/*
156798879b3bSYang Shi 		 * THP may get swapped out in a whole, need account
156898879b3bSYang Shi 		 * all base pages.
156998879b3bSYang Shi 		 */
157098879b3bSYang Shi 		nr_reclaimed += nr_pages;
1571abe4c3b5SMel Gorman 
1572abe4c3b5SMel Gorman 		/*
1573abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1574abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1575abe4c3b5SMel Gorman 		 */
15767ae88534SYang Shi 		if (unlikely(PageTransHuge(page)))
1577ff45fc3cSMatthew Wilcox (Oracle) 			destroy_compound_page(page);
15787ae88534SYang Shi 		else
1579abe4c3b5SMel Gorman 			list_add(&page->lru, &free_pages);
15801da177e4SLinus Torvalds 		continue;
15811da177e4SLinus Torvalds 
158298879b3bSYang Shi activate_locked_split:
158398879b3bSYang Shi 		/*
158498879b3bSYang Shi 		 * The tail pages that are failed to add into swap cache
158598879b3bSYang Shi 		 * reach here.  Fixup nr_scanned and nr_pages.
158698879b3bSYang Shi 		 */
158798879b3bSYang Shi 		if (nr_pages > 1) {
158898879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
158998879b3bSYang Shi 			nr_pages = 1;
159098879b3bSYang Shi 		}
15911da177e4SLinus Torvalds activate_locked:
159268a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
1593ad6b6704SMinchan Kim 		if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1594ad6b6704SMinchan Kim 						PageMlocked(page)))
1595a2c43eedSHugh Dickins 			try_to_free_swap(page);
1596309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
1597ad6b6704SMinchan Kim 		if (!PageMlocked(page)) {
15989de4f22aSHuang Ying 			int type = page_is_file_lru(page);
15991da177e4SLinus Torvalds 			SetPageActive(page);
160098879b3bSYang Shi 			stat->nr_activate[type] += nr_pages;
16012262185cSRoman Gushchin 			count_memcg_page_event(page, PGACTIVATE);
1602ad6b6704SMinchan Kim 		}
16031da177e4SLinus Torvalds keep_locked:
16041da177e4SLinus Torvalds 		unlock_page(page);
16051da177e4SLinus Torvalds keep:
16061da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1607309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
16081da177e4SLinus Torvalds 	}
1609abe4c3b5SMel Gorman 
161098879b3bSYang Shi 	pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
161198879b3bSYang Shi 
1612747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
161372b252aeSMel Gorman 	try_to_unmap_flush();
16142d4894b5SMel Gorman 	free_unref_page_list(&free_pages);
1615abe4c3b5SMel Gorman 
16161da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1617886cf190SKirill Tkhai 	count_vm_events(PGACTIVATE, pgactivate);
16180a31bc97SJohannes Weiner 
161905ff5137SAndrew Morton 	return nr_reclaimed;
16201da177e4SLinus Torvalds }
16211da177e4SLinus Torvalds 
1622730ec8c0SManinder Singh unsigned int reclaim_clean_pages_from_list(struct zone *zone,
162302c6de8dSMinchan Kim 					    struct list_head *page_list)
162402c6de8dSMinchan Kim {
162502c6de8dSMinchan Kim 	struct scan_control sc = {
162602c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
162702c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
162802c6de8dSMinchan Kim 		.may_unmap = 1,
162902c6de8dSMinchan Kim 	};
16301f318a9bSJaewon Kim 	struct reclaim_stat stat;
1631730ec8c0SManinder Singh 	unsigned int nr_reclaimed;
163202c6de8dSMinchan Kim 	struct page *page, *next;
163302c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
163402c6de8dSMinchan Kim 
163502c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1636ae37c7ffSOscar Salvador 		if (!PageHuge(page) && page_is_file_lru(page) &&
1637ae37c7ffSOscar Salvador 		    !PageDirty(page) && !__PageMovable(page) &&
1638ae37c7ffSOscar Salvador 		    !PageUnevictable(page)) {
163902c6de8dSMinchan Kim 			ClearPageActive(page);
164002c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
164102c6de8dSMinchan Kim 		}
164202c6de8dSMinchan Kim 	}
164302c6de8dSMinchan Kim 
16441f318a9bSJaewon Kim 	nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1645013339dfSShakeel Butt 					&stat, true);
164602c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
16472da9f630SNicholas Piggin 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
16482da9f630SNicholas Piggin 			    -(long)nr_reclaimed);
16491f318a9bSJaewon Kim 	/*
16501f318a9bSJaewon Kim 	 * Since lazyfree pages are isolated from file LRU from the beginning,
16511f318a9bSJaewon Kim 	 * they will rotate back to anonymous LRU in the end if it failed to
16521f318a9bSJaewon Kim 	 * discard so isolated count will be mismatched.
16531f318a9bSJaewon Kim 	 * Compensate the isolated count for both LRU lists.
16541f318a9bSJaewon Kim 	 */
16551f318a9bSJaewon Kim 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
16561f318a9bSJaewon Kim 			    stat.nr_lazyfree_fail);
16571f318a9bSJaewon Kim 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
16582da9f630SNicholas Piggin 			    -(long)stat.nr_lazyfree_fail);
16591f318a9bSJaewon Kim 	return nr_reclaimed;
166002c6de8dSMinchan Kim }
166102c6de8dSMinchan Kim 
16625ad333ebSAndy Whitcroft /*
16635ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
16645ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
16655ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
16665ad333ebSAndy Whitcroft  *
16675ad333ebSAndy Whitcroft  * page:	page to consider
16685ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
16695ad333ebSAndy Whitcroft  *
1670c2135f7cSAlex Shi  * returns true on success, false on failure.
16715ad333ebSAndy Whitcroft  */
1672c2135f7cSAlex Shi bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
16735ad333ebSAndy Whitcroft {
16745ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
16755ad333ebSAndy Whitcroft 	if (!PageLRU(page))
1676c2135f7cSAlex Shi 		return false;
16775ad333ebSAndy Whitcroft 
1678e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1679e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1680c2135f7cSAlex Shi 		return false;
1681894bc310SLee Schermerhorn 
1682c8244935SMel Gorman 	/*
1683c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1684c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1685c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1686c8244935SMel Gorman 	 *
1687c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1688c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1689c8244935SMel Gorman 	 */
16901276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1691c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1692c8244935SMel Gorman 		if (PageWriteback(page))
1693c2135f7cSAlex Shi 			return false;
169439deaf85SMinchan Kim 
1695c8244935SMel Gorman 		if (PageDirty(page)) {
1696c8244935SMel Gorman 			struct address_space *mapping;
169769d763fcSMel Gorman 			bool migrate_dirty;
1698c8244935SMel Gorman 
1699c8244935SMel Gorman 			/*
1700c8244935SMel Gorman 			 * Only pages without mappings or that have a
1701c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
170269d763fcSMel Gorman 			 * without blocking. However, we can be racing with
170369d763fcSMel Gorman 			 * truncation so it's necessary to lock the page
170469d763fcSMel Gorman 			 * to stabilise the mapping as truncation holds
170569d763fcSMel Gorman 			 * the page lock until after the page is removed
170669d763fcSMel Gorman 			 * from the page cache.
1707c8244935SMel Gorman 			 */
170869d763fcSMel Gorman 			if (!trylock_page(page))
1709c2135f7cSAlex Shi 				return false;
171069d763fcSMel Gorman 
1711c8244935SMel Gorman 			mapping = page_mapping(page);
1712145e1a71SHugh Dickins 			migrate_dirty = !mapping || mapping->a_ops->migratepage;
171369d763fcSMel Gorman 			unlock_page(page);
171469d763fcSMel Gorman 			if (!migrate_dirty)
1715c2135f7cSAlex Shi 				return false;
1716c8244935SMel Gorman 		}
1717c8244935SMel Gorman 	}
1718c8244935SMel Gorman 
1719f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1720c2135f7cSAlex Shi 		return false;
1721f80c0673SMinchan Kim 
1722c2135f7cSAlex Shi 	return true;
17235ad333ebSAndy Whitcroft }
17245ad333ebSAndy Whitcroft 
17257ee36a14SMel Gorman /*
17267ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
172755b65a57SEthon Paul  * be complete before mem_cgroup_update_lru_size due to a sanity check.
17287ee36a14SMel Gorman  */
17297ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1730b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
17317ee36a14SMel Gorman {
17327ee36a14SMel Gorman 	int zid;
17337ee36a14SMel Gorman 
17347ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
17357ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
17367ee36a14SMel Gorman 			continue;
17377ee36a14SMel Gorman 
1738a892cb6bSWei Yang 		update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
17397ee36a14SMel Gorman 	}
17407ee36a14SMel Gorman 
17417ee36a14SMel Gorman }
17427ee36a14SMel Gorman 
1743f4b7e272SAndrey Ryabinin /**
174415b44736SHugh Dickins  * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
174515b44736SHugh Dickins  *
174615b44736SHugh Dickins  * lruvec->lru_lock is heavily contended.  Some of the functions that
17471da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
17481da177e4SLinus Torvalds  * and working on them outside the LRU lock.
17491da177e4SLinus Torvalds  *
17501da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
17511da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
17521da177e4SLinus Torvalds  *
175315b44736SHugh Dickins  * Lru_lock must be held before calling this function.
17541da177e4SLinus Torvalds  *
1755791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
17565dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
17571da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1758f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1759fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
17603cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
17611da177e4SLinus Torvalds  *
17621da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
17631da177e4SLinus Torvalds  */
176469e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
17655dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1766fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
1767a9e7c39fSKirill Tkhai 		enum lru_list lru)
17681da177e4SLinus Torvalds {
176975b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
177069e05944SAndrew Morton 	unsigned long nr_taken = 0;
1771599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
17727cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
17733db65812SJohannes Weiner 	unsigned long skipped = 0;
1774791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
1775b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
1776a9e7c39fSKirill Tkhai 	isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
17771da177e4SLinus Torvalds 
177898879b3bSYang Shi 	total_scan = 0;
1779791b48b6SMinchan Kim 	scan = 0;
178098879b3bSYang Shi 	while (scan < nr_to_scan && !list_empty(src)) {
17815ad333ebSAndy Whitcroft 		struct page *page;
17825ad333ebSAndy Whitcroft 
17831da177e4SLinus Torvalds 		page = lru_to_page(src);
17841da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
17851da177e4SLinus Torvalds 
1786d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
178798879b3bSYang Shi 		total_scan += nr_pages;
178898879b3bSYang Shi 
1789b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1790b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
179198879b3bSYang Shi 			nr_skipped[page_zonenum(page)] += nr_pages;
1792b2e18757SMel Gorman 			continue;
1793b2e18757SMel Gorman 		}
1794b2e18757SMel Gorman 
1795791b48b6SMinchan Kim 		/*
1796791b48b6SMinchan Kim 		 * Do not count skipped pages because that makes the function
1797791b48b6SMinchan Kim 		 * return with no isolated pages if the LRU mostly contains
1798791b48b6SMinchan Kim 		 * ineligible pages.  This causes the VM to not reclaim any
1799791b48b6SMinchan Kim 		 * pages, triggering a premature OOM.
180098879b3bSYang Shi 		 *
180198879b3bSYang Shi 		 * Account all tail pages of THP.  This would not cause
180298879b3bSYang Shi 		 * premature OOM since __isolate_lru_page() returns -EBUSY
180398879b3bSYang Shi 		 * only when the page is being freed somewhere else.
1804791b48b6SMinchan Kim 		 */
180598879b3bSYang Shi 		scan += nr_pages;
1806c2135f7cSAlex Shi 		if (!__isolate_lru_page_prepare(page, mode)) {
1807c2135f7cSAlex Shi 			/* It is being freed elsewhere */
1808c2135f7cSAlex Shi 			list_move(&page->lru, src);
1809c2135f7cSAlex Shi 			continue;
1810c2135f7cSAlex Shi 		}
18119df41314SAlex Shi 		/*
18129df41314SAlex Shi 		 * Be careful not to clear PageLRU until after we're
18139df41314SAlex Shi 		 * sure the page is not being freed elsewhere -- the
18149df41314SAlex Shi 		 * page release code relies on it.
18159df41314SAlex Shi 		 */
1816c2135f7cSAlex Shi 		if (unlikely(!get_page_unless_zero(page))) {
1817c2135f7cSAlex Shi 			list_move(&page->lru, src);
1818c2135f7cSAlex Shi 			continue;
1819c2135f7cSAlex Shi 		}
18209df41314SAlex Shi 
18219df41314SAlex Shi 		if (!TestClearPageLRU(page)) {
1822c2135f7cSAlex Shi 			/* Another thread is already isolating this page */
18239df41314SAlex Shi 			put_page(page);
1824c2135f7cSAlex Shi 			list_move(&page->lru, src);
1825c2135f7cSAlex Shi 			continue;
18269df41314SAlex Shi 		}
18279df41314SAlex Shi 
1828599d0c95SMel Gorman 		nr_taken += nr_pages;
1829599d0c95SMel Gorman 		nr_zone_taken[page_zonenum(page)] += nr_pages;
18305ad333ebSAndy Whitcroft 		list_move(&page->lru, dst);
18315ad333ebSAndy Whitcroft 	}
18321da177e4SLinus Torvalds 
1833b2e18757SMel Gorman 	/*
1834b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1835b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1836b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1837b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1838b2e18757SMel Gorman 	 * system at risk of premature OOM.
1839b2e18757SMel Gorman 	 */
18407cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
18417cc30fcfSMel Gorman 		int zid;
18427cc30fcfSMel Gorman 
18433db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
18447cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
18457cc30fcfSMel Gorman 			if (!nr_skipped[zid])
18467cc30fcfSMel Gorman 				continue;
18477cc30fcfSMel Gorman 
18487cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
18491265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
18507cc30fcfSMel Gorman 		}
18517cc30fcfSMel Gorman 	}
1852791b48b6SMinchan Kim 	*nr_scanned = total_scan;
18531265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1854791b48b6SMinchan Kim 				    total_scan, skipped, nr_taken, mode, lru);
1855b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
18561da177e4SLinus Torvalds 	return nr_taken;
18571da177e4SLinus Torvalds }
18581da177e4SLinus Torvalds 
185962695a84SNick Piggin /**
186062695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
186162695a84SNick Piggin  * @page: page to isolate from its LRU list
186262695a84SNick Piggin  *
186362695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
186462695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
186562695a84SNick Piggin  *
186662695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
186762695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
186862695a84SNick Piggin  *
186962695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1870894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1871894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1872894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
187362695a84SNick Piggin  *
187462695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
187562695a84SNick Piggin  * found will be decremented.
187662695a84SNick Piggin  *
187762695a84SNick Piggin  * Restrictions:
1878a5d09bedSMike Rapoport  *
187962695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
188001c4776bSHui Su  *     fundamental difference from isolate_lru_pages (which is called
188162695a84SNick Piggin  *     without a stable reference).
188262695a84SNick Piggin  * (2) the lru_lock must not be held.
188362695a84SNick Piggin  * (3) interrupts must be enabled.
188462695a84SNick Piggin  */
188562695a84SNick Piggin int isolate_lru_page(struct page *page)
188662695a84SNick Piggin {
188762695a84SNick Piggin 	int ret = -EBUSY;
188862695a84SNick Piggin 
1889309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1890cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
18910c917313SKonstantin Khlebnikov 
1892d25b5bd8SAlex Shi 	if (TestClearPageLRU(page)) {
1893fa9add64SHugh Dickins 		struct lruvec *lruvec;
189462695a84SNick Piggin 
18950c917313SKonstantin Khlebnikov 		get_page(page);
18966168d0daSAlex Shi 		lruvec = lock_page_lruvec_irq(page);
189746ae6b2cSYu Zhao 		del_page_from_lru_list(page, lruvec);
18986168d0daSAlex Shi 		unlock_page_lruvec_irq(lruvec);
1899fa9add64SHugh Dickins 		ret = 0;
190062695a84SNick Piggin 	}
1901d25b5bd8SAlex Shi 
190262695a84SNick Piggin 	return ret;
190362695a84SNick Piggin }
190462695a84SNick Piggin 
19055ad333ebSAndy Whitcroft /*
1906d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1907178821b8SXianting Tian  * then get rescheduled. When there are massive number of tasks doing page
1908d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1909d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1910d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
191135cd7815SRik van Riel  */
1912599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
191335cd7815SRik van Riel 		struct scan_control *sc)
191435cd7815SRik van Riel {
191535cd7815SRik van Riel 	unsigned long inactive, isolated;
191635cd7815SRik van Riel 
191735cd7815SRik van Riel 	if (current_is_kswapd())
191835cd7815SRik van Riel 		return 0;
191935cd7815SRik van Riel 
1920b5ead35eSJohannes Weiner 	if (!writeback_throttling_sane(sc))
192135cd7815SRik van Riel 		return 0;
192235cd7815SRik van Riel 
192335cd7815SRik van Riel 	if (file) {
1924599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1925599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
192635cd7815SRik van Riel 	} else {
1927599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1928599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
192935cd7815SRik van Riel 	}
193035cd7815SRik van Riel 
19313cf23841SFengguang Wu 	/*
19323cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
19333cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
19343cf23841SFengguang Wu 	 * deadlock.
19353cf23841SFengguang Wu 	 */
1936d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
19373cf23841SFengguang Wu 		inactive >>= 3;
19383cf23841SFengguang Wu 
193935cd7815SRik van Riel 	return isolated > inactive;
194035cd7815SRik van Riel }
194135cd7815SRik van Riel 
1942a222f341SKirill Tkhai /*
194315b44736SHugh Dickins  * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
194415b44736SHugh Dickins  * On return, @list is reused as a list of pages to be freed by the caller.
1945a222f341SKirill Tkhai  *
1946a222f341SKirill Tkhai  * Returns the number of pages moved to the given lruvec.
1947a222f341SKirill Tkhai  */
1948a222f341SKirill Tkhai static unsigned noinline_for_stack move_pages_to_lru(struct lruvec *lruvec,
1949a222f341SKirill Tkhai 						     struct list_head *list)
195066635629SMel Gorman {
1951a222f341SKirill Tkhai 	int nr_pages, nr_moved = 0;
19523f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
1953a222f341SKirill Tkhai 	struct page *page;
195466635629SMel Gorman 
1955a222f341SKirill Tkhai 	while (!list_empty(list)) {
1956a222f341SKirill Tkhai 		page = lru_to_page(list);
1957309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
1958a222f341SKirill Tkhai 		list_del(&page->lru);
19593d06afabSAlex Shi 		if (unlikely(!page_evictable(page))) {
19606168d0daSAlex Shi 			spin_unlock_irq(&lruvec->lru_lock);
196166635629SMel Gorman 			putback_lru_page(page);
19626168d0daSAlex Shi 			spin_lock_irq(&lruvec->lru_lock);
196366635629SMel Gorman 			continue;
196466635629SMel Gorman 		}
1965fa9add64SHugh Dickins 
19663d06afabSAlex Shi 		/*
19673d06afabSAlex Shi 		 * The SetPageLRU needs to be kept here for list integrity.
19683d06afabSAlex Shi 		 * Otherwise:
19693d06afabSAlex Shi 		 *   #0 move_pages_to_lru             #1 release_pages
19703d06afabSAlex Shi 		 *   if !put_page_testzero
19713d06afabSAlex Shi 		 *				      if (put_page_testzero())
19723d06afabSAlex Shi 		 *				        !PageLRU //skip lru_lock
19733d06afabSAlex Shi 		 *     SetPageLRU()
19743d06afabSAlex Shi 		 *     list_add(&page->lru,)
19753d06afabSAlex Shi 		 *                                        list_add(&page->lru,)
19763d06afabSAlex Shi 		 */
19777a608572SLinus Torvalds 		SetPageLRU(page);
1978a222f341SKirill Tkhai 
19793d06afabSAlex Shi 		if (unlikely(put_page_testzero(page))) {
198087560179SYu Zhao 			__clear_page_lru_flags(page);
19812bcf8879SHugh Dickins 
19822bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
19836168d0daSAlex Shi 				spin_unlock_irq(&lruvec->lru_lock);
1984ff45fc3cSMatthew Wilcox (Oracle) 				destroy_compound_page(page);
19856168d0daSAlex Shi 				spin_lock_irq(&lruvec->lru_lock);
19862bcf8879SHugh Dickins 			} else
19872bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
19883d06afabSAlex Shi 
19893d06afabSAlex Shi 			continue;
19903d06afabSAlex Shi 		}
19913d06afabSAlex Shi 
1992afca9157SAlex Shi 		/*
1993afca9157SAlex Shi 		 * All pages were isolated from the same lruvec (and isolation
1994afca9157SAlex Shi 		 * inhibits memcg migration).
1995afca9157SAlex Shi 		 */
19962a5e4e34SAlexander Duyck 		VM_BUG_ON_PAGE(!lruvec_holds_page_lru_lock(page, lruvec), page);
19973a9c9788SYu Zhao 		add_page_to_lru_list(page, lruvec);
19983d06afabSAlex Shi 		nr_pages = thp_nr_pages(page);
1999a222f341SKirill Tkhai 		nr_moved += nr_pages;
200031d8fcacSJohannes Weiner 		if (PageActive(page))
200131d8fcacSJohannes Weiner 			workingset_age_nonresident(lruvec, nr_pages);
200266635629SMel Gorman 	}
200366635629SMel Gorman 
20043f79768fSHugh Dickins 	/*
20053f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
20063f79768fSHugh Dickins 	 */
2007a222f341SKirill Tkhai 	list_splice(&pages_to_free, list);
2008a222f341SKirill Tkhai 
2009a222f341SKirill Tkhai 	return nr_moved;
201066635629SMel Gorman }
201166635629SMel Gorman 
201266635629SMel Gorman /*
2013399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
2014a37b0715SNeilBrown  * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
2015399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
2016399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
2017399ba0b9SNeilBrown  */
2018399ba0b9SNeilBrown static int current_may_throttle(void)
2019399ba0b9SNeilBrown {
2020a37b0715SNeilBrown 	return !(current->flags & PF_LOCAL_THROTTLE) ||
2021399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
2022399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
2023399ba0b9SNeilBrown }
2024399ba0b9SNeilBrown 
2025399ba0b9SNeilBrown /*
2026b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
20271742f19fSAndrew Morton  * of reclaimed pages
20281da177e4SLinus Torvalds  */
202966635629SMel Gorman static noinline_for_stack unsigned long
20301a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
20319e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
20321da177e4SLinus Torvalds {
20331da177e4SLinus Torvalds 	LIST_HEAD(page_list);
2034e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
2035730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
2036e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
2037060f005fSKirill Tkhai 	struct reclaim_stat stat;
2038497a6c1bSJohannes Weiner 	bool file = is_file_lru(lru);
2039f46b7912SKirill Tkhai 	enum vm_event_item item;
2040599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2041db73ee0dSMichal Hocko 	bool stalled = false;
204278dc583dSKOSAKI Motohiro 
2043599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
2044db73ee0dSMichal Hocko 		if (stalled)
2045db73ee0dSMichal Hocko 			return 0;
2046db73ee0dSMichal Hocko 
2047db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
2048db73ee0dSMichal Hocko 		msleep(100);
2049db73ee0dSMichal Hocko 		stalled = true;
205035cd7815SRik van Riel 
205135cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
205235cd7815SRik van Riel 		if (fatal_signal_pending(current))
205335cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
205435cd7815SRik van Riel 	}
205535cd7815SRik van Riel 
20561da177e4SLinus Torvalds 	lru_add_drain();
2057f80c0673SMinchan Kim 
20586168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
20591da177e4SLinus Torvalds 
20605dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
2061a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
206295d918fcSKonstantin Khlebnikov 
2063599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2064f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
2065b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
2066f46b7912SKirill Tkhai 		__count_vm_events(item, nr_scanned);
2067f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
2068497a6c1bSJohannes Weiner 	__count_vm_events(PGSCAN_ANON + file, nr_scanned);
2069497a6c1bSJohannes Weiner 
20706168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
2071d563c050SHillf Danton 
2072d563c050SHillf Danton 	if (nr_taken == 0)
207366635629SMel Gorman 		return 0;
2074b35ea17bSKOSAKI Motohiro 
2075013339dfSShakeel Butt 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
2076c661b078SAndy Whitcroft 
20776168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2078497a6c1bSJohannes Weiner 	move_pages_to_lru(lruvec, &page_list);
2079497a6c1bSJohannes Weiner 
2080497a6c1bSJohannes Weiner 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2081f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
2082b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
2083f46b7912SKirill Tkhai 		__count_vm_events(item, nr_reclaimed);
2084f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
2085497a6c1bSJohannes Weiner 	__count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
20866168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
20873f79768fSHugh Dickins 
208875cc3c91SAlex Shi 	lru_note_cost(lruvec, file, stat.nr_pageout);
2089747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
20902d4894b5SMel Gorman 	free_unref_page_list(&page_list);
2091e11da5b4SMel Gorman 
209292df3a72SMel Gorman 	/*
20931c610d5fSAndrey Ryabinin 	 * If dirty pages are scanned that are not queued for IO, it
20941c610d5fSAndrey Ryabinin 	 * implies that flushers are not doing their job. This can
20951c610d5fSAndrey Ryabinin 	 * happen when memory pressure pushes dirty pages to the end of
20961c610d5fSAndrey Ryabinin 	 * the LRU before the dirty limits are breached and the dirty
20971c610d5fSAndrey Ryabinin 	 * data has expired. It can also happen when the proportion of
20981c610d5fSAndrey Ryabinin 	 * dirty pages grows not through writes but through memory
20991c610d5fSAndrey Ryabinin 	 * pressure reclaiming all the clean cache. And in some cases,
21001c610d5fSAndrey Ryabinin 	 * the flushers simply cannot keep up with the allocation
21011c610d5fSAndrey Ryabinin 	 * rate. Nudge the flusher threads in case they are asleep.
21021c610d5fSAndrey Ryabinin 	 */
21031c610d5fSAndrey Ryabinin 	if (stat.nr_unqueued_dirty == nr_taken)
21041c610d5fSAndrey Ryabinin 		wakeup_flusher_threads(WB_REASON_VMSCAN);
21051c610d5fSAndrey Ryabinin 
2106d108c772SAndrey Ryabinin 	sc->nr.dirty += stat.nr_dirty;
2107d108c772SAndrey Ryabinin 	sc->nr.congested += stat.nr_congested;
2108d108c772SAndrey Ryabinin 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2109d108c772SAndrey Ryabinin 	sc->nr.writeback += stat.nr_writeback;
2110d108c772SAndrey Ryabinin 	sc->nr.immediate += stat.nr_immediate;
2111d108c772SAndrey Ryabinin 	sc->nr.taken += nr_taken;
2112d108c772SAndrey Ryabinin 	if (file)
2113d108c772SAndrey Ryabinin 		sc->nr.file_taken += nr_taken;
21148e950282SMel Gorman 
2115599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2116d51d1e64SSteven Rostedt 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
211705ff5137SAndrew Morton 	return nr_reclaimed;
21181da177e4SLinus Torvalds }
21191da177e4SLinus Torvalds 
212015b44736SHugh Dickins /*
212115b44736SHugh Dickins  * shrink_active_list() moves pages from the active LRU to the inactive LRU.
212215b44736SHugh Dickins  *
212315b44736SHugh Dickins  * We move them the other way if the page is referenced by one or more
212415b44736SHugh Dickins  * processes.
212515b44736SHugh Dickins  *
212615b44736SHugh Dickins  * If the pages are mostly unmapped, the processing is fast and it is
212715b44736SHugh Dickins  * appropriate to hold lru_lock across the whole operation.  But if
212815b44736SHugh Dickins  * the pages are mapped, the processing is slow (page_referenced()), so
212915b44736SHugh Dickins  * we should drop lru_lock around each page.  It's impossible to balance
213015b44736SHugh Dickins  * this, so instead we remove the pages from the LRU while processing them.
213115b44736SHugh Dickins  * It is safe to rely on PG_active against the non-LRU pages in here because
213215b44736SHugh Dickins  * nobody will play with that bit on a non-LRU page.
213315b44736SHugh Dickins  *
213415b44736SHugh Dickins  * The downside is that we have to touch page->_refcount against each page.
213515b44736SHugh Dickins  * But we had to alter page->flags anyway.
213615b44736SHugh Dickins  */
2137f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
21381a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
2139f16015fbSJohannes Weiner 			       struct scan_control *sc,
21409e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
21411cfb419bSKAMEZAWA Hiroyuki {
214244c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
2143f626012dSHugh Dickins 	unsigned long nr_scanned;
21446fe6b7e3SWu Fengguang 	unsigned long vm_flags;
21451cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
21468cab4754SWu Fengguang 	LIST_HEAD(l_active);
2147b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
21481cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
21499d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
21509d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
21513cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
2152599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
21531cfb419bSKAMEZAWA Hiroyuki 
21541da177e4SLinus Torvalds 	lru_add_drain();
2155f80c0673SMinchan Kim 
21566168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2157925b7673SJohannes Weiner 
21585dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2159a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
216089b5fae5SJohannes Weiner 
2161599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
21621cfb419bSKAMEZAWA Hiroyuki 
2163912c0572SShakeel Butt 	if (!cgroup_reclaim(sc))
2164599d0c95SMel Gorman 		__count_vm_events(PGREFILL, nr_scanned);
21652fa2690cSYafang Shao 	__count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
21669d5e6a9fSHugh Dickins 
21676168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
21681da177e4SLinus Torvalds 
21691da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
21701da177e4SLinus Torvalds 		cond_resched();
21711da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
21721da177e4SLinus Torvalds 		list_del(&page->lru);
21737e9cd484SRik van Riel 
217439b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
2175894bc310SLee Schermerhorn 			putback_lru_page(page);
2176894bc310SLee Schermerhorn 			continue;
2177894bc310SLee Schermerhorn 		}
2178894bc310SLee Schermerhorn 
2179cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
2180cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
2181cc715d99SMel Gorman 				if (page_has_private(page))
2182cc715d99SMel Gorman 					try_to_release_page(page, 0);
2183cc715d99SMel Gorman 				unlock_page(page);
2184cc715d99SMel Gorman 			}
2185cc715d99SMel Gorman 		}
2186cc715d99SMel Gorman 
2187c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
2188c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
21898cab4754SWu Fengguang 			/*
21908cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
21918cab4754SWu Fengguang 			 * give them one more trip around the active list. So
21928cab4754SWu Fengguang 			 * that executable code get better chances to stay in
21938cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
21948cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
21958cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
21968cab4754SWu Fengguang 			 * so we ignore them here.
21978cab4754SWu Fengguang 			 */
21989de4f22aSHuang Ying 			if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
21996c357848SMatthew Wilcox (Oracle) 				nr_rotated += thp_nr_pages(page);
22008cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
22018cab4754SWu Fengguang 				continue;
22028cab4754SWu Fengguang 			}
22038cab4754SWu Fengguang 		}
22047e9cd484SRik van Riel 
22055205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
22061899ad18SJohannes Weiner 		SetPageWorkingset(page);
22071da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
22081da177e4SLinus Torvalds 	}
22091da177e4SLinus Torvalds 
2210b555749aSAndrew Morton 	/*
22118cab4754SWu Fengguang 	 * Move pages back to the lru list.
2212b555749aSAndrew Morton 	 */
22136168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2214556adecbSRik van Riel 
2215a222f341SKirill Tkhai 	nr_activate = move_pages_to_lru(lruvec, &l_active);
2216a222f341SKirill Tkhai 	nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2217f372d89eSKirill Tkhai 	/* Keep all free pages in l_active list */
2218f372d89eSKirill Tkhai 	list_splice(&l_inactive, &l_active);
22199851ac13SKirill Tkhai 
22209851ac13SKirill Tkhai 	__count_vm_events(PGDEACTIVATE, nr_deactivate);
22219851ac13SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
22229851ac13SKirill Tkhai 
2223599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
22246168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
22252bcf8879SHugh Dickins 
2226f372d89eSKirill Tkhai 	mem_cgroup_uncharge_list(&l_active);
2227f372d89eSKirill Tkhai 	free_unref_page_list(&l_active);
22289d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
22299d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
22301da177e4SLinus Torvalds }
22311da177e4SLinus Torvalds 
22321a4e58ccSMinchan Kim unsigned long reclaim_pages(struct list_head *page_list)
22331a4e58ccSMinchan Kim {
2234f661d007SYang Shi 	int nid = NUMA_NO_NODE;
2235730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
22361a4e58ccSMinchan Kim 	LIST_HEAD(node_page_list);
22371a4e58ccSMinchan Kim 	struct reclaim_stat dummy_stat;
22381a4e58ccSMinchan Kim 	struct page *page;
22391a4e58ccSMinchan Kim 	struct scan_control sc = {
22401a4e58ccSMinchan Kim 		.gfp_mask = GFP_KERNEL,
22411a4e58ccSMinchan Kim 		.priority = DEF_PRIORITY,
22421a4e58ccSMinchan Kim 		.may_writepage = 1,
22431a4e58ccSMinchan Kim 		.may_unmap = 1,
22441a4e58ccSMinchan Kim 		.may_swap = 1,
22451a4e58ccSMinchan Kim 	};
22461a4e58ccSMinchan Kim 
22471a4e58ccSMinchan Kim 	while (!list_empty(page_list)) {
22481a4e58ccSMinchan Kim 		page = lru_to_page(page_list);
2249f661d007SYang Shi 		if (nid == NUMA_NO_NODE) {
22501a4e58ccSMinchan Kim 			nid = page_to_nid(page);
22511a4e58ccSMinchan Kim 			INIT_LIST_HEAD(&node_page_list);
22521a4e58ccSMinchan Kim 		}
22531a4e58ccSMinchan Kim 
22541a4e58ccSMinchan Kim 		if (nid == page_to_nid(page)) {
22551a4e58ccSMinchan Kim 			ClearPageActive(page);
22561a4e58ccSMinchan Kim 			list_move(&page->lru, &node_page_list);
22571a4e58ccSMinchan Kim 			continue;
22581a4e58ccSMinchan Kim 		}
22591a4e58ccSMinchan Kim 
22601a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
22611a4e58ccSMinchan Kim 						NODE_DATA(nid),
2262013339dfSShakeel Butt 						&sc, &dummy_stat, false);
22631a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
22641a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
22651a4e58ccSMinchan Kim 			list_del(&page->lru);
22661a4e58ccSMinchan Kim 			putback_lru_page(page);
22671a4e58ccSMinchan Kim 		}
22681a4e58ccSMinchan Kim 
2269f661d007SYang Shi 		nid = NUMA_NO_NODE;
22701a4e58ccSMinchan Kim 	}
22711a4e58ccSMinchan Kim 
22721a4e58ccSMinchan Kim 	if (!list_empty(&node_page_list)) {
22731a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
22741a4e58ccSMinchan Kim 						NODE_DATA(nid),
2275013339dfSShakeel Butt 						&sc, &dummy_stat, false);
22761a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
22771a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
22781a4e58ccSMinchan Kim 			list_del(&page->lru);
22791a4e58ccSMinchan Kim 			putback_lru_page(page);
22801a4e58ccSMinchan Kim 		}
22811a4e58ccSMinchan Kim 	}
22821a4e58ccSMinchan Kim 
22831a4e58ccSMinchan Kim 	return nr_reclaimed;
22841a4e58ccSMinchan Kim }
22851a4e58ccSMinchan Kim 
2286b91ac374SJohannes Weiner static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2287b91ac374SJohannes Weiner 				 struct lruvec *lruvec, struct scan_control *sc)
2288b91ac374SJohannes Weiner {
2289b91ac374SJohannes Weiner 	if (is_active_lru(lru)) {
2290b91ac374SJohannes Weiner 		if (sc->may_deactivate & (1 << is_file_lru(lru)))
2291b91ac374SJohannes Weiner 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2292b91ac374SJohannes Weiner 		else
2293b91ac374SJohannes Weiner 			sc->skipped_deactivate = 1;
2294b91ac374SJohannes Weiner 		return 0;
2295b91ac374SJohannes Weiner 	}
2296b91ac374SJohannes Weiner 
2297b91ac374SJohannes Weiner 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2298b91ac374SJohannes Weiner }
2299b91ac374SJohannes Weiner 
230059dc76b0SRik van Riel /*
230159dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
230259dc76b0SRik van Riel  * to do too much work.
230314797e23SKOSAKI Motohiro  *
230459dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
230559dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
230659dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
230759dc76b0SRik van Riel  *
230859dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
230959dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
231059dc76b0SRik van Riel  *
23112a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
23122a2e4885SJohannes Weiner  *
231359dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
23143a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
231559dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
231659dc76b0SRik van Riel  *
231759dc76b0SRik van Riel  * total     target    max
231859dc76b0SRik van Riel  * memory    ratio     inactive
231959dc76b0SRik van Riel  * -------------------------------------
232059dc76b0SRik van Riel  *   10MB       1         5MB
232159dc76b0SRik van Riel  *  100MB       1        50MB
232259dc76b0SRik van Riel  *    1GB       3       250MB
232359dc76b0SRik van Riel  *   10GB      10       0.9GB
232459dc76b0SRik van Riel  *  100GB      31         3GB
232559dc76b0SRik van Riel  *    1TB     101        10GB
232659dc76b0SRik van Riel  *   10TB     320        32GB
232714797e23SKOSAKI Motohiro  */
2328b91ac374SJohannes Weiner static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
232914797e23SKOSAKI Motohiro {
2330b91ac374SJohannes Weiner 	enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
23312a2e4885SJohannes Weiner 	unsigned long inactive, active;
23322a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
233359dc76b0SRik van Riel 	unsigned long gb;
233459dc76b0SRik van Riel 
2335b91ac374SJohannes Weiner 	inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2336b91ac374SJohannes Weiner 	active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2337f8d1a311SMel Gorman 
233859dc76b0SRik van Riel 	gb = (inactive + active) >> (30 - PAGE_SHIFT);
23394002570cSJoonsoo Kim 	if (gb)
234059dc76b0SRik van Riel 		inactive_ratio = int_sqrt(10 * gb);
2341b39415b2SRik van Riel 	else
234259dc76b0SRik van Riel 		inactive_ratio = 1;
2343fd538803SMichal Hocko 
234459dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2345b39415b2SRik van Riel }
2346b39415b2SRik van Riel 
23479a265114SJohannes Weiner enum scan_balance {
23489a265114SJohannes Weiner 	SCAN_EQUAL,
23499a265114SJohannes Weiner 	SCAN_FRACT,
23509a265114SJohannes Weiner 	SCAN_ANON,
23519a265114SJohannes Weiner 	SCAN_FILE,
23529a265114SJohannes Weiner };
23539a265114SJohannes Weiner 
23541da177e4SLinus Torvalds /*
23554f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
23564f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
23574f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
23584f98a2feSRik van Riel  * onto the active list instead of evict.
23594f98a2feSRik van Riel  *
2360be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2361be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
23624f98a2feSRik van Riel  */
2363afaf07a6SJohannes Weiner static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2364afaf07a6SJohannes Weiner 			   unsigned long *nr)
23654f98a2feSRik van Riel {
2366afaf07a6SJohannes Weiner 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2367d483a5ddSJohannes Weiner 	unsigned long anon_cost, file_cost, total_cost;
236833377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
2369ed017373SYu Zhao 	u64 fraction[ANON_AND_FILE];
23709a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
23719a265114SJohannes Weiner 	enum scan_balance scan_balance;
23729a265114SJohannes Weiner 	unsigned long ap, fp;
23739a265114SJohannes Weiner 	enum lru_list lru;
237476a33fc3SShaohua Li 
237576a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2376d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
23779a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
237876a33fc3SShaohua Li 		goto out;
237976a33fc3SShaohua Li 	}
23804f98a2feSRik van Riel 
238110316b31SJohannes Weiner 	/*
238210316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
238310316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
238410316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
238510316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
238610316b31SJohannes Weiner 	 * too expensive.
238710316b31SJohannes Weiner 	 */
2388b5ead35eSJohannes Weiner 	if (cgroup_reclaim(sc) && !swappiness) {
23899a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
239010316b31SJohannes Weiner 		goto out;
239110316b31SJohannes Weiner 	}
239210316b31SJohannes Weiner 
239310316b31SJohannes Weiner 	/*
239410316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
239510316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
239610316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
239710316b31SJohannes Weiner 	 */
239802695175SJohannes Weiner 	if (!sc->priority && swappiness) {
23999a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
240010316b31SJohannes Weiner 		goto out;
240110316b31SJohannes Weiner 	}
240210316b31SJohannes Weiner 
240311d16c25SJohannes Weiner 	/*
240453138ceaSJohannes Weiner 	 * If the system is almost out of file pages, force-scan anon.
240562376251SJohannes Weiner 	 */
2406b91ac374SJohannes Weiner 	if (sc->file_is_tiny) {
240762376251SJohannes Weiner 		scan_balance = SCAN_ANON;
240862376251SJohannes Weiner 		goto out;
240962376251SJohannes Weiner 	}
241062376251SJohannes Weiner 
241162376251SJohannes Weiner 	/*
2412b91ac374SJohannes Weiner 	 * If there is enough inactive page cache, we do not reclaim
2413b91ac374SJohannes Weiner 	 * anything from the anonymous working right now.
2414e9868505SRik van Riel 	 */
2415b91ac374SJohannes Weiner 	if (sc->cache_trim_mode) {
24169a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2417e9868505SRik van Riel 		goto out;
24184f98a2feSRik van Riel 	}
24194f98a2feSRik van Riel 
24209a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
24214f98a2feSRik van Riel 	/*
2422314b57fbSJohannes Weiner 	 * Calculate the pressure balance between anon and file pages.
2423314b57fbSJohannes Weiner 	 *
2424314b57fbSJohannes Weiner 	 * The amount of pressure we put on each LRU is inversely
2425314b57fbSJohannes Weiner 	 * proportional to the cost of reclaiming each list, as
2426314b57fbSJohannes Weiner 	 * determined by the share of pages that are refaulting, times
2427314b57fbSJohannes Weiner 	 * the relative IO cost of bringing back a swapped out
2428314b57fbSJohannes Weiner 	 * anonymous page vs reloading a filesystem page (swappiness).
2429314b57fbSJohannes Weiner 	 *
2430d483a5ddSJohannes Weiner 	 * Although we limit that influence to ensure no list gets
2431d483a5ddSJohannes Weiner 	 * left behind completely: at least a third of the pressure is
2432d483a5ddSJohannes Weiner 	 * applied, before swappiness.
2433d483a5ddSJohannes Weiner 	 *
2434314b57fbSJohannes Weiner 	 * With swappiness at 100, anon and file have equal IO cost.
243558c37f6eSKOSAKI Motohiro 	 */
2436d483a5ddSJohannes Weiner 	total_cost = sc->anon_cost + sc->file_cost;
2437d483a5ddSJohannes Weiner 	anon_cost = total_cost + sc->anon_cost;
2438d483a5ddSJohannes Weiner 	file_cost = total_cost + sc->file_cost;
2439d483a5ddSJohannes Weiner 	total_cost = anon_cost + file_cost;
244058c37f6eSKOSAKI Motohiro 
2441d483a5ddSJohannes Weiner 	ap = swappiness * (total_cost + 1);
2442d483a5ddSJohannes Weiner 	ap /= anon_cost + 1;
24434f98a2feSRik van Riel 
2444d483a5ddSJohannes Weiner 	fp = (200 - swappiness) * (total_cost + 1);
2445d483a5ddSJohannes Weiner 	fp /= file_cost + 1;
24464f98a2feSRik van Riel 
244776a33fc3SShaohua Li 	fraction[0] = ap;
244876a33fc3SShaohua Li 	fraction[1] = fp;
2449a4fe1631SJohannes Weiner 	denominator = ap + fp;
245076a33fc3SShaohua Li out:
24514111304dSHugh Dickins 	for_each_evictable_lru(lru) {
24524111304dSHugh Dickins 		int file = is_file_lru(lru);
24539783aa99SChris Down 		unsigned long lruvec_size;
245476a33fc3SShaohua Li 		unsigned long scan;
24551bc63fb1SChris Down 		unsigned long protection;
245676a33fc3SShaohua Li 
24579783aa99SChris Down 		lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
245822f7496fSYafang Shao 		protection = mem_cgroup_protection(sc->target_mem_cgroup,
245922f7496fSYafang Shao 						   memcg,
24601bc63fb1SChris Down 						   sc->memcg_low_reclaim);
24619783aa99SChris Down 
24621bc63fb1SChris Down 		if (protection) {
24639783aa99SChris Down 			/*
24649783aa99SChris Down 			 * Scale a cgroup's reclaim pressure by proportioning
24659783aa99SChris Down 			 * its current usage to its memory.low or memory.min
24669783aa99SChris Down 			 * setting.
24679783aa99SChris Down 			 *
24689783aa99SChris Down 			 * This is important, as otherwise scanning aggression
24699783aa99SChris Down 			 * becomes extremely binary -- from nothing as we
24709783aa99SChris Down 			 * approach the memory protection threshold, to totally
24719783aa99SChris Down 			 * nominal as we exceed it.  This results in requiring
24729783aa99SChris Down 			 * setting extremely liberal protection thresholds. It
24739783aa99SChris Down 			 * also means we simply get no protection at all if we
24749783aa99SChris Down 			 * set it too low, which is not ideal.
24751bc63fb1SChris Down 			 *
24761bc63fb1SChris Down 			 * If there is any protection in place, we reduce scan
24771bc63fb1SChris Down 			 * pressure by how much of the total memory used is
24781bc63fb1SChris Down 			 * within protection thresholds.
24799783aa99SChris Down 			 *
24809de7ca46SChris Down 			 * There is one special case: in the first reclaim pass,
24819de7ca46SChris Down 			 * we skip over all groups that are within their low
24829de7ca46SChris Down 			 * protection. If that fails to reclaim enough pages to
24839de7ca46SChris Down 			 * satisfy the reclaim goal, we come back and override
24849de7ca46SChris Down 			 * the best-effort low protection. However, we still
24859de7ca46SChris Down 			 * ideally want to honor how well-behaved groups are in
24869de7ca46SChris Down 			 * that case instead of simply punishing them all
24879de7ca46SChris Down 			 * equally. As such, we reclaim them based on how much
24881bc63fb1SChris Down 			 * memory they are using, reducing the scan pressure
24891bc63fb1SChris Down 			 * again by how much of the total memory used is under
24901bc63fb1SChris Down 			 * hard protection.
24919783aa99SChris Down 			 */
24921bc63fb1SChris Down 			unsigned long cgroup_size = mem_cgroup_size(memcg);
24931bc63fb1SChris Down 
24941bc63fb1SChris Down 			/* Avoid TOCTOU with earlier protection check */
24951bc63fb1SChris Down 			cgroup_size = max(cgroup_size, protection);
24961bc63fb1SChris Down 
24971bc63fb1SChris Down 			scan = lruvec_size - lruvec_size * protection /
24981bc63fb1SChris Down 				cgroup_size;
24999783aa99SChris Down 
25009783aa99SChris Down 			/*
25011bc63fb1SChris Down 			 * Minimally target SWAP_CLUSTER_MAX pages to keep
250255b65a57SEthon Paul 			 * reclaim moving forwards, avoiding decrementing
25039de7ca46SChris Down 			 * sc->priority further than desirable.
25049783aa99SChris Down 			 */
25051bc63fb1SChris Down 			scan = max(scan, SWAP_CLUSTER_MAX);
25069783aa99SChris Down 		} else {
25079783aa99SChris Down 			scan = lruvec_size;
25089783aa99SChris Down 		}
25099783aa99SChris Down 
25109783aa99SChris Down 		scan >>= sc->priority;
25119783aa99SChris Down 
2512688035f7SJohannes Weiner 		/*
2513688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2514688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2515688035f7SJohannes Weiner 		 */
2516688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
25179783aa99SChris Down 			scan = min(lruvec_size, SWAP_CLUSTER_MAX);
25189a265114SJohannes Weiner 
25199a265114SJohannes Weiner 		switch (scan_balance) {
25209a265114SJohannes Weiner 		case SCAN_EQUAL:
25219a265114SJohannes Weiner 			/* Scan lists relative to size */
25229a265114SJohannes Weiner 			break;
25239a265114SJohannes Weiner 		case SCAN_FRACT:
25249a265114SJohannes Weiner 			/*
25259a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
25269a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
252776073c64SGavin Shan 			 * Make sure we don't miss the last page on
252876073c64SGavin Shan 			 * the offlined memory cgroups because of a
252976073c64SGavin Shan 			 * round-off error.
25309a265114SJohannes Weiner 			 */
253176073c64SGavin Shan 			scan = mem_cgroup_online(memcg) ?
253276073c64SGavin Shan 			       div64_u64(scan * fraction[file], denominator) :
253376073c64SGavin Shan 			       DIV64_U64_ROUND_UP(scan * fraction[file],
25346f04f48dSSuleiman Souhlal 						  denominator);
25359a265114SJohannes Weiner 			break;
25369a265114SJohannes Weiner 		case SCAN_FILE:
25379a265114SJohannes Weiner 		case SCAN_ANON:
25389a265114SJohannes Weiner 			/* Scan one type exclusively */
2539e072bff6SMateusz Nosek 			if ((scan_balance == SCAN_FILE) != file)
25409a265114SJohannes Weiner 				scan = 0;
25419a265114SJohannes Weiner 			break;
25429a265114SJohannes Weiner 		default:
25439a265114SJohannes Weiner 			/* Look ma, no brain */
25449a265114SJohannes Weiner 			BUG();
25459a265114SJohannes Weiner 		}
25466b4f7799SJohannes Weiner 
25474111304dSHugh Dickins 		nr[lru] = scan;
254876a33fc3SShaohua Li 	}
25496e08a369SWu Fengguang }
25504f98a2feSRik van Riel 
2551afaf07a6SJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
25529b4f98cdSJohannes Weiner {
25539b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2554e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
25559b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
25569b4f98cdSJohannes Weiner 	enum lru_list lru;
25579b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
25589b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
25599b4f98cdSJohannes Weiner 	struct blk_plug plug;
25601a501907SMel Gorman 	bool scan_adjusted;
25619b4f98cdSJohannes Weiner 
2562afaf07a6SJohannes Weiner 	get_scan_count(lruvec, sc, nr);
25639b4f98cdSJohannes Weiner 
2564e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2565e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2566e82e0561SMel Gorman 
25671a501907SMel Gorman 	/*
25681a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
25691a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
25701a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
25711a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
25721a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
25731a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
25741a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
25751a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
25761a501907SMel Gorman 	 * dropped to zero at the first pass.
25771a501907SMel Gorman 	 */
2578b5ead35eSJohannes Weiner 	scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
25791a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
25801a501907SMel Gorman 
25819b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
25829b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
25839b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2584e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2585e82e0561SMel Gorman 		unsigned long nr_scanned;
2586e82e0561SMel Gorman 
25879b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
25889b4f98cdSJohannes Weiner 			if (nr[lru]) {
25899b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
25909b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
25919b4f98cdSJohannes Weiner 
25929b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
25933b991208SJohannes Weiner 							    lruvec, sc);
25949b4f98cdSJohannes Weiner 			}
25959b4f98cdSJohannes Weiner 		}
2596e82e0561SMel Gorman 
2597bd041733SMichal Hocko 		cond_resched();
2598bd041733SMichal Hocko 
2599e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2600e82e0561SMel Gorman 			continue;
2601e82e0561SMel Gorman 
26029b4f98cdSJohannes Weiner 		/*
2603e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
26041a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2605e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2606e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2607e82e0561SMel Gorman 		 * proportional to the original scan target.
2608e82e0561SMel Gorman 		 */
2609e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2610e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2611e82e0561SMel Gorman 
26121a501907SMel Gorman 		/*
26131a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
26141a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
26151a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
26161a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
26171a501907SMel Gorman 		 */
26181a501907SMel Gorman 		if (!nr_file || !nr_anon)
26191a501907SMel Gorman 			break;
26201a501907SMel Gorman 
2621e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2622e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2623e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2624e82e0561SMel Gorman 			lru = LRU_BASE;
2625e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2626e82e0561SMel Gorman 		} else {
2627e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2628e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2629e82e0561SMel Gorman 			lru = LRU_FILE;
2630e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2631e82e0561SMel Gorman 		}
2632e82e0561SMel Gorman 
2633e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2634e82e0561SMel Gorman 		nr[lru] = 0;
2635e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2636e82e0561SMel Gorman 
2637e82e0561SMel Gorman 		/*
2638e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2639e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2640e82e0561SMel Gorman 		 */
2641e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2642e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2643e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2644e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2645e82e0561SMel Gorman 
2646e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2647e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2648e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2649e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2650e82e0561SMel Gorman 
2651e82e0561SMel Gorman 		scan_adjusted = true;
26529b4f98cdSJohannes Weiner 	}
26539b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
26549b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
26559b4f98cdSJohannes Weiner 
26569b4f98cdSJohannes Weiner 	/*
26579b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
26589b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
26599b4f98cdSJohannes Weiner 	 */
2660b91ac374SJohannes Weiner 	if (total_swap_pages && inactive_is_low(lruvec, LRU_INACTIVE_ANON))
26619b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
26629b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
26639b4f98cdSJohannes Weiner }
26649b4f98cdSJohannes Weiner 
266523b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
26669e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
266723b9da55SMel Gorman {
2668d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
266923b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
26709e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
267123b9da55SMel Gorman 		return true;
267223b9da55SMel Gorman 
267323b9da55SMel Gorman 	return false;
267423b9da55SMel Gorman }
267523b9da55SMel Gorman 
26764f98a2feSRik van Riel /*
267723b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
267823b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
267923b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
2680df3a45f9SQiwu Chen  * calls try_to_compact_pages() that it will have enough free pages to succeed.
268123b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
26823e7d3449SMel Gorman  */
2683a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
26843e7d3449SMel Gorman 					unsigned long nr_reclaimed,
26853e7d3449SMel Gorman 					struct scan_control *sc)
26863e7d3449SMel Gorman {
26873e7d3449SMel Gorman 	unsigned long pages_for_compaction;
26883e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2689a9dd0a83SMel Gorman 	int z;
26903e7d3449SMel Gorman 
26913e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
26929e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
26933e7d3449SMel Gorman 		return false;
26943e7d3449SMel Gorman 
26953e7d3449SMel Gorman 	/*
26965ee04716SVlastimil Babka 	 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
26975ee04716SVlastimil Babka 	 * number of pages that were scanned. This will return to the caller
26985ee04716SVlastimil Babka 	 * with the risk reclaim/compaction and the resulting allocation attempt
26995ee04716SVlastimil Babka 	 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
27005ee04716SVlastimil Babka 	 * allocations through requiring that the full LRU list has been scanned
27015ee04716SVlastimil Babka 	 * first, by assuming that zero delta of sc->nr_scanned means full LRU
27025ee04716SVlastimil Babka 	 * scan, but that approximation was wrong, and there were corner cases
27035ee04716SVlastimil Babka 	 * where always a non-zero amount of pages were scanned.
27042876592fSMel Gorman 	 */
27052876592fSMel Gorman 	if (!nr_reclaimed)
27062876592fSMel Gorman 		return false;
27073e7d3449SMel Gorman 
27083e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2709a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2710a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
27116aa303deSMel Gorman 		if (!managed_zone(zone))
2712a9dd0a83SMel Gorman 			continue;
2713a9dd0a83SMel Gorman 
2714a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2715cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
27163e7d3449SMel Gorman 		case COMPACT_CONTINUE:
27173e7d3449SMel Gorman 			return false;
27183e7d3449SMel Gorman 		default:
2719a9dd0a83SMel Gorman 			/* check next zone */
2720a9dd0a83SMel Gorman 			;
27213e7d3449SMel Gorman 		}
27223e7d3449SMel Gorman 	}
27231c6c1597SHillf Danton 
27241c6c1597SHillf Danton 	/*
27251c6c1597SHillf Danton 	 * If we have not reclaimed enough pages for compaction and the
27261c6c1597SHillf Danton 	 * inactive lists are large enough, continue reclaiming
27271c6c1597SHillf Danton 	 */
27281c6c1597SHillf Danton 	pages_for_compaction = compact_gap(sc->order);
27291c6c1597SHillf Danton 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
27301c6c1597SHillf Danton 	if (get_nr_swap_pages() > 0)
27311c6c1597SHillf Danton 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
27321c6c1597SHillf Danton 
27335ee04716SVlastimil Babka 	return inactive_lru_pages > pages_for_compaction;
2734a9dd0a83SMel Gorman }
27353e7d3449SMel Gorman 
27360f6a5cffSJohannes Weiner static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
2737f16015fbSJohannes Weiner {
27380f6a5cffSJohannes Weiner 	struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
2739694fbc0fSAndrew Morton 	struct mem_cgroup *memcg;
2740d108c772SAndrey Ryabinin 
27410f6a5cffSJohannes Weiner 	memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
2742694fbc0fSAndrew Morton 	do {
2743afaf07a6SJohannes Weiner 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
27448e8ae645SJohannes Weiner 		unsigned long reclaimed;
2745cb731d6cSVladimir Davydov 		unsigned long scanned;
27469b4f98cdSJohannes Weiner 
2747e3336cabSXunlei Pang 		/*
2748e3336cabSXunlei Pang 		 * This loop can become CPU-bound when target memcgs
2749e3336cabSXunlei Pang 		 * aren't eligible for reclaim - either because they
2750e3336cabSXunlei Pang 		 * don't have any reclaimable pages, or because their
2751e3336cabSXunlei Pang 		 * memory is explicitly protected. Avoid soft lockups.
2752e3336cabSXunlei Pang 		 */
2753e3336cabSXunlei Pang 		cond_resched();
2754e3336cabSXunlei Pang 
275545c7f7e1SChris Down 		mem_cgroup_calculate_protection(target_memcg, memcg);
275645c7f7e1SChris Down 
275745c7f7e1SChris Down 		if (mem_cgroup_below_min(memcg)) {
2758bf8d5d52SRoman Gushchin 			/*
2759bf8d5d52SRoman Gushchin 			 * Hard protection.
2760bf8d5d52SRoman Gushchin 			 * If there is no reclaimable memory, OOM.
2761bf8d5d52SRoman Gushchin 			 */
2762bf8d5d52SRoman Gushchin 			continue;
276345c7f7e1SChris Down 		} else if (mem_cgroup_below_low(memcg)) {
2764bf8d5d52SRoman Gushchin 			/*
2765bf8d5d52SRoman Gushchin 			 * Soft protection.
2766bf8d5d52SRoman Gushchin 			 * Respect the protection only as long as
2767bf8d5d52SRoman Gushchin 			 * there is an unprotected supply
2768bf8d5d52SRoman Gushchin 			 * of reclaimable memory from other cgroups.
2769bf8d5d52SRoman Gushchin 			 */
2770d6622f63SYisheng Xie 			if (!sc->memcg_low_reclaim) {
2771d6622f63SYisheng Xie 				sc->memcg_low_skipped = 1;
2772241994edSJohannes Weiner 				continue;
2773d6622f63SYisheng Xie 			}
2774e27be240SJohannes Weiner 			memcg_memory_event(memcg, MEMCG_LOW);
2775241994edSJohannes Weiner 		}
2776241994edSJohannes Weiner 
27778e8ae645SJohannes Weiner 		reclaimed = sc->nr_reclaimed;
2778cb731d6cSVladimir Davydov 		scanned = sc->nr_scanned;
2779afaf07a6SJohannes Weiner 
2780afaf07a6SJohannes Weiner 		shrink_lruvec(lruvec, sc);
2781f9be23d6SKonstantin Khlebnikov 
278228360f39SMel Gorman 		shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
278328360f39SMel Gorman 			    sc->priority);
2784cb731d6cSVladimir Davydov 
27858e8ae645SJohannes Weiner 		/* Record the group's reclaim efficiency */
27868e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, memcg, false,
27878e8ae645SJohannes Weiner 			   sc->nr_scanned - scanned,
27888e8ae645SJohannes Weiner 			   sc->nr_reclaimed - reclaimed);
27898e8ae645SJohannes Weiner 
27900f6a5cffSJohannes Weiner 	} while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
27910f6a5cffSJohannes Weiner }
27920f6a5cffSJohannes Weiner 
27936c9e0907SLiu Song static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
27940f6a5cffSJohannes Weiner {
27950f6a5cffSJohannes Weiner 	struct reclaim_state *reclaim_state = current->reclaim_state;
27960f6a5cffSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
27971b05117dSJohannes Weiner 	struct lruvec *target_lruvec;
27980f6a5cffSJohannes Weiner 	bool reclaimable = false;
2799b91ac374SJohannes Weiner 	unsigned long file;
28000f6a5cffSJohannes Weiner 
28011b05117dSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
28021b05117dSJohannes Weiner 
28030f6a5cffSJohannes Weiner again:
28040f6a5cffSJohannes Weiner 	memset(&sc->nr, 0, sizeof(sc->nr));
28050f6a5cffSJohannes Weiner 
28060f6a5cffSJohannes Weiner 	nr_reclaimed = sc->nr_reclaimed;
28070f6a5cffSJohannes Weiner 	nr_scanned = sc->nr_scanned;
28080f6a5cffSJohannes Weiner 
280953138ceaSJohannes Weiner 	/*
28107cf111bcSJohannes Weiner 	 * Determine the scan balance between anon and file LRUs.
28117cf111bcSJohannes Weiner 	 */
28126168d0daSAlex Shi 	spin_lock_irq(&target_lruvec->lru_lock);
28137cf111bcSJohannes Weiner 	sc->anon_cost = target_lruvec->anon_cost;
28147cf111bcSJohannes Weiner 	sc->file_cost = target_lruvec->file_cost;
28156168d0daSAlex Shi 	spin_unlock_irq(&target_lruvec->lru_lock);
28167cf111bcSJohannes Weiner 
28177cf111bcSJohannes Weiner 	/*
2818b91ac374SJohannes Weiner 	 * Target desirable inactive:active list ratios for the anon
2819b91ac374SJohannes Weiner 	 * and file LRU lists.
2820b91ac374SJohannes Weiner 	 */
2821b91ac374SJohannes Weiner 	if (!sc->force_deactivate) {
2822b91ac374SJohannes Weiner 		unsigned long refaults;
2823b91ac374SJohannes Weiner 
2824170b04b7SJoonsoo Kim 		refaults = lruvec_page_state(target_lruvec,
2825170b04b7SJoonsoo Kim 				WORKINGSET_ACTIVATE_ANON);
2826170b04b7SJoonsoo Kim 		if (refaults != target_lruvec->refaults[0] ||
2827170b04b7SJoonsoo Kim 			inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2828b91ac374SJohannes Weiner 			sc->may_deactivate |= DEACTIVATE_ANON;
2829b91ac374SJohannes Weiner 		else
2830b91ac374SJohannes Weiner 			sc->may_deactivate &= ~DEACTIVATE_ANON;
2831b91ac374SJohannes Weiner 
2832b91ac374SJohannes Weiner 		/*
2833b91ac374SJohannes Weiner 		 * When refaults are being observed, it means a new
2834b91ac374SJohannes Weiner 		 * workingset is being established. Deactivate to get
2835b91ac374SJohannes Weiner 		 * rid of any stale active pages quickly.
2836b91ac374SJohannes Weiner 		 */
2837b91ac374SJohannes Weiner 		refaults = lruvec_page_state(target_lruvec,
2838170b04b7SJoonsoo Kim 				WORKINGSET_ACTIVATE_FILE);
2839170b04b7SJoonsoo Kim 		if (refaults != target_lruvec->refaults[1] ||
2840b91ac374SJohannes Weiner 		    inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2841b91ac374SJohannes Weiner 			sc->may_deactivate |= DEACTIVATE_FILE;
2842b91ac374SJohannes Weiner 		else
2843b91ac374SJohannes Weiner 			sc->may_deactivate &= ~DEACTIVATE_FILE;
2844b91ac374SJohannes Weiner 	} else
2845b91ac374SJohannes Weiner 		sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2846b91ac374SJohannes Weiner 
2847b91ac374SJohannes Weiner 	/*
2848b91ac374SJohannes Weiner 	 * If we have plenty of inactive file pages that aren't
2849b91ac374SJohannes Weiner 	 * thrashing, try to reclaim those first before touching
2850b91ac374SJohannes Weiner 	 * anonymous pages.
2851b91ac374SJohannes Weiner 	 */
2852b91ac374SJohannes Weiner 	file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2853b91ac374SJohannes Weiner 	if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2854b91ac374SJohannes Weiner 		sc->cache_trim_mode = 1;
2855b91ac374SJohannes Weiner 	else
2856b91ac374SJohannes Weiner 		sc->cache_trim_mode = 0;
2857b91ac374SJohannes Weiner 
2858b91ac374SJohannes Weiner 	/*
285953138ceaSJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
286053138ceaSJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
286153138ceaSJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
286253138ceaSJohannes Weiner 	 * shrinks, so does the window for rotation from references.
286353138ceaSJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
286453138ceaSJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
286553138ceaSJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
286653138ceaSJohannes Weiner 	 */
286753138ceaSJohannes Weiner 	if (!cgroup_reclaim(sc)) {
286853138ceaSJohannes Weiner 		unsigned long total_high_wmark = 0;
2869b91ac374SJohannes Weiner 		unsigned long free, anon;
2870b91ac374SJohannes Weiner 		int z;
287153138ceaSJohannes Weiner 
287253138ceaSJohannes Weiner 		free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
287353138ceaSJohannes Weiner 		file = node_page_state(pgdat, NR_ACTIVE_FILE) +
287453138ceaSJohannes Weiner 			   node_page_state(pgdat, NR_INACTIVE_FILE);
287553138ceaSJohannes Weiner 
287653138ceaSJohannes Weiner 		for (z = 0; z < MAX_NR_ZONES; z++) {
287753138ceaSJohannes Weiner 			struct zone *zone = &pgdat->node_zones[z];
287853138ceaSJohannes Weiner 			if (!managed_zone(zone))
287953138ceaSJohannes Weiner 				continue;
288053138ceaSJohannes Weiner 
288153138ceaSJohannes Weiner 			total_high_wmark += high_wmark_pages(zone);
288253138ceaSJohannes Weiner 		}
288353138ceaSJohannes Weiner 
2884b91ac374SJohannes Weiner 		/*
2885b91ac374SJohannes Weiner 		 * Consider anon: if that's low too, this isn't a
2886b91ac374SJohannes Weiner 		 * runaway file reclaim problem, but rather just
2887b91ac374SJohannes Weiner 		 * extreme pressure. Reclaim as per usual then.
2888b91ac374SJohannes Weiner 		 */
2889b91ac374SJohannes Weiner 		anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2890b91ac374SJohannes Weiner 
2891b91ac374SJohannes Weiner 		sc->file_is_tiny =
2892b91ac374SJohannes Weiner 			file + free <= total_high_wmark &&
2893b91ac374SJohannes Weiner 			!(sc->may_deactivate & DEACTIVATE_ANON) &&
2894b91ac374SJohannes Weiner 			anon >> sc->priority;
289553138ceaSJohannes Weiner 	}
289653138ceaSJohannes Weiner 
28970f6a5cffSJohannes Weiner 	shrink_node_memcgs(pgdat, sc);
289870ddf637SAnton Vorontsov 
28996b4f7799SJohannes Weiner 	if (reclaim_state) {
2900cb731d6cSVladimir Davydov 		sc->nr_reclaimed += reclaim_state->reclaimed_slab;
29016b4f7799SJohannes Weiner 		reclaim_state->reclaimed_slab = 0;
29026b4f7799SJohannes Weiner 	}
29036b4f7799SJohannes Weiner 
29048e8ae645SJohannes Weiner 	/* Record the subtree's reclaim efficiency */
29051b05117dSJohannes Weiner 	vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
290670ddf637SAnton Vorontsov 		   sc->nr_scanned - nr_scanned,
290770ddf637SAnton Vorontsov 		   sc->nr_reclaimed - nr_reclaimed);
290870ddf637SAnton Vorontsov 
29092344d7e4SJohannes Weiner 	if (sc->nr_reclaimed - nr_reclaimed)
29102344d7e4SJohannes Weiner 		reclaimable = true;
29112344d7e4SJohannes Weiner 
2912e3c1ac58SAndrey Ryabinin 	if (current_is_kswapd()) {
2913d108c772SAndrey Ryabinin 		/*
2914e3c1ac58SAndrey Ryabinin 		 * If reclaim is isolating dirty pages under writeback,
2915e3c1ac58SAndrey Ryabinin 		 * it implies that the long-lived page allocation rate
2916e3c1ac58SAndrey Ryabinin 		 * is exceeding the page laundering rate. Either the
2917e3c1ac58SAndrey Ryabinin 		 * global limits are not being effective at throttling
2918e3c1ac58SAndrey Ryabinin 		 * processes due to the page distribution throughout
2919e3c1ac58SAndrey Ryabinin 		 * zones or there is heavy usage of a slow backing
2920e3c1ac58SAndrey Ryabinin 		 * device. The only option is to throttle from reclaim
2921e3c1ac58SAndrey Ryabinin 		 * context which is not ideal as there is no guarantee
2922d108c772SAndrey Ryabinin 		 * the dirtying process is throttled in the same way
2923d108c772SAndrey Ryabinin 		 * balance_dirty_pages() manages.
2924d108c772SAndrey Ryabinin 		 *
2925e3c1ac58SAndrey Ryabinin 		 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
2926e3c1ac58SAndrey Ryabinin 		 * count the number of pages under pages flagged for
2927e3c1ac58SAndrey Ryabinin 		 * immediate reclaim and stall if any are encountered
2928e3c1ac58SAndrey Ryabinin 		 * in the nr_immediate check below.
2929d108c772SAndrey Ryabinin 		 */
2930d108c772SAndrey Ryabinin 		if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
2931d108c772SAndrey Ryabinin 			set_bit(PGDAT_WRITEBACK, &pgdat->flags);
2932d108c772SAndrey Ryabinin 
2933d108c772SAndrey Ryabinin 		/* Allow kswapd to start writing pages during reclaim.*/
2934d108c772SAndrey Ryabinin 		if (sc->nr.unqueued_dirty == sc->nr.file_taken)
2935d108c772SAndrey Ryabinin 			set_bit(PGDAT_DIRTY, &pgdat->flags);
2936d108c772SAndrey Ryabinin 
2937d108c772SAndrey Ryabinin 		/*
29381eba09c1SRandy Dunlap 		 * If kswapd scans pages marked for immediate
2939d108c772SAndrey Ryabinin 		 * reclaim and under writeback (nr_immediate), it
2940d108c772SAndrey Ryabinin 		 * implies that pages are cycling through the LRU
2941d108c772SAndrey Ryabinin 		 * faster than they are written so also forcibly stall.
2942d108c772SAndrey Ryabinin 		 */
2943d108c772SAndrey Ryabinin 		if (sc->nr.immediate)
2944d108c772SAndrey Ryabinin 			congestion_wait(BLK_RW_ASYNC, HZ/10);
2945d108c772SAndrey Ryabinin 	}
2946d108c772SAndrey Ryabinin 
2947d108c772SAndrey Ryabinin 	/*
29481b05117dSJohannes Weiner 	 * Tag a node/memcg as congested if all the dirty pages
29491b05117dSJohannes Weiner 	 * scanned were backed by a congested BDI and
29501b05117dSJohannes Weiner 	 * wait_iff_congested will stall.
29511b05117dSJohannes Weiner 	 *
2952e3c1ac58SAndrey Ryabinin 	 * Legacy memcg will stall in page writeback so avoid forcibly
2953e3c1ac58SAndrey Ryabinin 	 * stalling in wait_iff_congested().
2954e3c1ac58SAndrey Ryabinin 	 */
29551b05117dSJohannes Weiner 	if ((current_is_kswapd() ||
29561b05117dSJohannes Weiner 	     (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
2957e3c1ac58SAndrey Ryabinin 	    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
29581b05117dSJohannes Weiner 		set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
2959e3c1ac58SAndrey Ryabinin 
2960e3c1ac58SAndrey Ryabinin 	/*
2961d108c772SAndrey Ryabinin 	 * Stall direct reclaim for IO completions if underlying BDIs
2962d108c772SAndrey Ryabinin 	 * and node is congested. Allow kswapd to continue until it
2963d108c772SAndrey Ryabinin 	 * starts encountering unqueued dirty pages or cycling through
2964d108c772SAndrey Ryabinin 	 * the LRU too quickly.
2965d108c772SAndrey Ryabinin 	 */
29661b05117dSJohannes Weiner 	if (!current_is_kswapd() && current_may_throttle() &&
29671b05117dSJohannes Weiner 	    !sc->hibernation_mode &&
29681b05117dSJohannes Weiner 	    test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
2969e3c1ac58SAndrey Ryabinin 		wait_iff_congested(BLK_RW_ASYNC, HZ/10);
2970d108c772SAndrey Ryabinin 
2971d2af3397SJohannes Weiner 	if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
2972d2af3397SJohannes Weiner 				    sc))
2973d2af3397SJohannes Weiner 		goto again;
29742344d7e4SJohannes Weiner 
2975c73322d0SJohannes Weiner 	/*
2976c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
2977c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
2978c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
2979c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
2980c73322d0SJohannes Weiner 	 */
2981c73322d0SJohannes Weiner 	if (reclaimable)
2982c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
2983f16015fbSJohannes Weiner }
2984f16015fbSJohannes Weiner 
298553853e2dSVlastimil Babka /*
2986fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
2987fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
2988fdd4c614SVlastimil Babka  * should reclaim first.
298953853e2dSVlastimil Babka  */
29904f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2991fe4b1b24SMel Gorman {
299231483b6aSMel Gorman 	unsigned long watermark;
2993fdd4c614SVlastimil Babka 	enum compact_result suitable;
2994fe4b1b24SMel Gorman 
2995fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2996fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
2997fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
2998fdd4c614SVlastimil Babka 		return true;
2999fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
3000fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
3001fe4b1b24SMel Gorman 		return false;
3002fe4b1b24SMel Gorman 
3003fdd4c614SVlastimil Babka 	/*
3004fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
3005fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
3006fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
3007fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
3008fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
3009fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
3010fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
3011fdd4c614SVlastimil Babka 	 */
3012fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
3013fdd4c614SVlastimil Babka 
3014fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
3015fe4b1b24SMel Gorman }
3016fe4b1b24SMel Gorman 
30171da177e4SLinus Torvalds /*
30181da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
30191da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
30201da177e4SLinus Torvalds  * request.
30211da177e4SLinus Torvalds  *
30221da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
30231da177e4SLinus Torvalds  * scan then give up on it.
30241da177e4SLinus Torvalds  */
30250a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
30261da177e4SLinus Torvalds {
3027dd1a239fSMel Gorman 	struct zoneref *z;
302854a6eb5cSMel Gorman 	struct zone *zone;
30290608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
30300608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3031619d0d76SWeijie Yang 	gfp_t orig_mask;
303279dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
30331cfb419bSKAMEZAWA Hiroyuki 
3034cc715d99SMel Gorman 	/*
3035cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
3036cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
3037cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
3038cc715d99SMel Gorman 	 */
3039619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
3040b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
3041cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
30424f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
3043b2e18757SMel Gorman 	}
3044cc715d99SMel Gorman 
3045d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
3046b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
3047b2e18757SMel Gorman 		/*
30481cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
30491cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
30501cfb419bSKAMEZAWA Hiroyuki 		 */
3051b5ead35eSJohannes Weiner 		if (!cgroup_reclaim(sc)) {
3052344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
3053344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
30541da177e4SLinus Torvalds 				continue;
305565ec02cbSVladimir Davydov 
3056e0887c19SRik van Riel 			/*
3057e0c23279SMel Gorman 			 * If we already have plenty of memory free for
3058e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
3059e0c23279SMel Gorman 			 * Even though compaction is invoked for any
3060e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
3061e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
3062c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
3063c7cfa37bSCopot Alexandru 			 * page allocations.
3064e0887c19SRik van Riel 			 */
30650b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
30660b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
30674f588331SMel Gorman 			    compaction_ready(zone, sc)) {
30680b06496aSJohannes Weiner 				sc->compaction_ready = true;
3069e0887c19SRik van Riel 				continue;
3070e0887c19SRik van Riel 			}
30710b06496aSJohannes Weiner 
30720608f43dSAndrew Morton 			/*
307379dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
307479dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
307579dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
307679dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
307779dafcdcSMel Gorman 			 */
307879dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
307979dafcdcSMel Gorman 				continue;
308079dafcdcSMel Gorman 
308179dafcdcSMel Gorman 			/*
30820608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
30830608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
30840608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
30850608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
30860608f43dSAndrew Morton 			 */
30870608f43dSAndrew Morton 			nr_soft_scanned = 0;
3088ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
30890608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
30900608f43dSAndrew Morton 						&nr_soft_scanned);
30910608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
30920608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
3093ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
3094ac34a1a3SKAMEZAWA Hiroyuki 		}
3095d149e3b2SYing Han 
309679dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
309779dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
309879dafcdcSMel Gorman 			continue;
309979dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
3100970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
31011da177e4SLinus Torvalds 	}
3102e0c23279SMel Gorman 
310365ec02cbSVladimir Davydov 	/*
3104619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
3105619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
3106619d0d76SWeijie Yang 	 */
3107619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
31081da177e4SLinus Torvalds }
31091da177e4SLinus Torvalds 
3110b910718aSJohannes Weiner static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
31112a2e4885SJohannes Weiner {
3112b910718aSJohannes Weiner 	struct lruvec *target_lruvec;
31132a2e4885SJohannes Weiner 	unsigned long refaults;
31142a2e4885SJohannes Weiner 
3115b910718aSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
3116170b04b7SJoonsoo Kim 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
3117170b04b7SJoonsoo Kim 	target_lruvec->refaults[0] = refaults;
3118170b04b7SJoonsoo Kim 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
3119170b04b7SJoonsoo Kim 	target_lruvec->refaults[1] = refaults;
31202a2e4885SJohannes Weiner }
31212a2e4885SJohannes Weiner 
31221da177e4SLinus Torvalds /*
31231da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
31241da177e4SLinus Torvalds  *
31251da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
31261da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
31271da177e4SLinus Torvalds  *
31281da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
31291da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
31305b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
31315b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
31325b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
31335b0830cbSJens Axboe  * work, and the allocation attempt will fail.
3134a41f24eaSNishanth Aravamudan  *
3135a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
3136a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
31371da177e4SLinus Torvalds  */
3138dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
31393115cd91SVladimir Davydov 					  struct scan_control *sc)
31401da177e4SLinus Torvalds {
3141241994edSJohannes Weiner 	int initial_priority = sc->priority;
31422a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
31432a2e4885SJohannes Weiner 	struct zoneref *z;
31442a2e4885SJohannes Weiner 	struct zone *zone;
3145241994edSJohannes Weiner retry:
3146873b4771SKeika Kobayashi 	delayacct_freepages_start();
3147873b4771SKeika Kobayashi 
3148b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
31497cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
31501da177e4SLinus Torvalds 
31519e3b2f8cSKonstantin Khlebnikov 	do {
315270ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
315370ddf637SAnton Vorontsov 				sc->priority);
315466e1707bSBalbir Singh 		sc->nr_scanned = 0;
31550a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
3156e0c23279SMel Gorman 
3157bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
31580b06496aSJohannes Weiner 			break;
31590b06496aSJohannes Weiner 
31600b06496aSJohannes Weiner 		if (sc->compaction_ready)
31610b06496aSJohannes Weiner 			break;
31621da177e4SLinus Torvalds 
31631da177e4SLinus Torvalds 		/*
31640e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
31650e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
31660e50ce3bSMinchan Kim 		 */
31670e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
31680e50ce3bSMinchan Kim 			sc->may_writepage = 1;
31690b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
3170bb21c7ceSKOSAKI Motohiro 
31712a2e4885SJohannes Weiner 	last_pgdat = NULL;
31722a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
31732a2e4885SJohannes Weiner 					sc->nodemask) {
31742a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
31752a2e4885SJohannes Weiner 			continue;
31762a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
31771b05117dSJohannes Weiner 
31782a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
31791b05117dSJohannes Weiner 
31801b05117dSJohannes Weiner 		if (cgroup_reclaim(sc)) {
31811b05117dSJohannes Weiner 			struct lruvec *lruvec;
31821b05117dSJohannes Weiner 
31831b05117dSJohannes Weiner 			lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
31841b05117dSJohannes Weiner 						   zone->zone_pgdat);
31851b05117dSJohannes Weiner 			clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
31861b05117dSJohannes Weiner 		}
31872a2e4885SJohannes Weiner 	}
31882a2e4885SJohannes Weiner 
3189873b4771SKeika Kobayashi 	delayacct_freepages_end();
3190873b4771SKeika Kobayashi 
3191bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
3192bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
3193bb21c7ceSKOSAKI Motohiro 
31940cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
31950b06496aSJohannes Weiner 	if (sc->compaction_ready)
31967335084dSMel Gorman 		return 1;
31977335084dSMel Gorman 
3198b91ac374SJohannes Weiner 	/*
3199b91ac374SJohannes Weiner 	 * We make inactive:active ratio decisions based on the node's
3200b91ac374SJohannes Weiner 	 * composition of memory, but a restrictive reclaim_idx or a
3201b91ac374SJohannes Weiner 	 * memory.low cgroup setting can exempt large amounts of
3202b91ac374SJohannes Weiner 	 * memory from reclaim. Neither of which are very common, so
3203b91ac374SJohannes Weiner 	 * instead of doing costly eligibility calculations of the
3204b91ac374SJohannes Weiner 	 * entire cgroup subtree up front, we assume the estimates are
3205b91ac374SJohannes Weiner 	 * good, and retry with forcible deactivation if that fails.
3206b91ac374SJohannes Weiner 	 */
3207b91ac374SJohannes Weiner 	if (sc->skipped_deactivate) {
3208b91ac374SJohannes Weiner 		sc->priority = initial_priority;
3209b91ac374SJohannes Weiner 		sc->force_deactivate = 1;
3210b91ac374SJohannes Weiner 		sc->skipped_deactivate = 0;
3211b91ac374SJohannes Weiner 		goto retry;
3212b91ac374SJohannes Weiner 	}
3213b91ac374SJohannes Weiner 
3214241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
3215d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
3216241994edSJohannes Weiner 		sc->priority = initial_priority;
3217b91ac374SJohannes Weiner 		sc->force_deactivate = 0;
3218d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
3219d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
3220241994edSJohannes Weiner 		goto retry;
3221241994edSJohannes Weiner 	}
3222241994edSJohannes Weiner 
3223bb21c7ceSKOSAKI Motohiro 	return 0;
32241da177e4SLinus Torvalds }
32251da177e4SLinus Torvalds 
3226c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
32275515061dSMel Gorman {
32285515061dSMel Gorman 	struct zone *zone;
32295515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
32305515061dSMel Gorman 	unsigned long free_pages = 0;
32315515061dSMel Gorman 	int i;
32325515061dSMel Gorman 	bool wmark_ok;
32335515061dSMel Gorman 
3234c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3235c73322d0SJohannes Weiner 		return true;
3236c73322d0SJohannes Weiner 
32375515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
32385515061dSMel Gorman 		zone = &pgdat->node_zones[i];
3239d450abd8SJohannes Weiner 		if (!managed_zone(zone))
3240d450abd8SJohannes Weiner 			continue;
3241d450abd8SJohannes Weiner 
3242d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
3243675becceSMel Gorman 			continue;
3244675becceSMel Gorman 
32455515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
32465515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
32475515061dSMel Gorman 	}
32485515061dSMel Gorman 
3249675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
3250675becceSMel Gorman 	if (!pfmemalloc_reserve)
3251675becceSMel Gorman 		return true;
3252675becceSMel Gorman 
32535515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
32545515061dSMel Gorman 
32555515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
32565515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
325797a225e6SJoonsoo Kim 		if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
325897a225e6SJoonsoo Kim 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
32595644e1fbSQian Cai 
32605515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
32615515061dSMel Gorman 	}
32625515061dSMel Gorman 
32635515061dSMel Gorman 	return wmark_ok;
32645515061dSMel Gorman }
32655515061dSMel Gorman 
32665515061dSMel Gorman /*
32675515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
32685515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
32695515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
327050694c28SMel Gorman  * when the low watermark is reached.
327150694c28SMel Gorman  *
327250694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
327350694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
32745515061dSMel Gorman  */
327550694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
32765515061dSMel Gorman 					nodemask_t *nodemask)
32775515061dSMel Gorman {
3278675becceSMel Gorman 	struct zoneref *z;
32795515061dSMel Gorman 	struct zone *zone;
3280675becceSMel Gorman 	pg_data_t *pgdat = NULL;
32815515061dSMel Gorman 
32825515061dSMel Gorman 	/*
32835515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
32845515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
32855515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
32865515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
32875515061dSMel Gorman 	 * processes to block on log_wait_commit().
32885515061dSMel Gorman 	 */
32895515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
329050694c28SMel Gorman 		goto out;
329150694c28SMel Gorman 
329250694c28SMel Gorman 	/*
329350694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
329450694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
329550694c28SMel Gorman 	 */
329650694c28SMel Gorman 	if (fatal_signal_pending(current))
329750694c28SMel Gorman 		goto out;
32985515061dSMel Gorman 
3299675becceSMel Gorman 	/*
3300675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
3301675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3302675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
3303675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
3304675becceSMel Gorman 	 *
3305675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
3306675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
3307675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
3308675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
3309675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
3310675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
3311675becceSMel Gorman 	 * should make reasonable progress.
3312675becceSMel Gorman 	 */
3313675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
331417636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
3315675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
3316675becceSMel Gorman 			continue;
3317675becceSMel Gorman 
3318675becceSMel Gorman 		/* Throttle based on the first usable node */
33195515061dSMel Gorman 		pgdat = zone->zone_pgdat;
3320c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
332150694c28SMel Gorman 			goto out;
3322675becceSMel Gorman 		break;
3323675becceSMel Gorman 	}
3324675becceSMel Gorman 
3325675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
3326675becceSMel Gorman 	if (!pgdat)
3327675becceSMel Gorman 		goto out;
33285515061dSMel Gorman 
332968243e76SMel Gorman 	/* Account for the throttling */
333068243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
333168243e76SMel Gorman 
33325515061dSMel Gorman 	/*
33335515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
33345515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
33355515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
33365515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
33375515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
33385515061dSMel Gorman 	 * second before continuing.
33395515061dSMel Gorman 	 */
33405515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
33415515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3342c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
334350694c28SMel Gorman 
334450694c28SMel Gorman 		goto check_pending;
33455515061dSMel Gorman 	}
33465515061dSMel Gorman 
33475515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
33485515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3349c73322d0SJohannes Weiner 		allow_direct_reclaim(pgdat));
335050694c28SMel Gorman 
335150694c28SMel Gorman check_pending:
335250694c28SMel Gorman 	if (fatal_signal_pending(current))
335350694c28SMel Gorman 		return true;
335450694c28SMel Gorman 
335550694c28SMel Gorman out:
335650694c28SMel Gorman 	return false;
33575515061dSMel Gorman }
33585515061dSMel Gorman 
3359dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3360327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
336166e1707bSBalbir Singh {
336233906bc5SMel Gorman 	unsigned long nr_reclaimed;
336366e1707bSBalbir Singh 	struct scan_control sc = {
336422fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3365f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3366b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
3367ee814fe2SJohannes Weiner 		.order = order,
3368ee814fe2SJohannes Weiner 		.nodemask = nodemask,
3369ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
3370ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3371a6dc60f8SJohannes Weiner 		.may_unmap = 1,
33722e2e4259SKOSAKI Motohiro 		.may_swap = 1,
337366e1707bSBalbir Singh 	};
337466e1707bSBalbir Singh 
33755515061dSMel Gorman 	/*
3376bb451fdfSGreg Thelen 	 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3377bb451fdfSGreg Thelen 	 * Confirm they are large enough for max values.
3378bb451fdfSGreg Thelen 	 */
3379bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3380bb451fdfSGreg Thelen 	BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3381bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3382bb451fdfSGreg Thelen 
3383bb451fdfSGreg Thelen 	/*
338450694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
338550694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
338650694c28SMel Gorman 	 * point.
33875515061dSMel Gorman 	 */
3388f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
33895515061dSMel Gorman 		return 1;
33905515061dSMel Gorman 
33911732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
33923481c37fSYafang Shao 	trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
339333906bc5SMel Gorman 
33943115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
339533906bc5SMel Gorman 
339633906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
33971732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
339833906bc5SMel Gorman 
339933906bc5SMel Gorman 	return nr_reclaimed;
340066e1707bSBalbir Singh }
340166e1707bSBalbir Singh 
3402c255a458SAndrew Morton #ifdef CONFIG_MEMCG
340366e1707bSBalbir Singh 
3404d2e5fb92SMichal Hocko /* Only used by soft limit reclaim. Do not reuse for anything else. */
3405a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
34064e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
3407ef8f2327SMel Gorman 						pg_data_t *pgdat,
34080ae5e89cSYing Han 						unsigned long *nr_scanned)
34094e416953SBalbir Singh {
3410afaf07a6SJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
34114e416953SBalbir Singh 	struct scan_control sc = {
3412b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3413ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
34144e416953SBalbir Singh 		.may_writepage = !laptop_mode,
34154e416953SBalbir Singh 		.may_unmap = 1,
3416b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
34174e416953SBalbir Singh 		.may_swap = !noswap,
34184e416953SBalbir Singh 	};
34190ae5e89cSYing Han 
3420d2e5fb92SMichal Hocko 	WARN_ON_ONCE(!current->reclaim_state);
3421d2e5fb92SMichal Hocko 
34224e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
34234e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3424bdce6d9eSKOSAKI Motohiro 
34259e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
34263481c37fSYafang Shao 						      sc.gfp_mask);
3427bdce6d9eSKOSAKI Motohiro 
34284e416953SBalbir Singh 	/*
34294e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
34304e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3431a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
34324e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
34334e416953SBalbir Singh 	 * the priority and make it zero.
34344e416953SBalbir Singh 	 */
3435afaf07a6SJohannes Weiner 	shrink_lruvec(lruvec, &sc);
3436bdce6d9eSKOSAKI Motohiro 
3437bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3438bdce6d9eSKOSAKI Motohiro 
34390ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
34400308f7cfSYafang Shao 
34414e416953SBalbir Singh 	return sc.nr_reclaimed;
34424e416953SBalbir Singh }
34434e416953SBalbir Singh 
344472835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3445b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
34468c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3447b70a2a21SJohannes Weiner 					   bool may_swap)
344866e1707bSBalbir Singh {
3449bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3450499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
345166e1707bSBalbir Singh 	struct scan_control sc = {
3452b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
34537dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3454ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3455b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3456ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3457ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
345866e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3459a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3460b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3461a09ed5e0SYing Han 	};
3462fa40d1eeSShakeel Butt 	/*
3463fa40d1eeSShakeel Butt 	 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
3464fa40d1eeSShakeel Butt 	 * equal pressure on all the nodes. This is based on the assumption that
3465fa40d1eeSShakeel Butt 	 * the reclaim does not bail out early.
3466fa40d1eeSShakeel Butt 	 */
3467fa40d1eeSShakeel Butt 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
346866e1707bSBalbir Singh 
34691732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
34703481c37fSYafang Shao 	trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
3471499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3472eb414681SJohannes Weiner 
34733115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3474eb414681SJohannes Weiner 
3475499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3476bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
34771732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3478bdce6d9eSKOSAKI Motohiro 
3479bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
348066e1707bSBalbir Singh }
348166e1707bSBalbir Singh #endif
348266e1707bSBalbir Singh 
34831d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3484ef8f2327SMel Gorman 				struct scan_control *sc)
3485f16015fbSJohannes Weiner {
3486b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3487b91ac374SJohannes Weiner 	struct lruvec *lruvec;
3488b95a2f2dSJohannes Weiner 
3489b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3490b95a2f2dSJohannes Weiner 		return;
3491b95a2f2dSJohannes Weiner 
3492b91ac374SJohannes Weiner 	lruvec = mem_cgroup_lruvec(NULL, pgdat);
3493b91ac374SJohannes Weiner 	if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
3494b91ac374SJohannes Weiner 		return;
3495b91ac374SJohannes Weiner 
3496b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3497b95a2f2dSJohannes Weiner 	do {
3498b91ac374SJohannes Weiner 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
34991a93be0eSKonstantin Khlebnikov 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
35009e3b2f8cSKonstantin Khlebnikov 				   sc, LRU_ACTIVE_ANON);
3501b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3502b95a2f2dSJohannes Weiner 	} while (memcg);
3503f16015fbSJohannes Weiner }
3504f16015fbSJohannes Weiner 
350597a225e6SJoonsoo Kim static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
35061c30844dSMel Gorman {
35071c30844dSMel Gorman 	int i;
35081c30844dSMel Gorman 	struct zone *zone;
35091c30844dSMel Gorman 
35101c30844dSMel Gorman 	/*
35111c30844dSMel Gorman 	 * Check for watermark boosts top-down as the higher zones
35121c30844dSMel Gorman 	 * are more likely to be boosted. Both watermarks and boosts
35131eba09c1SRandy Dunlap 	 * should not be checked at the same time as reclaim would
35141c30844dSMel Gorman 	 * start prematurely when there is no boosting and a lower
35151c30844dSMel Gorman 	 * zone is balanced.
35161c30844dSMel Gorman 	 */
351797a225e6SJoonsoo Kim 	for (i = highest_zoneidx; i >= 0; i--) {
35181c30844dSMel Gorman 		zone = pgdat->node_zones + i;
35191c30844dSMel Gorman 		if (!managed_zone(zone))
35201c30844dSMel Gorman 			continue;
35211c30844dSMel Gorman 
35221c30844dSMel Gorman 		if (zone->watermark_boost)
35231c30844dSMel Gorman 			return true;
35241c30844dSMel Gorman 	}
35251c30844dSMel Gorman 
35261c30844dSMel Gorman 	return false;
35271c30844dSMel Gorman }
35281c30844dSMel Gorman 
3529e716f2ebSMel Gorman /*
3530e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
353197a225e6SJoonsoo Kim  * and highest_zoneidx
3532e716f2ebSMel Gorman  */
353397a225e6SJoonsoo Kim static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
353460cefed4SJohannes Weiner {
3535e716f2ebSMel Gorman 	int i;
3536e716f2ebSMel Gorman 	unsigned long mark = -1;
3537e716f2ebSMel Gorman 	struct zone *zone;
353860cefed4SJohannes Weiner 
35391c30844dSMel Gorman 	/*
35401c30844dSMel Gorman 	 * Check watermarks bottom-up as lower zones are more likely to
35411c30844dSMel Gorman 	 * meet watermarks.
35421c30844dSMel Gorman 	 */
354397a225e6SJoonsoo Kim 	for (i = 0; i <= highest_zoneidx; i++) {
3544e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
35456256c6b4SMel Gorman 
3546e716f2ebSMel Gorman 		if (!managed_zone(zone))
3547e716f2ebSMel Gorman 			continue;
3548e716f2ebSMel Gorman 
3549e716f2ebSMel Gorman 		mark = high_wmark_pages(zone);
355097a225e6SJoonsoo Kim 		if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
35516256c6b4SMel Gorman 			return true;
355260cefed4SJohannes Weiner 	}
355360cefed4SJohannes Weiner 
3554e716f2ebSMel Gorman 	/*
355597a225e6SJoonsoo Kim 	 * If a node has no populated zone within highest_zoneidx, it does not
3556e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3557e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3558e716f2ebSMel Gorman 	 */
3559e716f2ebSMel Gorman 	if (mark == -1)
3560e716f2ebSMel Gorman 		return true;
3561e716f2ebSMel Gorman 
3562e716f2ebSMel Gorman 	return false;
3563e716f2ebSMel Gorman }
3564e716f2ebSMel Gorman 
3565631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
3566631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
3567631b6e08SMel Gorman {
35681b05117dSJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
35691b05117dSJohannes Weiner 
35701b05117dSJohannes Weiner 	clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3571631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
3572631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3573631b6e08SMel Gorman }
3574631b6e08SMel Gorman 
35751741c877SMel Gorman /*
35765515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
35775515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
35785515061dSMel Gorman  *
35795515061dSMel Gorman  * Returns true if kswapd is ready to sleep
35805515061dSMel Gorman  */
358197a225e6SJoonsoo Kim static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
358297a225e6SJoonsoo Kim 				int highest_zoneidx)
3583f50de2d3SMel Gorman {
35845515061dSMel Gorman 	/*
35859e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3586c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
35879e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
35889e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
35899e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
35909e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
35919e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
35929e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
35939e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
35949e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
35959e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
35965515061dSMel Gorman 	 */
35979e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
35989e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3599f50de2d3SMel Gorman 
3600c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3601c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3602c73322d0SJohannes Weiner 		return true;
3603c73322d0SJohannes Weiner 
360497a225e6SJoonsoo Kim 	if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
3605631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
3606333b0a45SShantanu Goel 		return true;
36071d82de61SMel Gorman 	}
36081d82de61SMel Gorman 
3609333b0a45SShantanu Goel 	return false;
3610f50de2d3SMel Gorman }
3611f50de2d3SMel Gorman 
36121da177e4SLinus Torvalds /*
36131d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
36141d82de61SMel Gorman  * zone that is currently unbalanced.
3615b8e83b94SMel Gorman  *
3616b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3617283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3618283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
361975485363SMel Gorman  */
36201d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3621accf6242SVlastimil Babka 			       struct scan_control *sc)
362275485363SMel Gorman {
36231d82de61SMel Gorman 	struct zone *zone;
36241d82de61SMel Gorman 	int z;
362575485363SMel Gorman 
36261d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
36271d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3628970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
36291d82de61SMel Gorman 		zone = pgdat->node_zones + z;
36306aa303deSMel Gorman 		if (!managed_zone(zone))
36311d82de61SMel Gorman 			continue;
36327c954f6dSMel Gorman 
36331d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
36347c954f6dSMel Gorman 	}
36357c954f6dSMel Gorman 
36361d82de61SMel Gorman 	/*
36371d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
36381d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
36391d82de61SMel Gorman 	 */
3640970a39a3SMel Gorman 	shrink_node(pgdat, sc);
36411d82de61SMel Gorman 
36421d82de61SMel Gorman 	/*
36431d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
36441d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
36451d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
36461d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
36471d82de61SMel Gorman 	 * can direct reclaim/compact.
36481d82de61SMel Gorman 	 */
36499861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
36501d82de61SMel Gorman 		sc->order = 0;
36511d82de61SMel Gorman 
3652b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
365375485363SMel Gorman }
365475485363SMel Gorman 
365575485363SMel Gorman /*
36561d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
36571d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
36581d82de61SMel Gorman  * balanced.
36591da177e4SLinus Torvalds  *
36601d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
36611da177e4SLinus Torvalds  *
36621da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
366341858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
36648bb4e7a2SWei Yang  * found to have free_pages <= high_wmark_pages(zone), any page in that zone
36651d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
36661d82de61SMel Gorman  * balanced.
36671da177e4SLinus Torvalds  */
366897a225e6SJoonsoo Kim static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
36691da177e4SLinus Torvalds {
36701da177e4SLinus Torvalds 	int i;
36710608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
36720608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3673eb414681SJohannes Weiner 	unsigned long pflags;
36741c30844dSMel Gorman 	unsigned long nr_boost_reclaim;
36751c30844dSMel Gorman 	unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
36761c30844dSMel Gorman 	bool boosted;
36771d82de61SMel Gorman 	struct zone *zone;
3678179e9639SAndrew Morton 	struct scan_control sc = {
3679179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3680ee814fe2SJohannes Weiner 		.order = order,
3681a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3682179e9639SAndrew Morton 	};
368393781325SOmar Sandoval 
36841732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
3685eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
368693781325SOmar Sandoval 	__fs_reclaim_acquire();
368793781325SOmar Sandoval 
3688f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
36891da177e4SLinus Torvalds 
36901c30844dSMel Gorman 	/*
36911c30844dSMel Gorman 	 * Account for the reclaim boost. Note that the zone boost is left in
36921c30844dSMel Gorman 	 * place so that parallel allocations that are near the watermark will
36931c30844dSMel Gorman 	 * stall or direct reclaim until kswapd is finished.
36941c30844dSMel Gorman 	 */
36951c30844dSMel Gorman 	nr_boost_reclaim = 0;
369697a225e6SJoonsoo Kim 	for (i = 0; i <= highest_zoneidx; i++) {
36971c30844dSMel Gorman 		zone = pgdat->node_zones + i;
36981c30844dSMel Gorman 		if (!managed_zone(zone))
36991c30844dSMel Gorman 			continue;
37001c30844dSMel Gorman 
37011c30844dSMel Gorman 		nr_boost_reclaim += zone->watermark_boost;
37021c30844dSMel Gorman 		zone_boosts[i] = zone->watermark_boost;
37031c30844dSMel Gorman 	}
37041c30844dSMel Gorman 	boosted = nr_boost_reclaim;
37051c30844dSMel Gorman 
37061c30844dSMel Gorman restart:
37071c30844dSMel Gorman 	sc.priority = DEF_PRIORITY;
37089e3b2f8cSKonstantin Khlebnikov 	do {
3709c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
3710b8e83b94SMel Gorman 		bool raise_priority = true;
37111c30844dSMel Gorman 		bool balanced;
371293781325SOmar Sandoval 		bool ret;
3713b8e83b94SMel Gorman 
371497a225e6SJoonsoo Kim 		sc.reclaim_idx = highest_zoneidx;
37151da177e4SLinus Torvalds 
371686c79f6bSMel Gorman 		/*
371784c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
371884c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
371984c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
372084c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
372184c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
372284c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
372384c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
372484c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
372586c79f6bSMel Gorman 		 */
372686c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
372786c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
372886c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
37296aa303deSMel Gorman 				if (!managed_zone(zone))
373086c79f6bSMel Gorman 					continue;
373186c79f6bSMel Gorman 
3732970a39a3SMel Gorman 				sc.reclaim_idx = i;
373386c79f6bSMel Gorman 				break;
373486c79f6bSMel Gorman 			}
373586c79f6bSMel Gorman 		}
373686c79f6bSMel Gorman 
373786c79f6bSMel Gorman 		/*
37381c30844dSMel Gorman 		 * If the pgdat is imbalanced then ignore boosting and preserve
37391c30844dSMel Gorman 		 * the watermarks for a later time and restart. Note that the
37401c30844dSMel Gorman 		 * zone watermarks will be still reset at the end of balancing
37411c30844dSMel Gorman 		 * on the grounds that the normal reclaim should be enough to
37421c30844dSMel Gorman 		 * re-evaluate if boosting is required when kswapd next wakes.
374386c79f6bSMel Gorman 		 */
374497a225e6SJoonsoo Kim 		balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
37451c30844dSMel Gorman 		if (!balanced && nr_boost_reclaim) {
37461c30844dSMel Gorman 			nr_boost_reclaim = 0;
37471c30844dSMel Gorman 			goto restart;
37481c30844dSMel Gorman 		}
37491c30844dSMel Gorman 
37501c30844dSMel Gorman 		/*
37511c30844dSMel Gorman 		 * If boosting is not active then only reclaim if there are no
37521c30844dSMel Gorman 		 * eligible zones. Note that sc.reclaim_idx is not used as
37531c30844dSMel Gorman 		 * buffer_heads_over_limit may have adjusted it.
37541c30844dSMel Gorman 		 */
37551c30844dSMel Gorman 		if (!nr_boost_reclaim && balanced)
37561da177e4SLinus Torvalds 			goto out;
3757e1dbeda6SAndrew Morton 
37581c30844dSMel Gorman 		/* Limit the priority of boosting to avoid reclaim writeback */
37591c30844dSMel Gorman 		if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
37601c30844dSMel Gorman 			raise_priority = false;
37611c30844dSMel Gorman 
37621c30844dSMel Gorman 		/*
37631c30844dSMel Gorman 		 * Do not writeback or swap pages for boosted reclaim. The
37641c30844dSMel Gorman 		 * intent is to relieve pressure not issue sub-optimal IO
37651c30844dSMel Gorman 		 * from reclaim context. If no pages are reclaimed, the
37661c30844dSMel Gorman 		 * reclaim will be aborted.
37671c30844dSMel Gorman 		 */
37681c30844dSMel Gorman 		sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
37691c30844dSMel Gorman 		sc.may_swap = !nr_boost_reclaim;
37701c30844dSMel Gorman 
37711da177e4SLinus Torvalds 		/*
37721d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
37731d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
37741d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
37751d82de61SMel Gorman 		 * about consistent aging.
37761d82de61SMel Gorman 		 */
3777ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
37781d82de61SMel Gorman 
37791d82de61SMel Gorman 		/*
3780b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3781b7ea3c41SMel Gorman 		 * even in laptop mode.
3782b7ea3c41SMel Gorman 		 */
3783047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
3784b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3785b7ea3c41SMel Gorman 
37861d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
37871da177e4SLinus Torvalds 		sc.nr_scanned = 0;
37880608f43dSAndrew Morton 		nr_soft_scanned = 0;
3789ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
37901d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
37910608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
37920608f43dSAndrew Morton 
379332a4330dSRik van Riel 		/*
37941d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
37951d82de61SMel Gorman 		 * enough pages are already being scanned that that high
37961d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
379732a4330dSRik van Riel 		 */
3798970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3799b8e83b94SMel Gorman 			raise_priority = false;
3800d7868daeSMel Gorman 
38015515061dSMel Gorman 		/*
38025515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
38035515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
38045515061dSMel Gorman 		 * able to safely make forward progress. Wake them
38055515061dSMel Gorman 		 */
38065515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3807c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
3808cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
38095515061dSMel Gorman 
3810b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
381193781325SOmar Sandoval 		__fs_reclaim_release();
381293781325SOmar Sandoval 		ret = try_to_freeze();
381393781325SOmar Sandoval 		__fs_reclaim_acquire();
381493781325SOmar Sandoval 		if (ret || kthread_should_stop())
3815b8e83b94SMel Gorman 			break;
3816b8e83b94SMel Gorman 
3817b8e83b94SMel Gorman 		/*
3818b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3819b8e83b94SMel Gorman 		 * progress in reclaiming pages
3820b8e83b94SMel Gorman 		 */
3821c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
38221c30844dSMel Gorman 		nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
38231c30844dSMel Gorman 
38241c30844dSMel Gorman 		/*
38251c30844dSMel Gorman 		 * If reclaim made no progress for a boost, stop reclaim as
38261c30844dSMel Gorman 		 * IO cannot be queued and it could be an infinite loop in
38271c30844dSMel Gorman 		 * extreme circumstances.
38281c30844dSMel Gorman 		 */
38291c30844dSMel Gorman 		if (nr_boost_reclaim && !nr_reclaimed)
38301c30844dSMel Gorman 			break;
38311c30844dSMel Gorman 
3832c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
3833b8e83b94SMel Gorman 			sc.priority--;
38341d82de61SMel Gorman 	} while (sc.priority >= 1);
38351da177e4SLinus Torvalds 
3836c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
3837c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
3838c73322d0SJohannes Weiner 
3839b8e83b94SMel Gorman out:
38401c30844dSMel Gorman 	/* If reclaim was boosted, account for the reclaim done in this pass */
38411c30844dSMel Gorman 	if (boosted) {
38421c30844dSMel Gorman 		unsigned long flags;
38431c30844dSMel Gorman 
384497a225e6SJoonsoo Kim 		for (i = 0; i <= highest_zoneidx; i++) {
38451c30844dSMel Gorman 			if (!zone_boosts[i])
38461c30844dSMel Gorman 				continue;
38471c30844dSMel Gorman 
38481c30844dSMel Gorman 			/* Increments are under the zone lock */
38491c30844dSMel Gorman 			zone = pgdat->node_zones + i;
38501c30844dSMel Gorman 			spin_lock_irqsave(&zone->lock, flags);
38511c30844dSMel Gorman 			zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
38521c30844dSMel Gorman 			spin_unlock_irqrestore(&zone->lock, flags);
38531c30844dSMel Gorman 		}
38541c30844dSMel Gorman 
38551c30844dSMel Gorman 		/*
38561c30844dSMel Gorman 		 * As there is now likely space, wakeup kcompact to defragment
38571c30844dSMel Gorman 		 * pageblocks.
38581c30844dSMel Gorman 		 */
385997a225e6SJoonsoo Kim 		wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
38601c30844dSMel Gorman 	}
38611c30844dSMel Gorman 
38622a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
386393781325SOmar Sandoval 	__fs_reclaim_release();
3864eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
38651732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3866e5ca8071SYafang Shao 
38670abdee2bSMel Gorman 	/*
38681d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
38691d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
38701d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
38711d82de61SMel Gorman 	 * remain at the higher level.
38720abdee2bSMel Gorman 	 */
38731d82de61SMel Gorman 	return sc.order;
38741da177e4SLinus Torvalds }
38751da177e4SLinus Torvalds 
3876e716f2ebSMel Gorman /*
387797a225e6SJoonsoo Kim  * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
387897a225e6SJoonsoo Kim  * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
387997a225e6SJoonsoo Kim  * not a valid index then either kswapd runs for first time or kswapd couldn't
388097a225e6SJoonsoo Kim  * sleep after previous reclaim attempt (node is still unbalanced). In that
388197a225e6SJoonsoo Kim  * case return the zone index of the previous kswapd reclaim cycle.
3882e716f2ebSMel Gorman  */
388397a225e6SJoonsoo Kim static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
388497a225e6SJoonsoo Kim 					   enum zone_type prev_highest_zoneidx)
3885e716f2ebSMel Gorman {
388697a225e6SJoonsoo Kim 	enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
38875644e1fbSQian Cai 
388897a225e6SJoonsoo Kim 	return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
3889e716f2ebSMel Gorman }
3890e716f2ebSMel Gorman 
389138087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
389297a225e6SJoonsoo Kim 				unsigned int highest_zoneidx)
3893f0bc0a60SKOSAKI Motohiro {
3894f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3895f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3896f0bc0a60SKOSAKI Motohiro 
3897f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3898f0bc0a60SKOSAKI Motohiro 		return;
3899f0bc0a60SKOSAKI Motohiro 
3900f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3901f0bc0a60SKOSAKI Motohiro 
3902333b0a45SShantanu Goel 	/*
3903333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
3904333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
3905333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
3906333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
3907333b0a45SShantanu Goel 	 * succeed.
3908333b0a45SShantanu Goel 	 */
390997a225e6SJoonsoo Kim 	if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
3910fd901c95SVlastimil Babka 		/*
3911fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3912fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3913fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3914fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3915fd901c95SVlastimil Babka 		 */
3916fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3917fd901c95SVlastimil Babka 
3918fd901c95SVlastimil Babka 		/*
3919fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3920fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3921fd901c95SVlastimil Babka 		 */
392297a225e6SJoonsoo Kim 		wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
3923fd901c95SVlastimil Babka 
3924f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
392538087d9bSMel Gorman 
392638087d9bSMel Gorman 		/*
392797a225e6SJoonsoo Kim 		 * If woken prematurely then reset kswapd_highest_zoneidx and
392838087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
392938087d9bSMel Gorman 		 * the previous request that slept prematurely.
393038087d9bSMel Gorman 		 */
393138087d9bSMel Gorman 		if (remaining) {
393297a225e6SJoonsoo Kim 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
393397a225e6SJoonsoo Kim 					kswapd_highest_zoneidx(pgdat,
393497a225e6SJoonsoo Kim 							highest_zoneidx));
39355644e1fbSQian Cai 
39365644e1fbSQian Cai 			if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
39375644e1fbSQian Cai 				WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
393838087d9bSMel Gorman 		}
393938087d9bSMel Gorman 
3940f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3941f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3942f0bc0a60SKOSAKI Motohiro 	}
3943f0bc0a60SKOSAKI Motohiro 
3944f0bc0a60SKOSAKI Motohiro 	/*
3945f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3946f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3947f0bc0a60SKOSAKI Motohiro 	 */
3948d9f21d42SMel Gorman 	if (!remaining &&
394997a225e6SJoonsoo Kim 	    prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
3950f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3951f0bc0a60SKOSAKI Motohiro 
3952f0bc0a60SKOSAKI Motohiro 		/*
3953f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3954f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3955f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3956f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3957f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3958f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3959f0bc0a60SKOSAKI Motohiro 		 */
3960f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
39611c7e7f6cSAaditya Kumar 
39621c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3963f0bc0a60SKOSAKI Motohiro 			schedule();
39641c7e7f6cSAaditya Kumar 
3965f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3966f0bc0a60SKOSAKI Motohiro 	} else {
3967f0bc0a60SKOSAKI Motohiro 		if (remaining)
3968f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3969f0bc0a60SKOSAKI Motohiro 		else
3970f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3971f0bc0a60SKOSAKI Motohiro 	}
3972f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3973f0bc0a60SKOSAKI Motohiro }
3974f0bc0a60SKOSAKI Motohiro 
39751da177e4SLinus Torvalds /*
39761da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
39771da177e4SLinus Torvalds  * from the init process.
39781da177e4SLinus Torvalds  *
39791da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
39801da177e4SLinus Torvalds  * free memory available even if there is no other activity
39811da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
39821da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
39831da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
39841da177e4SLinus Torvalds  *
39851da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
39861da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
39871da177e4SLinus Torvalds  */
39881da177e4SLinus Torvalds static int kswapd(void *p)
39891da177e4SLinus Torvalds {
3990e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
399197a225e6SJoonsoo Kim 	unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
39921da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
39931da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3994a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
39951da177e4SLinus Torvalds 
3996174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3997c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
39981da177e4SLinus Torvalds 
39991da177e4SLinus Torvalds 	/*
40001da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
40011da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
40021da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
40031da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
40041da177e4SLinus Torvalds 	 *
40051da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
40061da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
40071da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
40081da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
40091da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
40101da177e4SLinus Torvalds 	 */
4011930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
401283144186SRafael J. Wysocki 	set_freezable();
40131da177e4SLinus Torvalds 
40145644e1fbSQian Cai 	WRITE_ONCE(pgdat->kswapd_order, 0);
401597a225e6SJoonsoo Kim 	WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
40161da177e4SLinus Torvalds 	for ( ; ; ) {
40176f6313d4SJeff Liu 		bool ret;
40183e1d1d28SChristoph Lameter 
40195644e1fbSQian Cai 		alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
402097a225e6SJoonsoo Kim 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
402197a225e6SJoonsoo Kim 							highest_zoneidx);
4022e716f2ebSMel Gorman 
402338087d9bSMel Gorman kswapd_try_sleep:
402438087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
402597a225e6SJoonsoo Kim 					highest_zoneidx);
4026215ddd66SMel Gorman 
402797a225e6SJoonsoo Kim 		/* Read the new order and highest_zoneidx */
40282b47a24cSLukas Bulwahn 		alloc_order = READ_ONCE(pgdat->kswapd_order);
402997a225e6SJoonsoo Kim 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
403097a225e6SJoonsoo Kim 							highest_zoneidx);
40315644e1fbSQian Cai 		WRITE_ONCE(pgdat->kswapd_order, 0);
403297a225e6SJoonsoo Kim 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
40331da177e4SLinus Torvalds 
40348fe23e05SDavid Rientjes 		ret = try_to_freeze();
40358fe23e05SDavid Rientjes 		if (kthread_should_stop())
40368fe23e05SDavid Rientjes 			break;
40378fe23e05SDavid Rientjes 
40388fe23e05SDavid Rientjes 		/*
40398fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
40408fe23e05SDavid Rientjes 		 * after returning from the refrigerator
4041b1296cc4SRafael J. Wysocki 		 */
404238087d9bSMel Gorman 		if (ret)
404338087d9bSMel Gorman 			continue;
40441d82de61SMel Gorman 
404538087d9bSMel Gorman 		/*
404638087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
404738087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
404838087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
404938087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
405038087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
405138087d9bSMel Gorman 		 * request (alloc_order).
405238087d9bSMel Gorman 		 */
405397a225e6SJoonsoo Kim 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
4054e5146b12SMel Gorman 						alloc_order);
405597a225e6SJoonsoo Kim 		reclaim_order = balance_pgdat(pgdat, alloc_order,
405697a225e6SJoonsoo Kim 						highest_zoneidx);
405738087d9bSMel Gorman 		if (reclaim_order < alloc_order)
405838087d9bSMel Gorman 			goto kswapd_try_sleep;
405933906bc5SMel Gorman 	}
4060b0a8cc58STakamori Yamaguchi 
406171abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
406271abdc15SJohannes Weiner 
40631da177e4SLinus Torvalds 	return 0;
40641da177e4SLinus Torvalds }
40651da177e4SLinus Torvalds 
40661da177e4SLinus Torvalds /*
40675ecd9d40SDavid Rientjes  * A zone is low on free memory or too fragmented for high-order memory.  If
40685ecd9d40SDavid Rientjes  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
40695ecd9d40SDavid Rientjes  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
40705ecd9d40SDavid Rientjes  * has failed or is not needed, still wake up kcompactd if only compaction is
40715ecd9d40SDavid Rientjes  * needed.
40721da177e4SLinus Torvalds  */
40735ecd9d40SDavid Rientjes void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
407497a225e6SJoonsoo Kim 		   enum zone_type highest_zoneidx)
40751da177e4SLinus Torvalds {
40761da177e4SLinus Torvalds 	pg_data_t *pgdat;
40775644e1fbSQian Cai 	enum zone_type curr_idx;
40781da177e4SLinus Torvalds 
40796aa303deSMel Gorman 	if (!managed_zone(zone))
40801da177e4SLinus Torvalds 		return;
40811da177e4SLinus Torvalds 
40825ecd9d40SDavid Rientjes 	if (!cpuset_zone_allowed(zone, gfp_flags))
40831da177e4SLinus Torvalds 		return;
4084dffcac2cSShakeel Butt 
40855644e1fbSQian Cai 	pgdat = zone->zone_pgdat;
408697a225e6SJoonsoo Kim 	curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
40875644e1fbSQian Cai 
408897a225e6SJoonsoo Kim 	if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
408997a225e6SJoonsoo Kim 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
40905644e1fbSQian Cai 
40915644e1fbSQian Cai 	if (READ_ONCE(pgdat->kswapd_order) < order)
40925644e1fbSQian Cai 		WRITE_ONCE(pgdat->kswapd_order, order);
40935644e1fbSQian Cai 
40948d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
40951da177e4SLinus Torvalds 		return;
4096e1a55637SMel Gorman 
40975ecd9d40SDavid Rientjes 	/* Hopeless node, leave it to direct reclaim if possible */
40985ecd9d40SDavid Rientjes 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
409997a225e6SJoonsoo Kim 	    (pgdat_balanced(pgdat, order, highest_zoneidx) &&
410097a225e6SJoonsoo Kim 	     !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
41015ecd9d40SDavid Rientjes 		/*
41025ecd9d40SDavid Rientjes 		 * There may be plenty of free memory available, but it's too
41035ecd9d40SDavid Rientjes 		 * fragmented for high-order allocations.  Wake up kcompactd
41045ecd9d40SDavid Rientjes 		 * and rely on compaction_suitable() to determine if it's
41055ecd9d40SDavid Rientjes 		 * needed.  If it fails, it will defer subsequent attempts to
41065ecd9d40SDavid Rientjes 		 * ratelimit its work.
41075ecd9d40SDavid Rientjes 		 */
41085ecd9d40SDavid Rientjes 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
410997a225e6SJoonsoo Kim 			wakeup_kcompactd(pgdat, order, highest_zoneidx);
4110c73322d0SJohannes Weiner 		return;
41115ecd9d40SDavid Rientjes 	}
4112c73322d0SJohannes Weiner 
411397a225e6SJoonsoo Kim 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
41145ecd9d40SDavid Rientjes 				      gfp_flags);
41158d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
41161da177e4SLinus Torvalds }
41171da177e4SLinus Torvalds 
4118c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
41191da177e4SLinus Torvalds /*
41207b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
4121d6277db4SRafael J. Wysocki  * freed pages.
4122d6277db4SRafael J. Wysocki  *
4123d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
4124d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
4125d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
41261da177e4SLinus Torvalds  */
41277b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
41281da177e4SLinus Torvalds {
4129d6277db4SRafael J. Wysocki 	struct scan_control sc = {
41307b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
4131ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
4132b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
41339e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
4134ee814fe2SJohannes Weiner 		.may_writepage = 1,
4135ee814fe2SJohannes Weiner 		.may_unmap = 1,
4136ee814fe2SJohannes Weiner 		.may_swap = 1,
4137ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
41381da177e4SLinus Torvalds 	};
41397b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
41407b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
4141499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
41421da177e4SLinus Torvalds 
4143d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
414493781325SOmar Sandoval 	noreclaim_flag = memalloc_noreclaim_save();
41451732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
4146d6277db4SRafael J. Wysocki 
41473115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4148d6277db4SRafael J. Wysocki 
41491732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
4150499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
415193781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4152d6277db4SRafael J. Wysocki 
41537b51755cSKOSAKI Motohiro 	return nr_reclaimed;
41541da177e4SLinus Torvalds }
4155c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
41561da177e4SLinus Torvalds 
41573218ae14SYasunori Goto /*
41583218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
41593218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
41603218ae14SYasunori Goto  */
41613218ae14SYasunori Goto int kswapd_run(int nid)
41623218ae14SYasunori Goto {
41633218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
41643218ae14SYasunori Goto 	int ret = 0;
41653218ae14SYasunori Goto 
41663218ae14SYasunori Goto 	if (pgdat->kswapd)
41673218ae14SYasunori Goto 		return 0;
41683218ae14SYasunori Goto 
41693218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
41703218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
41713218ae14SYasunori Goto 		/* failure at boot is fatal */
4172c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
4173d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
4174d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
4175d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
41763218ae14SYasunori Goto 	}
41773218ae14SYasunori Goto 	return ret;
41783218ae14SYasunori Goto }
41793218ae14SYasunori Goto 
41808fe23e05SDavid Rientjes /*
4181d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
4182bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
41838fe23e05SDavid Rientjes  */
41848fe23e05SDavid Rientjes void kswapd_stop(int nid)
41858fe23e05SDavid Rientjes {
41868fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
41878fe23e05SDavid Rientjes 
4188d8adde17SJiang Liu 	if (kswapd) {
41898fe23e05SDavid Rientjes 		kthread_stop(kswapd);
4190d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
4191d8adde17SJiang Liu 	}
41928fe23e05SDavid Rientjes }
41938fe23e05SDavid Rientjes 
41941da177e4SLinus Torvalds static int __init kswapd_init(void)
41951da177e4SLinus Torvalds {
41966b700b5bSWei Yang 	int nid;
419769e05944SAndrew Morton 
41981da177e4SLinus Torvalds 	swap_setup();
419948fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
42003218ae14SYasunori Goto  		kswapd_run(nid);
42011da177e4SLinus Torvalds 	return 0;
42021da177e4SLinus Torvalds }
42031da177e4SLinus Torvalds 
42041da177e4SLinus Torvalds module_init(kswapd_init)
42059eeff239SChristoph Lameter 
42069eeff239SChristoph Lameter #ifdef CONFIG_NUMA
42079eeff239SChristoph Lameter /*
4208a5f5f91dSMel Gorman  * Node reclaim mode
42099eeff239SChristoph Lameter  *
4210a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
42119eeff239SChristoph Lameter  * the watermarks.
42129eeff239SChristoph Lameter  */
4213a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
42149eeff239SChristoph Lameter 
421551998364SDave Hansen /*
4216a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
4217a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
4218a92f7126SChristoph Lameter  * a zone.
4219a92f7126SChristoph Lameter  */
4220a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
4221a92f7126SChristoph Lameter 
42229eeff239SChristoph Lameter /*
4223a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
42249614634fSChristoph Lameter  * occur.
42259614634fSChristoph Lameter  */
42269614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
42279614634fSChristoph Lameter 
42289614634fSChristoph Lameter /*
42290ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
42300ff38490SChristoph Lameter  * slab reclaim needs to occur.
42310ff38490SChristoph Lameter  */
42320ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
42330ff38490SChristoph Lameter 
423411fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
423590afa5deSMel Gorman {
423611fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
423711fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
423811fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
423990afa5deSMel Gorman 
424090afa5deSMel Gorman 	/*
424190afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
424290afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
424390afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
424490afa5deSMel Gorman 	 */
424590afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
424690afa5deSMel Gorman }
424790afa5deSMel Gorman 
424890afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4249a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
425090afa5deSMel Gorman {
4251d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
4252d031a157SAlexandru Moise 	unsigned long delta = 0;
425390afa5deSMel Gorman 
425490afa5deSMel Gorman 	/*
425595bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
425690afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
425711fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
425890afa5deSMel Gorman 	 * a better estimate
425990afa5deSMel Gorman 	 */
4260a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
4261a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
426290afa5deSMel Gorman 	else
4263a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
426490afa5deSMel Gorman 
426590afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
4266a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
4267a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
426890afa5deSMel Gorman 
426990afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
427090afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
427190afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
427290afa5deSMel Gorman 
427390afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
427490afa5deSMel Gorman }
427590afa5deSMel Gorman 
42760ff38490SChristoph Lameter /*
4277a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
42789eeff239SChristoph Lameter  */
4279a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
42809eeff239SChristoph Lameter {
42817fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
428269e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
42839eeff239SChristoph Lameter 	struct task_struct *p = current;
4284499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
4285179e9639SAndrew Morton 	struct scan_control sc = {
428662b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4287f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
4288bd2f6199SJohannes Weiner 		.order = order,
4289a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
4290a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4291a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4292ee814fe2SJohannes Weiner 		.may_swap = 1,
4293f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
4294179e9639SAndrew Morton 	};
42959eeff239SChristoph Lameter 
4296132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4297132bb8cfSYafang Shao 					   sc.gfp_mask);
4298132bb8cfSYafang Shao 
42999eeff239SChristoph Lameter 	cond_resched();
430093781325SOmar Sandoval 	fs_reclaim_acquire(sc.gfp_mask);
4301d4f7796eSChristoph Lameter 	/*
430295bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4303d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
430495bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
4305d4f7796eSChristoph Lameter 	 */
4306499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
4307499118e9SVlastimil Babka 	p->flags |= PF_SWAPWRITE;
43081732d2b0SAndrew Morton 	set_task_reclaim_state(p, &sc.reclaim_state);
4309c84db23cSChristoph Lameter 
4310a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
4311a92f7126SChristoph Lameter 		/*
4312894befecSAndrey Ryabinin 		 * Free memory by calling shrink node with increasing
43130ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
4314a92f7126SChristoph Lameter 		 */
4315a92f7126SChristoph Lameter 		do {
4316970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
43179e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
43180ff38490SChristoph Lameter 	}
4319a92f7126SChristoph Lameter 
43201732d2b0SAndrew Morton 	set_task_reclaim_state(p, NULL);
4321499118e9SVlastimil Babka 	current->flags &= ~PF_SWAPWRITE;
4322499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
432393781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4324132bb8cfSYafang Shao 
4325132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4326132bb8cfSYafang Shao 
4327a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
43289eeff239SChristoph Lameter }
4329179e9639SAndrew Morton 
4330a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4331179e9639SAndrew Morton {
4332d773ed6bSDavid Rientjes 	int ret;
4333179e9639SAndrew Morton 
4334179e9639SAndrew Morton 	/*
4335a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
43360ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
433734aa1330SChristoph Lameter 	 *
43389614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
43399614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
4340a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
4341a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
43429614634fSChristoph Lameter 	 * unmapped file backed pages.
4343179e9639SAndrew Morton 	 */
4344a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4345d42f3245SRoman Gushchin 	    node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
4346d42f3245SRoman Gushchin 	    pgdat->min_slab_pages)
4347a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
4348179e9639SAndrew Morton 
4349179e9639SAndrew Morton 	/*
4350d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
4351179e9639SAndrew Morton 	 */
4352d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4353a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4354179e9639SAndrew Morton 
4355179e9639SAndrew Morton 	/*
4356a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
4357179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
4358179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
4359179e9639SAndrew Morton 	 * as wide as possible.
4360179e9639SAndrew Morton 	 */
4361a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4362a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4363d773ed6bSDavid Rientjes 
4364a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4365a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4366fa5e084eSMel Gorman 
4367a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
4368a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4369d773ed6bSDavid Rientjes 
437024cf7251SMel Gorman 	if (!ret)
437124cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
437224cf7251SMel Gorman 
4373d773ed6bSDavid Rientjes 	return ret;
4374179e9639SAndrew Morton }
43759eeff239SChristoph Lameter #endif
4376894bc310SLee Schermerhorn 
437789e004eaSLee Schermerhorn /**
437864e3d12fSKuo-Hsin Yang  * check_move_unevictable_pages - check pages for evictability and move to
437964e3d12fSKuo-Hsin Yang  * appropriate zone lru list
438064e3d12fSKuo-Hsin Yang  * @pvec: pagevec with lru pages to check
438189e004eaSLee Schermerhorn  *
438264e3d12fSKuo-Hsin Yang  * Checks pages for evictability, if an evictable page is in the unevictable
438364e3d12fSKuo-Hsin Yang  * lru list, moves it to the appropriate evictable lru list. This function
438464e3d12fSKuo-Hsin Yang  * should be only used for lru pages.
438589e004eaSLee Schermerhorn  */
438664e3d12fSKuo-Hsin Yang void check_move_unevictable_pages(struct pagevec *pvec)
438789e004eaSLee Schermerhorn {
43886168d0daSAlex Shi 	struct lruvec *lruvec = NULL;
438924513264SHugh Dickins 	int pgscanned = 0;
439024513264SHugh Dickins 	int pgrescued = 0;
439189e004eaSLee Schermerhorn 	int i;
439289e004eaSLee Schermerhorn 
439364e3d12fSKuo-Hsin Yang 	for (i = 0; i < pvec->nr; i++) {
439464e3d12fSKuo-Hsin Yang 		struct page *page = pvec->pages[i];
43958d8869caSHugh Dickins 		int nr_pages;
439689e004eaSLee Schermerhorn 
43978d8869caSHugh Dickins 		if (PageTransTail(page))
43988d8869caSHugh Dickins 			continue;
43998d8869caSHugh Dickins 
44008d8869caSHugh Dickins 		nr_pages = thp_nr_pages(page);
44018d8869caSHugh Dickins 		pgscanned += nr_pages;
44028d8869caSHugh Dickins 
4403d25b5bd8SAlex Shi 		/* block memcg migration during page moving between lru */
4404d25b5bd8SAlex Shi 		if (!TestClearPageLRU(page))
4405d25b5bd8SAlex Shi 			continue;
4406d25b5bd8SAlex Shi 
44072a5e4e34SAlexander Duyck 		lruvec = relock_page_lruvec_irq(page, lruvec);
4408d25b5bd8SAlex Shi 		if (page_evictable(page) && PageUnevictable(page)) {
440946ae6b2cSYu Zhao 			del_page_from_lru_list(page, lruvec);
441024513264SHugh Dickins 			ClearPageUnevictable(page);
44113a9c9788SYu Zhao 			add_page_to_lru_list(page, lruvec);
44128d8869caSHugh Dickins 			pgrescued += nr_pages;
441389e004eaSLee Schermerhorn 		}
4414d25b5bd8SAlex Shi 		SetPageLRU(page);
441589e004eaSLee Schermerhorn 	}
441624513264SHugh Dickins 
44176168d0daSAlex Shi 	if (lruvec) {
441824513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
441924513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
44206168d0daSAlex Shi 		unlock_page_lruvec_irq(lruvec);
4421d25b5bd8SAlex Shi 	} else if (pgscanned) {
4422d25b5bd8SAlex Shi 		count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
442324513264SHugh Dickins 	}
442485046579SHugh Dickins }
442564e3d12fSKuo-Hsin Yang EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
4426