xref: /openbmc/linux/mm/vmscan.c (revision 72673e861dd032ccaff533c0d9bb705d508017f7)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  *  Swap reorganised 29.12.95, Stephen Tweedie.
61da177e4SLinus Torvalds  *  kswapd added: 7.1.96  sct
71da177e4SLinus Torvalds  *  Removed kswapd_ctl limits, and swap out as many pages as needed
81da177e4SLinus Torvalds  *  to bring the system back to freepages.high: 2.4.97, Rik van Riel.
91da177e4SLinus Torvalds  *  Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
101da177e4SLinus Torvalds  *  Multiqueue VM started 5.8.00, Rik van Riel.
111da177e4SLinus Torvalds  */
121da177e4SLinus Torvalds 
13b1de0d13SMitchel Humpherys #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14b1de0d13SMitchel Humpherys 
151da177e4SLinus Torvalds #include <linux/mm.h>
165b3cc15aSIngo Molnar #include <linux/sched/mm.h>
171da177e4SLinus Torvalds #include <linux/module.h>
185a0e3ad6STejun Heo #include <linux/gfp.h>
191da177e4SLinus Torvalds #include <linux/kernel_stat.h>
201da177e4SLinus Torvalds #include <linux/swap.h>
211da177e4SLinus Torvalds #include <linux/pagemap.h>
221da177e4SLinus Torvalds #include <linux/init.h>
231da177e4SLinus Torvalds #include <linux/highmem.h>
2470ddf637SAnton Vorontsov #include <linux/vmpressure.h>
25e129b5c2SAndrew Morton #include <linux/vmstat.h>
261da177e4SLinus Torvalds #include <linux/file.h>
271da177e4SLinus Torvalds #include <linux/writeback.h>
281da177e4SLinus Torvalds #include <linux/blkdev.h>
291da177e4SLinus Torvalds #include <linux/buffer_head.h>	/* for try_to_release_page(),
301da177e4SLinus Torvalds 					buffer_heads_over_limit */
311da177e4SLinus Torvalds #include <linux/mm_inline.h>
321da177e4SLinus Torvalds #include <linux/backing-dev.h>
331da177e4SLinus Torvalds #include <linux/rmap.h>
341da177e4SLinus Torvalds #include <linux/topology.h>
351da177e4SLinus Torvalds #include <linux/cpu.h>
361da177e4SLinus Torvalds #include <linux/cpuset.h>
373e7d3449SMel Gorman #include <linux/compaction.h>
381da177e4SLinus Torvalds #include <linux/notifier.h>
391da177e4SLinus Torvalds #include <linux/rwsem.h>
40248a0301SRafael J. Wysocki #include <linux/delay.h>
413218ae14SYasunori Goto #include <linux/kthread.h>
427dfb7103SNigel Cunningham #include <linux/freezer.h>
4366e1707bSBalbir Singh #include <linux/memcontrol.h>
44873b4771SKeika Kobayashi #include <linux/delayacct.h>
45af936a16SLee Schermerhorn #include <linux/sysctl.h>
46929bea7cSKOSAKI Motohiro #include <linux/oom.h>
4764e3d12fSKuo-Hsin Yang #include <linux/pagevec.h>
48268bb0ceSLinus Torvalds #include <linux/prefetch.h>
49b1de0d13SMitchel Humpherys #include <linux/printk.h>
50f9fe48beSRoss Zwisler #include <linux/dax.h>
51eb414681SJohannes Weiner #include <linux/psi.h>
521da177e4SLinus Torvalds 
531da177e4SLinus Torvalds #include <asm/tlbflush.h>
541da177e4SLinus Torvalds #include <asm/div64.h>
551da177e4SLinus Torvalds 
561da177e4SLinus Torvalds #include <linux/swapops.h>
57117aad1eSRafael Aquini #include <linux/balloon_compaction.h>
581da177e4SLinus Torvalds 
590f8053a5SNick Piggin #include "internal.h"
600f8053a5SNick Piggin 
6133906bc5SMel Gorman #define CREATE_TRACE_POINTS
6233906bc5SMel Gorman #include <trace/events/vmscan.h>
6333906bc5SMel Gorman 
641da177e4SLinus Torvalds struct scan_control {
6522fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6622fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
6722fba335SKOSAKI Motohiro 
68ee814fe2SJohannes Weiner 	/*
69ee814fe2SJohannes Weiner 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
70ee814fe2SJohannes Weiner 	 * are scanned.
71ee814fe2SJohannes Weiner 	 */
72ee814fe2SJohannes Weiner 	nodemask_t	*nodemask;
739e3b2f8cSKonstantin Khlebnikov 
745f53e762SKOSAKI Motohiro 	/*
75f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
76f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
77f16015fbSJohannes Weiner 	 */
78f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
7966e1707bSBalbir Singh 
807cf111bcSJohannes Weiner 	/*
817cf111bcSJohannes Weiner 	 * Scan pressure balancing between anon and file LRUs
827cf111bcSJohannes Weiner 	 */
837cf111bcSJohannes Weiner 	unsigned long	anon_cost;
847cf111bcSJohannes Weiner 	unsigned long	file_cost;
857cf111bcSJohannes Weiner 
86b91ac374SJohannes Weiner 	/* Can active pages be deactivated as part of reclaim? */
87b91ac374SJohannes Weiner #define DEACTIVATE_ANON 1
88b91ac374SJohannes Weiner #define DEACTIVATE_FILE 2
89b91ac374SJohannes Weiner 	unsigned int may_deactivate:2;
90b91ac374SJohannes Weiner 	unsigned int force_deactivate:1;
91b91ac374SJohannes Weiner 	unsigned int skipped_deactivate:1;
92b91ac374SJohannes Weiner 
931276ad68SJohannes Weiner 	/* Writepage batching in laptop mode; RECLAIM_WRITE */
94ee814fe2SJohannes Weiner 	unsigned int may_writepage:1;
95ee814fe2SJohannes Weiner 
96ee814fe2SJohannes Weiner 	/* Can mapped pages be reclaimed? */
97ee814fe2SJohannes Weiner 	unsigned int may_unmap:1;
98ee814fe2SJohannes Weiner 
99ee814fe2SJohannes Weiner 	/* Can pages be swapped as part of reclaim? */
100ee814fe2SJohannes Weiner 	unsigned int may_swap:1;
101ee814fe2SJohannes Weiner 
102d6622f63SYisheng Xie 	/*
103d6622f63SYisheng Xie 	 * Cgroups are not reclaimed below their configured memory.low,
104d6622f63SYisheng Xie 	 * unless we threaten to OOM. If any cgroups are skipped due to
105d6622f63SYisheng Xie 	 * memory.low and nothing was reclaimed, go back for memory.low.
106d6622f63SYisheng Xie 	 */
107d6622f63SYisheng Xie 	unsigned int memcg_low_reclaim:1;
108d6622f63SYisheng Xie 	unsigned int memcg_low_skipped:1;
109241994edSJohannes Weiner 
110ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
111ee814fe2SJohannes Weiner 
112ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
113ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
114ee814fe2SJohannes Weiner 
115b91ac374SJohannes Weiner 	/* There is easily reclaimable cold cache in the current node */
116b91ac374SJohannes Weiner 	unsigned int cache_trim_mode:1;
117b91ac374SJohannes Weiner 
11853138ceaSJohannes Weiner 	/* The file pages on the current node are dangerously low */
11953138ceaSJohannes Weiner 	unsigned int file_is_tiny:1;
12053138ceaSJohannes Weiner 
121bb451fdfSGreg Thelen 	/* Allocation order */
122bb451fdfSGreg Thelen 	s8 order;
123bb451fdfSGreg Thelen 
124bb451fdfSGreg Thelen 	/* Scan (total_size >> priority) pages at once */
125bb451fdfSGreg Thelen 	s8 priority;
126bb451fdfSGreg Thelen 
127bb451fdfSGreg Thelen 	/* The highest zone to isolate pages for reclaim from */
128bb451fdfSGreg Thelen 	s8 reclaim_idx;
129bb451fdfSGreg Thelen 
130bb451fdfSGreg Thelen 	/* This context's GFP mask */
131bb451fdfSGreg Thelen 	gfp_t gfp_mask;
132bb451fdfSGreg Thelen 
133ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
134ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
135ee814fe2SJohannes Weiner 
136ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
137ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
138d108c772SAndrey Ryabinin 
139d108c772SAndrey Ryabinin 	struct {
140d108c772SAndrey Ryabinin 		unsigned int dirty;
141d108c772SAndrey Ryabinin 		unsigned int unqueued_dirty;
142d108c772SAndrey Ryabinin 		unsigned int congested;
143d108c772SAndrey Ryabinin 		unsigned int writeback;
144d108c772SAndrey Ryabinin 		unsigned int immediate;
145d108c772SAndrey Ryabinin 		unsigned int file_taken;
146d108c772SAndrey Ryabinin 		unsigned int taken;
147d108c772SAndrey Ryabinin 	} nr;
148e5ca8071SYafang Shao 
149e5ca8071SYafang Shao 	/* for recording the reclaimed slab by now */
150e5ca8071SYafang Shao 	struct reclaim_state reclaim_state;
1511da177e4SLinus Torvalds };
1521da177e4SLinus Torvalds 
1531da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1541da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1551da177e4SLinus Torvalds 	do {								\
1561da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1571da177e4SLinus Torvalds 			struct page *prev;				\
1581da177e4SLinus Torvalds 									\
1591da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1601da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1611da177e4SLinus Torvalds 		}							\
1621da177e4SLinus Torvalds 	} while (0)
1631da177e4SLinus Torvalds #else
1641da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1651da177e4SLinus Torvalds #endif
1661da177e4SLinus Torvalds 
1671da177e4SLinus Torvalds /*
168c843966cSJohannes Weiner  * From 0 .. 200.  Higher means more swappy.
1691da177e4SLinus Torvalds  */
1701da177e4SLinus Torvalds int vm_swappiness = 60;
1711da177e4SLinus Torvalds 
1720a432dcbSYang Shi static void set_task_reclaim_state(struct task_struct *task,
1730a432dcbSYang Shi 				   struct reclaim_state *rs)
1740a432dcbSYang Shi {
1750a432dcbSYang Shi 	/* Check for an overwrite */
1760a432dcbSYang Shi 	WARN_ON_ONCE(rs && task->reclaim_state);
1770a432dcbSYang Shi 
1780a432dcbSYang Shi 	/* Check for the nulling of an already-nulled member */
1790a432dcbSYang Shi 	WARN_ON_ONCE(!rs && !task->reclaim_state);
1800a432dcbSYang Shi 
1810a432dcbSYang Shi 	task->reclaim_state = rs;
1820a432dcbSYang Shi }
1830a432dcbSYang Shi 
1841da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1851da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1861da177e4SLinus Torvalds 
1870a432dcbSYang Shi #ifdef CONFIG_MEMCG
188a2fb1261SYang Shi static int shrinker_nr_max;
1892bfd3637SYang Shi 
190a2fb1261SYang Shi static inline int shrinker_map_size(int nr_items)
191a2fb1261SYang Shi {
192a2fb1261SYang Shi 	return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
193a2fb1261SYang Shi }
1942bfd3637SYang Shi 
1952bfd3637SYang Shi static int expand_one_shrinker_map(struct mem_cgroup *memcg,
1962bfd3637SYang Shi 				   int size, int old_size)
1972bfd3637SYang Shi {
1982bfd3637SYang Shi 	struct memcg_shrinker_map *new, *old;
1992bfd3637SYang Shi 	struct mem_cgroup_per_node *pn;
2002bfd3637SYang Shi 	int nid;
2012bfd3637SYang Shi 
2022bfd3637SYang Shi 	for_each_node(nid) {
2032bfd3637SYang Shi 		pn = memcg->nodeinfo[nid];
2042bfd3637SYang Shi 		old = rcu_dereference_protected(pn->shrinker_map, true);
2052bfd3637SYang Shi 		/* Not yet online memcg */
2062bfd3637SYang Shi 		if (!old)
2072bfd3637SYang Shi 			return 0;
2082bfd3637SYang Shi 
2092bfd3637SYang Shi 		new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
2102bfd3637SYang Shi 		if (!new)
2112bfd3637SYang Shi 			return -ENOMEM;
2122bfd3637SYang Shi 
2132bfd3637SYang Shi 		/* Set all old bits, clear all new bits */
2142bfd3637SYang Shi 		memset(new->map, (int)0xff, old_size);
2152bfd3637SYang Shi 		memset((void *)new->map + old_size, 0, size - old_size);
2162bfd3637SYang Shi 
2172bfd3637SYang Shi 		rcu_assign_pointer(pn->shrinker_map, new);
218*72673e86SYang Shi 		kvfree_rcu(old, rcu);
2192bfd3637SYang Shi 	}
2202bfd3637SYang Shi 
2212bfd3637SYang Shi 	return 0;
2222bfd3637SYang Shi }
2232bfd3637SYang Shi 
2242bfd3637SYang Shi void free_shrinker_maps(struct mem_cgroup *memcg)
2252bfd3637SYang Shi {
2262bfd3637SYang Shi 	struct mem_cgroup_per_node *pn;
2272bfd3637SYang Shi 	struct memcg_shrinker_map *map;
2282bfd3637SYang Shi 	int nid;
2292bfd3637SYang Shi 
2302bfd3637SYang Shi 	if (mem_cgroup_is_root(memcg))
2312bfd3637SYang Shi 		return;
2322bfd3637SYang Shi 
2332bfd3637SYang Shi 	for_each_node(nid) {
2342bfd3637SYang Shi 		pn = memcg->nodeinfo[nid];
2352bfd3637SYang Shi 		map = rcu_dereference_protected(pn->shrinker_map, true);
2362bfd3637SYang Shi 		kvfree(map);
2372bfd3637SYang Shi 		rcu_assign_pointer(pn->shrinker_map, NULL);
2382bfd3637SYang Shi 	}
2392bfd3637SYang Shi }
2402bfd3637SYang Shi 
2412bfd3637SYang Shi int alloc_shrinker_maps(struct mem_cgroup *memcg)
2422bfd3637SYang Shi {
2432bfd3637SYang Shi 	struct memcg_shrinker_map *map;
2442bfd3637SYang Shi 	int nid, size, ret = 0;
2452bfd3637SYang Shi 
2462bfd3637SYang Shi 	if (mem_cgroup_is_root(memcg))
2472bfd3637SYang Shi 		return 0;
2482bfd3637SYang Shi 
249d27cf2aaSYang Shi 	down_write(&shrinker_rwsem);
250a2fb1261SYang Shi 	size = shrinker_map_size(shrinker_nr_max);
2512bfd3637SYang Shi 	for_each_node(nid) {
2522bfd3637SYang Shi 		map = kvzalloc_node(sizeof(*map) + size, GFP_KERNEL, nid);
2532bfd3637SYang Shi 		if (!map) {
2542bfd3637SYang Shi 			free_shrinker_maps(memcg);
2552bfd3637SYang Shi 			ret = -ENOMEM;
2562bfd3637SYang Shi 			break;
2572bfd3637SYang Shi 		}
2582bfd3637SYang Shi 		rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, map);
2592bfd3637SYang Shi 	}
260d27cf2aaSYang Shi 	up_write(&shrinker_rwsem);
2612bfd3637SYang Shi 
2622bfd3637SYang Shi 	return ret;
2632bfd3637SYang Shi }
2642bfd3637SYang Shi 
2652bfd3637SYang Shi static int expand_shrinker_maps(int new_id)
2662bfd3637SYang Shi {
2672bfd3637SYang Shi 	int size, old_size, ret = 0;
268a2fb1261SYang Shi 	int new_nr_max = new_id + 1;
2692bfd3637SYang Shi 	struct mem_cgroup *memcg;
2702bfd3637SYang Shi 
271a2fb1261SYang Shi 	size = shrinker_map_size(new_nr_max);
272a2fb1261SYang Shi 	old_size = shrinker_map_size(shrinker_nr_max);
2732bfd3637SYang Shi 	if (size <= old_size)
274a2fb1261SYang Shi 		goto out;
2752bfd3637SYang Shi 
2762bfd3637SYang Shi 	if (!root_mem_cgroup)
277d27cf2aaSYang Shi 		goto out;
278d27cf2aaSYang Shi 
279d27cf2aaSYang Shi 	lockdep_assert_held(&shrinker_rwsem);
2802bfd3637SYang Shi 
2812bfd3637SYang Shi 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
2822bfd3637SYang Shi 	do {
2832bfd3637SYang Shi 		if (mem_cgroup_is_root(memcg))
2842bfd3637SYang Shi 			continue;
2852bfd3637SYang Shi 		ret = expand_one_shrinker_map(memcg, size, old_size);
2862bfd3637SYang Shi 		if (ret) {
2872bfd3637SYang Shi 			mem_cgroup_iter_break(NULL, memcg);
288d27cf2aaSYang Shi 			goto out;
2892bfd3637SYang Shi 		}
2902bfd3637SYang Shi 	} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
291d27cf2aaSYang Shi out:
2922bfd3637SYang Shi 	if (!ret)
293a2fb1261SYang Shi 		shrinker_nr_max = new_nr_max;
294d27cf2aaSYang Shi 
2952bfd3637SYang Shi 	return ret;
2962bfd3637SYang Shi }
2972bfd3637SYang Shi 
2982bfd3637SYang Shi void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
2992bfd3637SYang Shi {
3002bfd3637SYang Shi 	if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
3012bfd3637SYang Shi 		struct memcg_shrinker_map *map;
3022bfd3637SYang Shi 
3032bfd3637SYang Shi 		rcu_read_lock();
3042bfd3637SYang Shi 		map = rcu_dereference(memcg->nodeinfo[nid]->shrinker_map);
3052bfd3637SYang Shi 		/* Pairs with smp mb in shrink_slab() */
3062bfd3637SYang Shi 		smp_mb__before_atomic();
3072bfd3637SYang Shi 		set_bit(shrinker_id, map->map);
3082bfd3637SYang Shi 		rcu_read_unlock();
3092bfd3637SYang Shi 	}
3102bfd3637SYang Shi }
3112bfd3637SYang Shi 
3127e010df5SKirill Tkhai /*
3137e010df5SKirill Tkhai  * We allow subsystems to populate their shrinker-related
3147e010df5SKirill Tkhai  * LRU lists before register_shrinker_prepared() is called
3157e010df5SKirill Tkhai  * for the shrinker, since we don't want to impose
3167e010df5SKirill Tkhai  * restrictions on their internal registration order.
3177e010df5SKirill Tkhai  * In this case shrink_slab_memcg() may find corresponding
3187e010df5SKirill Tkhai  * bit is set in the shrinkers map.
3197e010df5SKirill Tkhai  *
3207e010df5SKirill Tkhai  * This value is used by the function to detect registering
3217e010df5SKirill Tkhai  * shrinkers and to skip do_shrink_slab() calls for them.
3227e010df5SKirill Tkhai  */
3237e010df5SKirill Tkhai #define SHRINKER_REGISTERING ((struct shrinker *)~0UL)
3247e010df5SKirill Tkhai 
325b4c2b231SKirill Tkhai static DEFINE_IDR(shrinker_idr);
326b4c2b231SKirill Tkhai 
327b4c2b231SKirill Tkhai static int prealloc_memcg_shrinker(struct shrinker *shrinker)
328b4c2b231SKirill Tkhai {
329b4c2b231SKirill Tkhai 	int id, ret = -ENOMEM;
330b4c2b231SKirill Tkhai 
331b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
332b4c2b231SKirill Tkhai 	/* This may call shrinker, so it must use down_read_trylock() */
3337e010df5SKirill Tkhai 	id = idr_alloc(&shrinker_idr, SHRINKER_REGISTERING, 0, 0, GFP_KERNEL);
334b4c2b231SKirill Tkhai 	if (id < 0)
335b4c2b231SKirill Tkhai 		goto unlock;
336b4c2b231SKirill Tkhai 
3370a4465d3SKirill Tkhai 	if (id >= shrinker_nr_max) {
3382bfd3637SYang Shi 		if (expand_shrinker_maps(id)) {
3390a4465d3SKirill Tkhai 			idr_remove(&shrinker_idr, id);
3400a4465d3SKirill Tkhai 			goto unlock;
3410a4465d3SKirill Tkhai 		}
3420a4465d3SKirill Tkhai 	}
343b4c2b231SKirill Tkhai 	shrinker->id = id;
344b4c2b231SKirill Tkhai 	ret = 0;
345b4c2b231SKirill Tkhai unlock:
346b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
347b4c2b231SKirill Tkhai 	return ret;
348b4c2b231SKirill Tkhai }
349b4c2b231SKirill Tkhai 
350b4c2b231SKirill Tkhai static void unregister_memcg_shrinker(struct shrinker *shrinker)
351b4c2b231SKirill Tkhai {
352b4c2b231SKirill Tkhai 	int id = shrinker->id;
353b4c2b231SKirill Tkhai 
354b4c2b231SKirill Tkhai 	BUG_ON(id < 0);
355b4c2b231SKirill Tkhai 
356b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
357b4c2b231SKirill Tkhai 	idr_remove(&shrinker_idr, id);
358b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
359b4c2b231SKirill Tkhai }
360b4c2b231SKirill Tkhai 
361b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
36289b5fae5SJohannes Weiner {
363b5ead35eSJohannes Weiner 	return sc->target_mem_cgroup;
36489b5fae5SJohannes Weiner }
36597c9341fSTejun Heo 
36697c9341fSTejun Heo /**
367b5ead35eSJohannes Weiner  * writeback_throttling_sane - is the usual dirty throttling mechanism available?
36897c9341fSTejun Heo  * @sc: scan_control in question
36997c9341fSTejun Heo  *
37097c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
37197c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
37297c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
37397c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
37497c9341fSTejun Heo  * allocation and configurability.
37597c9341fSTejun Heo  *
37697c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
37797c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
37897c9341fSTejun Heo  */
379b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
38097c9341fSTejun Heo {
381b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
38297c9341fSTejun Heo 		return true;
38397c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
38469234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
38597c9341fSTejun Heo 		return true;
38697c9341fSTejun Heo #endif
38797c9341fSTejun Heo 	return false;
38897c9341fSTejun Heo }
38991a45470SKAMEZAWA Hiroyuki #else
3900a432dcbSYang Shi static int prealloc_memcg_shrinker(struct shrinker *shrinker)
3910a432dcbSYang Shi {
3920a432dcbSYang Shi 	return 0;
3930a432dcbSYang Shi }
3940a432dcbSYang Shi 
3950a432dcbSYang Shi static void unregister_memcg_shrinker(struct shrinker *shrinker)
3960a432dcbSYang Shi {
3970a432dcbSYang Shi }
3980a432dcbSYang Shi 
399b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
40089b5fae5SJohannes Weiner {
401b5ead35eSJohannes Weiner 	return false;
40289b5fae5SJohannes Weiner }
40397c9341fSTejun Heo 
404b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
40597c9341fSTejun Heo {
40697c9341fSTejun Heo 	return true;
40797c9341fSTejun Heo }
40891a45470SKAMEZAWA Hiroyuki #endif
40991a45470SKAMEZAWA Hiroyuki 
4105a1c84b4SMel Gorman /*
4115a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
4125a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
4135a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
4145a1c84b4SMel Gorman  */
4155a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
4165a1c84b4SMel Gorman {
4175a1c84b4SMel Gorman 	unsigned long nr;
4185a1c84b4SMel Gorman 
4195a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
4205a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
4215a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
4225a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
4235a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
4245a1c84b4SMel Gorman 
4255a1c84b4SMel Gorman 	return nr;
4265a1c84b4SMel Gorman }
4275a1c84b4SMel Gorman 
428fd538803SMichal Hocko /**
429fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
430fd538803SMichal Hocko  * @lruvec: lru vector
431fd538803SMichal Hocko  * @lru: lru to use
432fd538803SMichal Hocko  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
433fd538803SMichal Hocko  */
4342091339dSYu Zhao static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
4352091339dSYu Zhao 				     int zone_idx)
436c9f299d9SKOSAKI Motohiro {
437de3b0150SJohannes Weiner 	unsigned long size = 0;
438fd538803SMichal Hocko 	int zid;
439a3d8e054SKOSAKI Motohiro 
440de3b0150SJohannes Weiner 	for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
441fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
442fd538803SMichal Hocko 
443fd538803SMichal Hocko 		if (!managed_zone(zone))
444fd538803SMichal Hocko 			continue;
445fd538803SMichal Hocko 
446fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
447de3b0150SJohannes Weiner 			size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
448fd538803SMichal Hocko 		else
449de3b0150SJohannes Weiner 			size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
450c9f299d9SKOSAKI Motohiro 	}
451de3b0150SJohannes Weiner 	return size;
452b4536f0cSMichal Hocko }
453b4536f0cSMichal Hocko 
4541da177e4SLinus Torvalds /*
4551d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
4561da177e4SLinus Torvalds  */
4578e04944fSTetsuo Handa int prealloc_shrinker(struct shrinker *shrinker)
4581da177e4SLinus Torvalds {
459b9726c26SAlexey Dobriyan 	unsigned int size = sizeof(*shrinker->nr_deferred);
4601d3d4437SGlauber Costa 
4611d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
4621d3d4437SGlauber Costa 		size *= nr_node_ids;
4631d3d4437SGlauber Costa 
4641d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
4651d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
4661d3d4437SGlauber Costa 		return -ENOMEM;
467b4c2b231SKirill Tkhai 
468b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
469b4c2b231SKirill Tkhai 		if (prealloc_memcg_shrinker(shrinker))
470b4c2b231SKirill Tkhai 			goto free_deferred;
471b4c2b231SKirill Tkhai 	}
472b4c2b231SKirill Tkhai 
4738e04944fSTetsuo Handa 	return 0;
474b4c2b231SKirill Tkhai 
475b4c2b231SKirill Tkhai free_deferred:
476b4c2b231SKirill Tkhai 	kfree(shrinker->nr_deferred);
477b4c2b231SKirill Tkhai 	shrinker->nr_deferred = NULL;
478b4c2b231SKirill Tkhai 	return -ENOMEM;
4798e04944fSTetsuo Handa }
4801d3d4437SGlauber Costa 
4818e04944fSTetsuo Handa void free_prealloced_shrinker(struct shrinker *shrinker)
4828e04944fSTetsuo Handa {
483b4c2b231SKirill Tkhai 	if (!shrinker->nr_deferred)
484b4c2b231SKirill Tkhai 		return;
485b4c2b231SKirill Tkhai 
486b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
487b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
488b4c2b231SKirill Tkhai 
4898e04944fSTetsuo Handa 	kfree(shrinker->nr_deferred);
4908e04944fSTetsuo Handa 	shrinker->nr_deferred = NULL;
4918e04944fSTetsuo Handa }
4928e04944fSTetsuo Handa 
4938e04944fSTetsuo Handa void register_shrinker_prepared(struct shrinker *shrinker)
4948e04944fSTetsuo Handa {
4951da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
4961da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
49742a9a53bSYang Shi #ifdef CONFIG_MEMCG
4988df4a44cSKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
4997e010df5SKirill Tkhai 		idr_replace(&shrinker_idr, shrinker, shrinker->id);
5007e010df5SKirill Tkhai #endif
5011da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
5028e04944fSTetsuo Handa }
5038e04944fSTetsuo Handa 
5048e04944fSTetsuo Handa int register_shrinker(struct shrinker *shrinker)
5058e04944fSTetsuo Handa {
5068e04944fSTetsuo Handa 	int err = prealloc_shrinker(shrinker);
5078e04944fSTetsuo Handa 
5088e04944fSTetsuo Handa 	if (err)
5098e04944fSTetsuo Handa 		return err;
5108e04944fSTetsuo Handa 	register_shrinker_prepared(shrinker);
5111d3d4437SGlauber Costa 	return 0;
5121da177e4SLinus Torvalds }
5138e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
5141da177e4SLinus Torvalds 
5151da177e4SLinus Torvalds /*
5161da177e4SLinus Torvalds  * Remove one
5171da177e4SLinus Torvalds  */
5188e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
5191da177e4SLinus Torvalds {
520bb422a73STetsuo Handa 	if (!shrinker->nr_deferred)
521bb422a73STetsuo Handa 		return;
522b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
523b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
5241da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
5251da177e4SLinus Torvalds 	list_del(&shrinker->list);
5261da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
527ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
528bb422a73STetsuo Handa 	shrinker->nr_deferred = NULL;
5291da177e4SLinus Torvalds }
5308e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
5311da177e4SLinus Torvalds 
5321da177e4SLinus Torvalds #define SHRINK_BATCH 128
5331d3d4437SGlauber Costa 
534cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
5359092c71bSJosef Bacik 				    struct shrinker *shrinker, int priority)
5361da177e4SLinus Torvalds {
53724f7c6b9SDave Chinner 	unsigned long freed = 0;
5381da177e4SLinus Torvalds 	unsigned long long delta;
539635697c6SKonstantin Khlebnikov 	long total_scan;
540d5bc5fd3SVladimir Davydov 	long freeable;
541acf92b48SDave Chinner 	long nr;
542acf92b48SDave Chinner 	long new_nr;
5431d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
544e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
545e9299f50SDave Chinner 					  : SHRINK_BATCH;
5465f33a080SShaohua Li 	long scanned = 0, next_deferred;
5471da177e4SLinus Torvalds 
548ac7fb3adSKirill Tkhai 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
549ac7fb3adSKirill Tkhai 		nid = 0;
550ac7fb3adSKirill Tkhai 
551d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
5529b996468SKirill Tkhai 	if (freeable == 0 || freeable == SHRINK_EMPTY)
5539b996468SKirill Tkhai 		return freeable;
554635697c6SKonstantin Khlebnikov 
555acf92b48SDave Chinner 	/*
556acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
557acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
558acf92b48SDave Chinner 	 * don't also do this scanning work.
559acf92b48SDave Chinner 	 */
5601d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
561acf92b48SDave Chinner 
562acf92b48SDave Chinner 	total_scan = nr;
5634b85afbdSJohannes Weiner 	if (shrinker->seeks) {
5649092c71bSJosef Bacik 		delta = freeable >> priority;
5659092c71bSJosef Bacik 		delta *= 4;
5669092c71bSJosef Bacik 		do_div(delta, shrinker->seeks);
5674b85afbdSJohannes Weiner 	} else {
5684b85afbdSJohannes Weiner 		/*
5694b85afbdSJohannes Weiner 		 * These objects don't require any IO to create. Trim
5704b85afbdSJohannes Weiner 		 * them aggressively under memory pressure to keep
5714b85afbdSJohannes Weiner 		 * them from causing refetches in the IO caches.
5724b85afbdSJohannes Weiner 		 */
5734b85afbdSJohannes Weiner 		delta = freeable / 2;
5744b85afbdSJohannes Weiner 	}
575172b06c3SRoman Gushchin 
576acf92b48SDave Chinner 	total_scan += delta;
577acf92b48SDave Chinner 	if (total_scan < 0) {
578d75f773cSSakari Ailus 		pr_err("shrink_slab: %pS negative objects to delete nr=%ld\n",
579a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
580d5bc5fd3SVladimir Davydov 		total_scan = freeable;
5815f33a080SShaohua Li 		next_deferred = nr;
5825f33a080SShaohua Li 	} else
5835f33a080SShaohua Li 		next_deferred = total_scan;
584ea164d73SAndrea Arcangeli 
585ea164d73SAndrea Arcangeli 	/*
5863567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
5873567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
5883567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
5893567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
5903567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
591d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
5923567b59aSDave Chinner 	 * memory.
5933567b59aSDave Chinner 	 *
5943567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
5953567b59aSDave Chinner 	 * a large delta change is calculated directly.
5963567b59aSDave Chinner 	 */
597d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
598d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
5993567b59aSDave Chinner 
6003567b59aSDave Chinner 	/*
601ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
602ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
603ea164d73SAndrea Arcangeli 	 * freeable entries.
604ea164d73SAndrea Arcangeli 	 */
605d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
606d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
6071da177e4SLinus Torvalds 
60824f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
6099092c71bSJosef Bacik 				   freeable, delta, total_scan, priority);
61009576073SDave Chinner 
6110b1fb40aSVladimir Davydov 	/*
6120b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
6130b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
6140b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
6150b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
6160b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
6170b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
6180b1fb40aSVladimir Davydov 	 * batch_size.
6190b1fb40aSVladimir Davydov 	 *
6200b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
6210b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
622d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
6230b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
6240b1fb40aSVladimir Davydov 	 * possible.
6250b1fb40aSVladimir Davydov 	 */
6260b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
627d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
62824f7c6b9SDave Chinner 		unsigned long ret;
6290b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
6301da177e4SLinus Torvalds 
6310b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
632d460acb5SChris Wilson 		shrinkctl->nr_scanned = nr_to_scan;
63324f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
63424f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
6351da177e4SLinus Torvalds 			break;
63624f7c6b9SDave Chinner 		freed += ret;
63724f7c6b9SDave Chinner 
638d460acb5SChris Wilson 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
639d460acb5SChris Wilson 		total_scan -= shrinkctl->nr_scanned;
640d460acb5SChris Wilson 		scanned += shrinkctl->nr_scanned;
6411da177e4SLinus Torvalds 
6421da177e4SLinus Torvalds 		cond_resched();
6431da177e4SLinus Torvalds 	}
6441da177e4SLinus Torvalds 
6455f33a080SShaohua Li 	if (next_deferred >= scanned)
6465f33a080SShaohua Li 		next_deferred -= scanned;
6475f33a080SShaohua Li 	else
6485f33a080SShaohua Li 		next_deferred = 0;
649acf92b48SDave Chinner 	/*
650acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
651acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
652acf92b48SDave Chinner 	 * scan, there is no need to do an update.
653acf92b48SDave Chinner 	 */
6545f33a080SShaohua Li 	if (next_deferred > 0)
6555f33a080SShaohua Li 		new_nr = atomic_long_add_return(next_deferred,
6561d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
65783aeeadaSKonstantin Khlebnikov 	else
6581d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
659acf92b48SDave Chinner 
6608efb4b59SYang Shi 	trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
6611d3d4437SGlauber Costa 	return freed;
6621d3d4437SGlauber Costa }
6631d3d4437SGlauber Costa 
6640a432dcbSYang Shi #ifdef CONFIG_MEMCG
665b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
666b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
667b0dedc49SKirill Tkhai {
668b0dedc49SKirill Tkhai 	struct memcg_shrinker_map *map;
669b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
670b8e57efaSKirill Tkhai 	int i;
671b0dedc49SKirill Tkhai 
6720a432dcbSYang Shi 	if (!mem_cgroup_online(memcg))
673b0dedc49SKirill Tkhai 		return 0;
674b0dedc49SKirill Tkhai 
675b0dedc49SKirill Tkhai 	if (!down_read_trylock(&shrinker_rwsem))
676b0dedc49SKirill Tkhai 		return 0;
677b0dedc49SKirill Tkhai 
678b0dedc49SKirill Tkhai 	map = rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_map,
679b0dedc49SKirill Tkhai 					true);
680b0dedc49SKirill Tkhai 	if (unlikely(!map))
681b0dedc49SKirill Tkhai 		goto unlock;
682b0dedc49SKirill Tkhai 
683b0dedc49SKirill Tkhai 	for_each_set_bit(i, map->map, shrinker_nr_max) {
684b0dedc49SKirill Tkhai 		struct shrink_control sc = {
685b0dedc49SKirill Tkhai 			.gfp_mask = gfp_mask,
686b0dedc49SKirill Tkhai 			.nid = nid,
687b0dedc49SKirill Tkhai 			.memcg = memcg,
688b0dedc49SKirill Tkhai 		};
689b0dedc49SKirill Tkhai 		struct shrinker *shrinker;
690b0dedc49SKirill Tkhai 
691b0dedc49SKirill Tkhai 		shrinker = idr_find(&shrinker_idr, i);
6927e010df5SKirill Tkhai 		if (unlikely(!shrinker || shrinker == SHRINKER_REGISTERING)) {
6937e010df5SKirill Tkhai 			if (!shrinker)
694b0dedc49SKirill Tkhai 				clear_bit(i, map->map);
695b0dedc49SKirill Tkhai 			continue;
696b0dedc49SKirill Tkhai 		}
697b0dedc49SKirill Tkhai 
6980a432dcbSYang Shi 		/* Call non-slab shrinkers even though kmem is disabled */
6990a432dcbSYang Shi 		if (!memcg_kmem_enabled() &&
7000a432dcbSYang Shi 		    !(shrinker->flags & SHRINKER_NONSLAB))
7010a432dcbSYang Shi 			continue;
7020a432dcbSYang Shi 
703b0dedc49SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
704f90280d6SKirill Tkhai 		if (ret == SHRINK_EMPTY) {
705f90280d6SKirill Tkhai 			clear_bit(i, map->map);
706f90280d6SKirill Tkhai 			/*
707f90280d6SKirill Tkhai 			 * After the shrinker reported that it had no objects to
708f90280d6SKirill Tkhai 			 * free, but before we cleared the corresponding bit in
709f90280d6SKirill Tkhai 			 * the memcg shrinker map, a new object might have been
710f90280d6SKirill Tkhai 			 * added. To make sure, we have the bit set in this
711f90280d6SKirill Tkhai 			 * case, we invoke the shrinker one more time and reset
712f90280d6SKirill Tkhai 			 * the bit if it reports that it is not empty anymore.
713f90280d6SKirill Tkhai 			 * The memory barrier here pairs with the barrier in
7142bfd3637SYang Shi 			 * set_shrinker_bit():
715f90280d6SKirill Tkhai 			 *
716f90280d6SKirill Tkhai 			 * list_lru_add()     shrink_slab_memcg()
717f90280d6SKirill Tkhai 			 *   list_add_tail()    clear_bit()
718f90280d6SKirill Tkhai 			 *   <MB>               <MB>
719f90280d6SKirill Tkhai 			 *   set_bit()          do_shrink_slab()
720f90280d6SKirill Tkhai 			 */
721f90280d6SKirill Tkhai 			smp_mb__after_atomic();
722f90280d6SKirill Tkhai 			ret = do_shrink_slab(&sc, shrinker, priority);
7239b996468SKirill Tkhai 			if (ret == SHRINK_EMPTY)
7249b996468SKirill Tkhai 				ret = 0;
725f90280d6SKirill Tkhai 			else
7262bfd3637SYang Shi 				set_shrinker_bit(memcg, nid, i);
727f90280d6SKirill Tkhai 		}
728b0dedc49SKirill Tkhai 		freed += ret;
729b0dedc49SKirill Tkhai 
730b0dedc49SKirill Tkhai 		if (rwsem_is_contended(&shrinker_rwsem)) {
731b0dedc49SKirill Tkhai 			freed = freed ? : 1;
732b0dedc49SKirill Tkhai 			break;
733b0dedc49SKirill Tkhai 		}
734b0dedc49SKirill Tkhai 	}
735b0dedc49SKirill Tkhai unlock:
736b0dedc49SKirill Tkhai 	up_read(&shrinker_rwsem);
737b0dedc49SKirill Tkhai 	return freed;
738b0dedc49SKirill Tkhai }
7390a432dcbSYang Shi #else /* CONFIG_MEMCG */
740b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
741b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
742b0dedc49SKirill Tkhai {
743b0dedc49SKirill Tkhai 	return 0;
744b0dedc49SKirill Tkhai }
7450a432dcbSYang Shi #endif /* CONFIG_MEMCG */
746b0dedc49SKirill Tkhai 
7476b4f7799SJohannes Weiner /**
748cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
7496b4f7799SJohannes Weiner  * @gfp_mask: allocation context
7506b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
751cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
7529092c71bSJosef Bacik  * @priority: the reclaim priority
7531d3d4437SGlauber Costa  *
7546b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
7551d3d4437SGlauber Costa  *
7566b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
7576b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
7581d3d4437SGlauber Costa  *
759aeed1d32SVladimir Davydov  * @memcg specifies the memory cgroup to target. Unaware shrinkers
760aeed1d32SVladimir Davydov  * are called only if it is the root cgroup.
761cb731d6cSVladimir Davydov  *
7629092c71bSJosef Bacik  * @priority is sc->priority, we take the number of objects and >> by priority
7639092c71bSJosef Bacik  * in order to get the scan target.
7641d3d4437SGlauber Costa  *
7656b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
7661d3d4437SGlauber Costa  */
767cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
768cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
7699092c71bSJosef Bacik 				 int priority)
7701d3d4437SGlauber Costa {
771b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
7721d3d4437SGlauber Costa 	struct shrinker *shrinker;
7731d3d4437SGlauber Costa 
774fa1e512fSYang Shi 	/*
775fa1e512fSYang Shi 	 * The root memcg might be allocated even though memcg is disabled
776fa1e512fSYang Shi 	 * via "cgroup_disable=memory" boot parameter.  This could make
777fa1e512fSYang Shi 	 * mem_cgroup_is_root() return false, then just run memcg slab
778fa1e512fSYang Shi 	 * shrink, but skip global shrink.  This may result in premature
779fa1e512fSYang Shi 	 * oom.
780fa1e512fSYang Shi 	 */
781fa1e512fSYang Shi 	if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
782b0dedc49SKirill Tkhai 		return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
783cb731d6cSVladimir Davydov 
784e830c63aSTetsuo Handa 	if (!down_read_trylock(&shrinker_rwsem))
7851d3d4437SGlauber Costa 		goto out;
7861d3d4437SGlauber Costa 
7871d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
7886b4f7799SJohannes Weiner 		struct shrink_control sc = {
7896b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
7906b4f7799SJohannes Weiner 			.nid = nid,
791cb731d6cSVladimir Davydov 			.memcg = memcg,
7926b4f7799SJohannes Weiner 		};
7936b4f7799SJohannes Weiner 
7949b996468SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
7959b996468SKirill Tkhai 		if (ret == SHRINK_EMPTY)
7969b996468SKirill Tkhai 			ret = 0;
7979b996468SKirill Tkhai 		freed += ret;
798e496612cSMinchan Kim 		/*
799e496612cSMinchan Kim 		 * Bail out if someone want to register a new shrinker to
80055b65a57SEthon Paul 		 * prevent the registration from being stalled for long periods
801e496612cSMinchan Kim 		 * by parallel ongoing shrinking.
802e496612cSMinchan Kim 		 */
803e496612cSMinchan Kim 		if (rwsem_is_contended(&shrinker_rwsem)) {
804e496612cSMinchan Kim 			freed = freed ? : 1;
805e496612cSMinchan Kim 			break;
806e496612cSMinchan Kim 		}
807ec97097bSVladimir Davydov 	}
8081d3d4437SGlauber Costa 
8091da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
810f06590bdSMinchan Kim out:
811f06590bdSMinchan Kim 	cond_resched();
81224f7c6b9SDave Chinner 	return freed;
8131da177e4SLinus Torvalds }
8141da177e4SLinus Torvalds 
815cb731d6cSVladimir Davydov void drop_slab_node(int nid)
816cb731d6cSVladimir Davydov {
817cb731d6cSVladimir Davydov 	unsigned long freed;
818cb731d6cSVladimir Davydov 
819cb731d6cSVladimir Davydov 	do {
820cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
821cb731d6cSVladimir Davydov 
822069c411dSChunxin Zang 		if (fatal_signal_pending(current))
823069c411dSChunxin Zang 			return;
824069c411dSChunxin Zang 
825cb731d6cSVladimir Davydov 		freed = 0;
826aeed1d32SVladimir Davydov 		memcg = mem_cgroup_iter(NULL, NULL, NULL);
827cb731d6cSVladimir Davydov 		do {
8289092c71bSJosef Bacik 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
829cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
830cb731d6cSVladimir Davydov 	} while (freed > 10);
831cb731d6cSVladimir Davydov }
832cb731d6cSVladimir Davydov 
833cb731d6cSVladimir Davydov void drop_slab(void)
834cb731d6cSVladimir Davydov {
835cb731d6cSVladimir Davydov 	int nid;
836cb731d6cSVladimir Davydov 
837cb731d6cSVladimir Davydov 	for_each_online_node(nid)
838cb731d6cSVladimir Davydov 		drop_slab_node(nid);
839cb731d6cSVladimir Davydov }
840cb731d6cSVladimir Davydov 
8411da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
8421da177e4SLinus Torvalds {
843ceddc3a5SJohannes Weiner 	/*
844ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
84567891fffSMatthew Wilcox 	 * that isolated the page, the page cache and optional buffer
84667891fffSMatthew Wilcox 	 * heads at page->private.
847ceddc3a5SJohannes Weiner 	 */
8483efe62e4SMatthew Wilcox (Oracle) 	int page_cache_pins = thp_nr_pages(page);
84967891fffSMatthew Wilcox 	return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
8501da177e4SLinus Torvalds }
8511da177e4SLinus Torvalds 
852cb16556dSYang Shi static int may_write_to_inode(struct inode *inode)
8531da177e4SLinus Torvalds {
854930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
8551da177e4SLinus Torvalds 		return 1;
856703c2708STejun Heo 	if (!inode_write_congested(inode))
8571da177e4SLinus Torvalds 		return 1;
858703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
8591da177e4SLinus Torvalds 		return 1;
8601da177e4SLinus Torvalds 	return 0;
8611da177e4SLinus Torvalds }
8621da177e4SLinus Torvalds 
8631da177e4SLinus Torvalds /*
8641da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
8651da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
8661da177e4SLinus Torvalds  * fsync(), msync() or close().
8671da177e4SLinus Torvalds  *
8681da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
8691da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
8701da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
8711da177e4SLinus Torvalds  *
8721da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
8731da177e4SLinus Torvalds  * __GFP_FS.
8741da177e4SLinus Torvalds  */
8751da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
8761da177e4SLinus Torvalds 				struct page *page, int error)
8771da177e4SLinus Torvalds {
8787eaceaccSJens Axboe 	lock_page(page);
8793e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
8803e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
8811da177e4SLinus Torvalds 	unlock_page(page);
8821da177e4SLinus Torvalds }
8831da177e4SLinus Torvalds 
88404e62a29SChristoph Lameter /* possible outcome of pageout() */
88504e62a29SChristoph Lameter typedef enum {
88604e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
88704e62a29SChristoph Lameter 	PAGE_KEEP,
88804e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
88904e62a29SChristoph Lameter 	PAGE_ACTIVATE,
89004e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
89104e62a29SChristoph Lameter 	PAGE_SUCCESS,
89204e62a29SChristoph Lameter 	/* page is clean and locked */
89304e62a29SChristoph Lameter 	PAGE_CLEAN,
89404e62a29SChristoph Lameter } pageout_t;
89504e62a29SChristoph Lameter 
8961da177e4SLinus Torvalds /*
8971742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
8981742f19fSAndrew Morton  * Calls ->writepage().
8991da177e4SLinus Torvalds  */
900cb16556dSYang Shi static pageout_t pageout(struct page *page, struct address_space *mapping)
9011da177e4SLinus Torvalds {
9021da177e4SLinus Torvalds 	/*
9031da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
9041da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
9051da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
9061da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
9071da177e4SLinus Torvalds 	 * PagePrivate for that.
9081da177e4SLinus Torvalds 	 *
9098174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
9101da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
9111da177e4SLinus Torvalds 	 * will block.
9121da177e4SLinus Torvalds 	 *
9131da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
9141da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
9151da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
9161da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
9171da177e4SLinus Torvalds 	 */
9181da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
9191da177e4SLinus Torvalds 		return PAGE_KEEP;
9201da177e4SLinus Torvalds 	if (!mapping) {
9211da177e4SLinus Torvalds 		/*
9221da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
9231da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
9241da177e4SLinus Torvalds 		 */
925266cf658SDavid Howells 		if (page_has_private(page)) {
9261da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
9271da177e4SLinus Torvalds 				ClearPageDirty(page);
928b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
9291da177e4SLinus Torvalds 				return PAGE_CLEAN;
9301da177e4SLinus Torvalds 			}
9311da177e4SLinus Torvalds 		}
9321da177e4SLinus Torvalds 		return PAGE_KEEP;
9331da177e4SLinus Torvalds 	}
9341da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
9351da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
936cb16556dSYang Shi 	if (!may_write_to_inode(mapping->host))
9371da177e4SLinus Torvalds 		return PAGE_KEEP;
9381da177e4SLinus Torvalds 
9391da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
9401da177e4SLinus Torvalds 		int res;
9411da177e4SLinus Torvalds 		struct writeback_control wbc = {
9421da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
9431da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
944111ebb6eSOGAWA Hirofumi 			.range_start = 0,
945111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
9461da177e4SLinus Torvalds 			.for_reclaim = 1,
9471da177e4SLinus Torvalds 		};
9481da177e4SLinus Torvalds 
9491da177e4SLinus Torvalds 		SetPageReclaim(page);
9501da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
9511da177e4SLinus Torvalds 		if (res < 0)
9521da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
953994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
9541da177e4SLinus Torvalds 			ClearPageReclaim(page);
9551da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
9561da177e4SLinus Torvalds 		}
957c661b078SAndy Whitcroft 
9581da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
9591da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
9601da177e4SLinus Torvalds 			ClearPageReclaim(page);
9611da177e4SLinus Torvalds 		}
9623aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
963c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
9641da177e4SLinus Torvalds 		return PAGE_SUCCESS;
9651da177e4SLinus Torvalds 	}
9661da177e4SLinus Torvalds 
9671da177e4SLinus Torvalds 	return PAGE_CLEAN;
9681da177e4SLinus Torvalds }
9691da177e4SLinus Torvalds 
970a649fd92SAndrew Morton /*
971e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
972e286781dSNick Piggin  * gets returned with a refcount of 0.
973a649fd92SAndrew Morton  */
974a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
975b910718aSJohannes Weiner 			    bool reclaimed, struct mem_cgroup *target_memcg)
97649d2e9ccSChristoph Lameter {
977c4843a75SGreg Thelen 	unsigned long flags;
978bd4c82c2SHuang Ying 	int refcount;
979aae466b0SJoonsoo Kim 	void *shadow = NULL;
980c4843a75SGreg Thelen 
98128e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
98228e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
98349d2e9ccSChristoph Lameter 
984b93b0163SMatthew Wilcox 	xa_lock_irqsave(&mapping->i_pages, flags);
98549d2e9ccSChristoph Lameter 	/*
9860fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
9870fd0e6b0SNick Piggin 	 *
9880fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
9890fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
9900fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
9910fd0e6b0SNick Piggin 	 * here, then the following race may occur:
9920fd0e6b0SNick Piggin 	 *
9930fd0e6b0SNick Piggin 	 * get_user_pages(&page);
9940fd0e6b0SNick Piggin 	 * [user mapping goes away]
9950fd0e6b0SNick Piggin 	 * write_to(page);
9960fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
9970fd0e6b0SNick Piggin 	 * SetPageDirty(page);
9980fd0e6b0SNick Piggin 	 * put_page(page);
9990fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
10000fd0e6b0SNick Piggin 	 *
10010fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
10020fd0e6b0SNick Piggin 	 *
10030fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
10040fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
10050139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
10060fd0e6b0SNick Piggin 	 *
10070fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
1008b93b0163SMatthew Wilcox 	 * and thus under the i_pages lock, then this ordering is not required.
100949d2e9ccSChristoph Lameter 	 */
1010906d278dSWilliam Kucharski 	refcount = 1 + compound_nr(page);
1011bd4c82c2SHuang Ying 	if (!page_ref_freeze(page, refcount))
101249d2e9ccSChristoph Lameter 		goto cannot_free;
10131c4c3b99SJiang Biao 	/* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
1014e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
1015bd4c82c2SHuang Ying 		page_ref_unfreeze(page, refcount);
101649d2e9ccSChristoph Lameter 		goto cannot_free;
1017e286781dSNick Piggin 	}
101849d2e9ccSChristoph Lameter 
101949d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
102049d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
10210a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
1022aae466b0SJoonsoo Kim 		if (reclaimed && !mapping_exiting(mapping))
1023aae466b0SJoonsoo Kim 			shadow = workingset_eviction(page, target_memcg);
1024aae466b0SJoonsoo Kim 		__delete_from_swap_cache(page, swap, shadow);
1025b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
102675f6d6d2SMinchan Kim 		put_swap_page(page, swap);
1027e286781dSNick Piggin 	} else {
10286072d13cSLinus Torvalds 		void (*freepage)(struct page *);
10296072d13cSLinus Torvalds 
10306072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
1031a528910eSJohannes Weiner 		/*
1032a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
1033a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
1034a528910eSJohannes Weiner 		 *
1035a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
1036238c3046Sdylan-meiners 		 * already exiting.  This is not just an optimization,
1037a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
1038a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
1039a528910eSJohannes Weiner 		 * back.
1040f9fe48beSRoss Zwisler 		 *
1041f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
1042f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
1043f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
1044f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
1045b93b0163SMatthew Wilcox 		 * same address_space.
1046a528910eSJohannes Weiner 		 */
10479de4f22aSHuang Ying 		if (reclaimed && page_is_file_lru(page) &&
1048f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
1049b910718aSJohannes Weiner 			shadow = workingset_eviction(page, target_memcg);
105062cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
1051b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
10526072d13cSLinus Torvalds 
10536072d13cSLinus Torvalds 		if (freepage != NULL)
10546072d13cSLinus Torvalds 			freepage(page);
1055e286781dSNick Piggin 	}
1056e286781dSNick Piggin 
105749d2e9ccSChristoph Lameter 	return 1;
105849d2e9ccSChristoph Lameter 
105949d2e9ccSChristoph Lameter cannot_free:
1060b93b0163SMatthew Wilcox 	xa_unlock_irqrestore(&mapping->i_pages, flags);
106149d2e9ccSChristoph Lameter 	return 0;
106249d2e9ccSChristoph Lameter }
106349d2e9ccSChristoph Lameter 
10641da177e4SLinus Torvalds /*
1065e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
1066e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
1067e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
1068e286781dSNick Piggin  * this page.
1069e286781dSNick Piggin  */
1070e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
1071e286781dSNick Piggin {
1072b910718aSJohannes Weiner 	if (__remove_mapping(mapping, page, false, NULL)) {
1073e286781dSNick Piggin 		/*
1074e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
1075e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
1076e286781dSNick Piggin 		 * atomic operation.
1077e286781dSNick Piggin 		 */
1078fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
1079e286781dSNick Piggin 		return 1;
1080e286781dSNick Piggin 	}
1081e286781dSNick Piggin 	return 0;
1082e286781dSNick Piggin }
1083e286781dSNick Piggin 
1084894bc310SLee Schermerhorn /**
1085894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
1086894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
1087894bc310SLee Schermerhorn  *
1088894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
1089894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
1090894bc310SLee Schermerhorn  *
1091894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
1092894bc310SLee Schermerhorn  */
1093894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
1094894bc310SLee Schermerhorn {
1095c53954a0SMel Gorman 	lru_cache_add(page);
1096894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
1097894bc310SLee Schermerhorn }
1098894bc310SLee Schermerhorn 
1099dfc8d636SJohannes Weiner enum page_references {
1100dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
1101dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
110264574746SJohannes Weiner 	PAGEREF_KEEP,
1103dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
1104dfc8d636SJohannes Weiner };
1105dfc8d636SJohannes Weiner 
1106dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
1107dfc8d636SJohannes Weiner 						  struct scan_control *sc)
1108dfc8d636SJohannes Weiner {
110964574746SJohannes Weiner 	int referenced_ptes, referenced_page;
1110dfc8d636SJohannes Weiner 	unsigned long vm_flags;
1111dfc8d636SJohannes Weiner 
1112c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1113c3ac9a8aSJohannes Weiner 					  &vm_flags);
111464574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
1115dfc8d636SJohannes Weiner 
1116dfc8d636SJohannes Weiner 	/*
1117dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
1118dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
1119dfc8d636SJohannes Weiner 	 */
1120dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
1121dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
1122dfc8d636SJohannes Weiner 
112364574746SJohannes Weiner 	if (referenced_ptes) {
112464574746SJohannes Weiner 		/*
112564574746SJohannes Weiner 		 * All mapped pages start out with page table
112664574746SJohannes Weiner 		 * references from the instantiating fault, so we need
112764574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
112864574746SJohannes Weiner 		 * than once.
112964574746SJohannes Weiner 		 *
113064574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
113164574746SJohannes Weiner 		 * inactive list.  Another page table reference will
113264574746SJohannes Weiner 		 * lead to its activation.
113364574746SJohannes Weiner 		 *
113464574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
113564574746SJohannes Weiner 		 * so that recently deactivated but used pages are
113664574746SJohannes Weiner 		 * quickly recovered.
113764574746SJohannes Weiner 		 */
113864574746SJohannes Weiner 		SetPageReferenced(page);
113964574746SJohannes Weiner 
114034dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
1141dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
1142dfc8d636SJohannes Weiner 
1143c909e993SKonstantin Khlebnikov 		/*
1144c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
1145c909e993SKonstantin Khlebnikov 		 */
1146b518154eSJoonsoo Kim 		if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
1147c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
1148c909e993SKonstantin Khlebnikov 
114964574746SJohannes Weiner 		return PAGEREF_KEEP;
115064574746SJohannes Weiner 	}
115164574746SJohannes Weiner 
1152dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
11532e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
1154dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
115564574746SJohannes Weiner 
115664574746SJohannes Weiner 	return PAGEREF_RECLAIM;
1157dfc8d636SJohannes Weiner }
1158dfc8d636SJohannes Weiner 
1159e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
1160e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
1161e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
1162e2be15f6SMel Gorman {
1163b4597226SMel Gorman 	struct address_space *mapping;
1164b4597226SMel Gorman 
1165e2be15f6SMel Gorman 	/*
1166e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
1167e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
1168e2be15f6SMel Gorman 	 */
11699de4f22aSHuang Ying 	if (!page_is_file_lru(page) ||
1170802a3a92SShaohua Li 	    (PageAnon(page) && !PageSwapBacked(page))) {
1171e2be15f6SMel Gorman 		*dirty = false;
1172e2be15f6SMel Gorman 		*writeback = false;
1173e2be15f6SMel Gorman 		return;
1174e2be15f6SMel Gorman 	}
1175e2be15f6SMel Gorman 
1176e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
1177e2be15f6SMel Gorman 	*dirty = PageDirty(page);
1178e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
1179b4597226SMel Gorman 
1180b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
1181b4597226SMel Gorman 	if (!page_has_private(page))
1182b4597226SMel Gorman 		return;
1183b4597226SMel Gorman 
1184b4597226SMel Gorman 	mapping = page_mapping(page);
1185b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
1186b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1187e2be15f6SMel Gorman }
1188e2be15f6SMel Gorman 
1189e286781dSNick Piggin /*
11901742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
11911da177e4SLinus Torvalds  */
1192730ec8c0SManinder Singh static unsigned int shrink_page_list(struct list_head *page_list,
1193599d0c95SMel Gorman 				     struct pglist_data *pgdat,
1194f84f6e2bSMel Gorman 				     struct scan_control *sc,
11953c710c1aSMichal Hocko 				     struct reclaim_stat *stat,
11968940b34aSMinchan Kim 				     bool ignore_references)
11971da177e4SLinus Torvalds {
11981da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
1199abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
1200730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
1201730ec8c0SManinder Singh 	unsigned int pgactivate = 0;
12021da177e4SLinus Torvalds 
1203060f005fSKirill Tkhai 	memset(stat, 0, sizeof(*stat));
12041da177e4SLinus Torvalds 	cond_resched();
12051da177e4SLinus Torvalds 
12061da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
12071da177e4SLinus Torvalds 		struct address_space *mapping;
12081da177e4SLinus Torvalds 		struct page *page;
12098940b34aSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM;
12104b793062SKirill Tkhai 		bool dirty, writeback, may_enter_fs;
121198879b3bSYang Shi 		unsigned int nr_pages;
12121da177e4SLinus Torvalds 
12131da177e4SLinus Torvalds 		cond_resched();
12141da177e4SLinus Torvalds 
12151da177e4SLinus Torvalds 		page = lru_to_page(page_list);
12161da177e4SLinus Torvalds 		list_del(&page->lru);
12171da177e4SLinus Torvalds 
1218529ae9aaSNick Piggin 		if (!trylock_page(page))
12191da177e4SLinus Torvalds 			goto keep;
12201da177e4SLinus Torvalds 
1221309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
12221da177e4SLinus Torvalds 
1223d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
122498879b3bSYang Shi 
122598879b3bSYang Shi 		/* Account the number of base pages even though THP */
122698879b3bSYang Shi 		sc->nr_scanned += nr_pages;
122780e43426SChristoph Lameter 
122839b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
1229ad6b6704SMinchan Kim 			goto activate_locked;
1230894bc310SLee Schermerhorn 
1231a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
123280e43426SChristoph Lameter 			goto keep_locked;
123380e43426SChristoph Lameter 
1234c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1235c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1236c661b078SAndy Whitcroft 
1237e62e384eSMichal Hocko 		/*
1238894befecSAndrey Ryabinin 		 * The number of dirty pages determines if a node is marked
1239e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
1240e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
1241e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
1242e2be15f6SMel Gorman 		 */
1243e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
1244e2be15f6SMel Gorman 		if (dirty || writeback)
1245060f005fSKirill Tkhai 			stat->nr_dirty++;
1246e2be15f6SMel Gorman 
1247e2be15f6SMel Gorman 		if (dirty && !writeback)
1248060f005fSKirill Tkhai 			stat->nr_unqueued_dirty++;
1249e2be15f6SMel Gorman 
1250d04e8acdSMel Gorman 		/*
1251d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
1252d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
1253d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
1254d04e8acdSMel Gorman 		 * end of the LRU a second time.
1255d04e8acdSMel Gorman 		 */
1256e2be15f6SMel Gorman 		mapping = page_mapping(page);
12571da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
1258703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
1259d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
1260060f005fSKirill Tkhai 			stat->nr_congested++;
1261e2be15f6SMel Gorman 
1262e2be15f6SMel Gorman 		/*
1263283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
1264283aba9fSMel Gorman 		 * are three cases to consider.
1265e62e384eSMichal Hocko 		 *
1266283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
1267283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
1268283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
1269283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
1270283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
1271283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
1272283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
1273b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
1274b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
1275c3b94f44SHugh Dickins 		 *
127697c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
1277ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1278ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1279ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
128097c9341fSTejun Heo 		 *    reclaim and continue scanning.
1281283aba9fSMel Gorman 		 *
1282ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1283ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1284283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1285283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1286283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1287283aba9fSMel Gorman 		 *    would probably show more reasons.
1288283aba9fSMel Gorman 		 *
12897fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1290283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1291283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1292283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1293283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1294c55e8d03SJohannes Weiner 		 *
1295c55e8d03SJohannes Weiner 		 * In cases 1) and 2) we activate the pages to get them out of
1296c55e8d03SJohannes Weiner 		 * the way while we continue scanning for clean pages on the
1297c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1298c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1299c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1300c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1301c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1302c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1303e62e384eSMichal Hocko 		 */
1304283aba9fSMel Gorman 		if (PageWriteback(page)) {
1305283aba9fSMel Gorman 			/* Case 1 above */
1306283aba9fSMel Gorman 			if (current_is_kswapd() &&
1307283aba9fSMel Gorman 			    PageReclaim(page) &&
1308599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1309060f005fSKirill Tkhai 				stat->nr_immediate++;
1310c55e8d03SJohannes Weiner 				goto activate_locked;
1311283aba9fSMel Gorman 
1312283aba9fSMel Gorman 			/* Case 2 above */
1313b5ead35eSJohannes Weiner 			} else if (writeback_throttling_sane(sc) ||
1314ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1315c3b94f44SHugh Dickins 				/*
1316c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1317c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1318c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1319c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1320c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1321c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1322c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1323c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1324c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1325c3b94f44SHugh Dickins 				 */
1326c3b94f44SHugh Dickins 				SetPageReclaim(page);
1327060f005fSKirill Tkhai 				stat->nr_writeback++;
1328c55e8d03SJohannes Weiner 				goto activate_locked;
1329283aba9fSMel Gorman 
1330283aba9fSMel Gorman 			/* Case 3 above */
1331283aba9fSMel Gorman 			} else {
13327fadc820SHugh Dickins 				unlock_page(page);
1333c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
13347fadc820SHugh Dickins 				/* then go back and try same page again */
13357fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
13367fadc820SHugh Dickins 				continue;
1337e62e384eSMichal Hocko 			}
1338283aba9fSMel Gorman 		}
13391da177e4SLinus Torvalds 
13408940b34aSMinchan Kim 		if (!ignore_references)
13416a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
134202c6de8dSMinchan Kim 
1343dfc8d636SJohannes Weiner 		switch (references) {
1344dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
13451da177e4SLinus Torvalds 			goto activate_locked;
134664574746SJohannes Weiner 		case PAGEREF_KEEP:
134798879b3bSYang Shi 			stat->nr_ref_keep += nr_pages;
134864574746SJohannes Weiner 			goto keep_locked;
1349dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1350dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1351dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1352dfc8d636SJohannes Weiner 		}
13531da177e4SLinus Torvalds 
13541da177e4SLinus Torvalds 		/*
13551da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
13561da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1357802a3a92SShaohua Li 		 * Lazyfree page could be freed directly
13581da177e4SLinus Torvalds 		 */
1359bd4c82c2SHuang Ying 		if (PageAnon(page) && PageSwapBacked(page)) {
1360bd4c82c2SHuang Ying 			if (!PageSwapCache(page)) {
136163eb6b93SHugh Dickins 				if (!(sc->gfp_mask & __GFP_IO))
136263eb6b93SHugh Dickins 					goto keep_locked;
1363feb889fbSLinus Torvalds 				if (page_maybe_dma_pinned(page))
1364feb889fbSLinus Torvalds 					goto keep_locked;
1365747552b1SHuang Ying 				if (PageTransHuge(page)) {
1366b8f593cdSHuang Ying 					/* cannot split THP, skip it */
1367747552b1SHuang Ying 					if (!can_split_huge_page(page, NULL))
1368b8f593cdSHuang Ying 						goto activate_locked;
1369747552b1SHuang Ying 					/*
1370747552b1SHuang Ying 					 * Split pages without a PMD map right
1371747552b1SHuang Ying 					 * away. Chances are some or all of the
1372747552b1SHuang Ying 					 * tail pages can be freed without IO.
1373747552b1SHuang Ying 					 */
1374747552b1SHuang Ying 					if (!compound_mapcount(page) &&
1375bd4c82c2SHuang Ying 					    split_huge_page_to_list(page,
1376bd4c82c2SHuang Ying 								    page_list))
1377747552b1SHuang Ying 						goto activate_locked;
1378747552b1SHuang Ying 				}
13790f074658SMinchan Kim 				if (!add_to_swap(page)) {
13800f074658SMinchan Kim 					if (!PageTransHuge(page))
138198879b3bSYang Shi 						goto activate_locked_split;
1382bd4c82c2SHuang Ying 					/* Fallback to swap normal pages */
1383bd4c82c2SHuang Ying 					if (split_huge_page_to_list(page,
1384bd4c82c2SHuang Ying 								    page_list))
13850f074658SMinchan Kim 						goto activate_locked;
1386fe490cc0SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1387fe490cc0SHuang Ying 					count_vm_event(THP_SWPOUT_FALLBACK);
1388fe490cc0SHuang Ying #endif
13890f074658SMinchan Kim 					if (!add_to_swap(page))
139098879b3bSYang Shi 						goto activate_locked_split;
13910f074658SMinchan Kim 				}
13920f074658SMinchan Kim 
13934b793062SKirill Tkhai 				may_enter_fs = true;
13941da177e4SLinus Torvalds 
1395e2be15f6SMel Gorman 				/* Adding to swap updated mapping */
13961da177e4SLinus Torvalds 				mapping = page_mapping(page);
1397bd4c82c2SHuang Ying 			}
13987751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
13997751b2daSKirill A. Shutemov 			/* Split file THP */
14007751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
14017751b2daSKirill A. Shutemov 				goto keep_locked;
1402e2be15f6SMel Gorman 		}
14031da177e4SLinus Torvalds 
14041da177e4SLinus Torvalds 		/*
140598879b3bSYang Shi 		 * THP may get split above, need minus tail pages and update
140698879b3bSYang Shi 		 * nr_pages to avoid accounting tail pages twice.
140798879b3bSYang Shi 		 *
140898879b3bSYang Shi 		 * The tail pages that are added into swap cache successfully
140998879b3bSYang Shi 		 * reach here.
141098879b3bSYang Shi 		 */
141198879b3bSYang Shi 		if ((nr_pages > 1) && !PageTransHuge(page)) {
141298879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
141398879b3bSYang Shi 			nr_pages = 1;
141498879b3bSYang Shi 		}
141598879b3bSYang Shi 
141698879b3bSYang Shi 		/*
14171da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
14181da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
14191da177e4SLinus Torvalds 		 */
1420802a3a92SShaohua Li 		if (page_mapped(page)) {
1421013339dfSShakeel Butt 			enum ttu_flags flags = TTU_BATCH_FLUSH;
14221f318a9bSJaewon Kim 			bool was_swapbacked = PageSwapBacked(page);
1423bd4c82c2SHuang Ying 
1424bd4c82c2SHuang Ying 			if (unlikely(PageTransHuge(page)))
1425bd4c82c2SHuang Ying 				flags |= TTU_SPLIT_HUGE_PMD;
14261f318a9bSJaewon Kim 
1427bd4c82c2SHuang Ying 			if (!try_to_unmap(page, flags)) {
142898879b3bSYang Shi 				stat->nr_unmap_fail += nr_pages;
14291f318a9bSJaewon Kim 				if (!was_swapbacked && PageSwapBacked(page))
14301f318a9bSJaewon Kim 					stat->nr_lazyfree_fail += nr_pages;
14311da177e4SLinus Torvalds 				goto activate_locked;
14321da177e4SLinus Torvalds 			}
14331da177e4SLinus Torvalds 		}
14341da177e4SLinus Torvalds 
14351da177e4SLinus Torvalds 		if (PageDirty(page)) {
1436ee72886dSMel Gorman 			/*
14374eda4823SJohannes Weiner 			 * Only kswapd can writeback filesystem pages
14384eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
14394eda4823SJohannes Weiner 			 * injecting inefficient single-page IO into
14404eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
14414eda4823SJohannes Weiner 			 * write pages when we've encountered many
14424eda4823SJohannes Weiner 			 * dirty pages, and when we've already scanned
14434eda4823SJohannes Weiner 			 * the rest of the LRU for clean pages and see
14444eda4823SJohannes Weiner 			 * the same dirty pages again (PageReclaim).
1445ee72886dSMel Gorman 			 */
14469de4f22aSHuang Ying 			if (page_is_file_lru(page) &&
14474eda4823SJohannes Weiner 			    (!current_is_kswapd() || !PageReclaim(page) ||
1448599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
144949ea7eb6SMel Gorman 				/*
145049ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
145149ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
145249ea7eb6SMel Gorman 				 * except we already have the page isolated
145349ea7eb6SMel Gorman 				 * and know it's dirty
145449ea7eb6SMel Gorman 				 */
1455c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
145649ea7eb6SMel Gorman 				SetPageReclaim(page);
145749ea7eb6SMel Gorman 
1458c55e8d03SJohannes Weiner 				goto activate_locked;
1459ee72886dSMel Gorman 			}
1460ee72886dSMel Gorman 
1461dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
14621da177e4SLinus Torvalds 				goto keep_locked;
14634dd4b920SAndrew Morton 			if (!may_enter_fs)
14641da177e4SLinus Torvalds 				goto keep_locked;
146552a8363eSChristoph Lameter 			if (!sc->may_writepage)
14661da177e4SLinus Torvalds 				goto keep_locked;
14671da177e4SLinus Torvalds 
1468d950c947SMel Gorman 			/*
1469d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1470d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1471d950c947SMel Gorman 			 * starts and then write it out here.
1472d950c947SMel Gorman 			 */
1473d950c947SMel Gorman 			try_to_unmap_flush_dirty();
1474cb16556dSYang Shi 			switch (pageout(page, mapping)) {
14751da177e4SLinus Torvalds 			case PAGE_KEEP:
14761da177e4SLinus Torvalds 				goto keep_locked;
14771da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
14781da177e4SLinus Torvalds 				goto activate_locked;
14791da177e4SLinus Torvalds 			case PAGE_SUCCESS:
14806c357848SMatthew Wilcox (Oracle) 				stat->nr_pageout += thp_nr_pages(page);
148196f8bf4fSJohannes Weiner 
14827d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
148341ac1999SMel Gorman 					goto keep;
14847d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
14851da177e4SLinus Torvalds 					goto keep;
14867d3579e8SKOSAKI Motohiro 
14871da177e4SLinus Torvalds 				/*
14881da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
14891da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
14901da177e4SLinus Torvalds 				 */
1491529ae9aaSNick Piggin 				if (!trylock_page(page))
14921da177e4SLinus Torvalds 					goto keep;
14931da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
14941da177e4SLinus Torvalds 					goto keep_locked;
14951da177e4SLinus Torvalds 				mapping = page_mapping(page);
149601359eb2SGustavo A. R. Silva 				fallthrough;
14971da177e4SLinus Torvalds 			case PAGE_CLEAN:
14981da177e4SLinus Torvalds 				; /* try to free the page below */
14991da177e4SLinus Torvalds 			}
15001da177e4SLinus Torvalds 		}
15011da177e4SLinus Torvalds 
15021da177e4SLinus Torvalds 		/*
15031da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
15041da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
15051da177e4SLinus Torvalds 		 * the page as well.
15061da177e4SLinus Torvalds 		 *
15071da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
15081da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
15091da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
15101da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
15111da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
15121da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
15131da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
15141da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
15151da177e4SLinus Torvalds 		 *
15161da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
15171da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
1518d12b8951SYang Shi 		 * truncate_cleanup_page().  We try to drop those buffers here
15191da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
15201da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
15211da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
15221da177e4SLinus Torvalds 		 */
1523266cf658SDavid Howells 		if (page_has_private(page)) {
15241da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
15251da177e4SLinus Torvalds 				goto activate_locked;
1526e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1527e286781dSNick Piggin 				unlock_page(page);
1528e286781dSNick Piggin 				if (put_page_testzero(page))
15291da177e4SLinus Torvalds 					goto free_it;
1530e286781dSNick Piggin 				else {
1531e286781dSNick Piggin 					/*
1532e286781dSNick Piggin 					 * rare race with speculative reference.
1533e286781dSNick Piggin 					 * the speculative reference will free
1534e286781dSNick Piggin 					 * this page shortly, so we may
1535e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1536e286781dSNick Piggin 					 * leave it off the LRU).
1537e286781dSNick Piggin 					 */
1538e286781dSNick Piggin 					nr_reclaimed++;
1539e286781dSNick Piggin 					continue;
1540e286781dSNick Piggin 				}
1541e286781dSNick Piggin 			}
15421da177e4SLinus Torvalds 		}
15431da177e4SLinus Torvalds 
1544802a3a92SShaohua Li 		if (PageAnon(page) && !PageSwapBacked(page)) {
1545802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
1546802a3a92SShaohua Li 			if (!page_ref_freeze(page, 1))
154749d2e9ccSChristoph Lameter 				goto keep_locked;
1548802a3a92SShaohua Li 			if (PageDirty(page)) {
1549802a3a92SShaohua Li 				page_ref_unfreeze(page, 1);
1550802a3a92SShaohua Li 				goto keep_locked;
1551802a3a92SShaohua Li 			}
15521da177e4SLinus Torvalds 
1553802a3a92SShaohua Li 			count_vm_event(PGLAZYFREED);
15542262185cSRoman Gushchin 			count_memcg_page_event(page, PGLAZYFREED);
1555b910718aSJohannes Weiner 		} else if (!mapping || !__remove_mapping(mapping, page, true,
1556b910718aSJohannes Weiner 							 sc->target_mem_cgroup))
1557802a3a92SShaohua Li 			goto keep_locked;
15589a1ea439SHugh Dickins 
15599a1ea439SHugh Dickins 		unlock_page(page);
1560e286781dSNick Piggin free_it:
156198879b3bSYang Shi 		/*
156298879b3bSYang Shi 		 * THP may get swapped out in a whole, need account
156398879b3bSYang Shi 		 * all base pages.
156498879b3bSYang Shi 		 */
156598879b3bSYang Shi 		nr_reclaimed += nr_pages;
1566abe4c3b5SMel Gorman 
1567abe4c3b5SMel Gorman 		/*
1568abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1569abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1570abe4c3b5SMel Gorman 		 */
15717ae88534SYang Shi 		if (unlikely(PageTransHuge(page)))
1572ff45fc3cSMatthew Wilcox (Oracle) 			destroy_compound_page(page);
15737ae88534SYang Shi 		else
1574abe4c3b5SMel Gorman 			list_add(&page->lru, &free_pages);
15751da177e4SLinus Torvalds 		continue;
15761da177e4SLinus Torvalds 
157798879b3bSYang Shi activate_locked_split:
157898879b3bSYang Shi 		/*
157998879b3bSYang Shi 		 * The tail pages that are failed to add into swap cache
158098879b3bSYang Shi 		 * reach here.  Fixup nr_scanned and nr_pages.
158198879b3bSYang Shi 		 */
158298879b3bSYang Shi 		if (nr_pages > 1) {
158398879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
158498879b3bSYang Shi 			nr_pages = 1;
158598879b3bSYang Shi 		}
15861da177e4SLinus Torvalds activate_locked:
158768a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
1588ad6b6704SMinchan Kim 		if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1589ad6b6704SMinchan Kim 						PageMlocked(page)))
1590a2c43eedSHugh Dickins 			try_to_free_swap(page);
1591309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
1592ad6b6704SMinchan Kim 		if (!PageMlocked(page)) {
15939de4f22aSHuang Ying 			int type = page_is_file_lru(page);
15941da177e4SLinus Torvalds 			SetPageActive(page);
159598879b3bSYang Shi 			stat->nr_activate[type] += nr_pages;
15962262185cSRoman Gushchin 			count_memcg_page_event(page, PGACTIVATE);
1597ad6b6704SMinchan Kim 		}
15981da177e4SLinus Torvalds keep_locked:
15991da177e4SLinus Torvalds 		unlock_page(page);
16001da177e4SLinus Torvalds keep:
16011da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1602309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
16031da177e4SLinus Torvalds 	}
1604abe4c3b5SMel Gorman 
160598879b3bSYang Shi 	pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
160698879b3bSYang Shi 
1607747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
160872b252aeSMel Gorman 	try_to_unmap_flush();
16092d4894b5SMel Gorman 	free_unref_page_list(&free_pages);
1610abe4c3b5SMel Gorman 
16111da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1612886cf190SKirill Tkhai 	count_vm_events(PGACTIVATE, pgactivate);
16130a31bc97SJohannes Weiner 
161405ff5137SAndrew Morton 	return nr_reclaimed;
16151da177e4SLinus Torvalds }
16161da177e4SLinus Torvalds 
1617730ec8c0SManinder Singh unsigned int reclaim_clean_pages_from_list(struct zone *zone,
161802c6de8dSMinchan Kim 					    struct list_head *page_list)
161902c6de8dSMinchan Kim {
162002c6de8dSMinchan Kim 	struct scan_control sc = {
162102c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
162202c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
162302c6de8dSMinchan Kim 		.may_unmap = 1,
162402c6de8dSMinchan Kim 	};
16251f318a9bSJaewon Kim 	struct reclaim_stat stat;
1626730ec8c0SManinder Singh 	unsigned int nr_reclaimed;
162702c6de8dSMinchan Kim 	struct page *page, *next;
162802c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
162902c6de8dSMinchan Kim 
163002c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1631ae37c7ffSOscar Salvador 		if (!PageHuge(page) && page_is_file_lru(page) &&
1632ae37c7ffSOscar Salvador 		    !PageDirty(page) && !__PageMovable(page) &&
1633ae37c7ffSOscar Salvador 		    !PageUnevictable(page)) {
163402c6de8dSMinchan Kim 			ClearPageActive(page);
163502c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
163602c6de8dSMinchan Kim 		}
163702c6de8dSMinchan Kim 	}
163802c6de8dSMinchan Kim 
16391f318a9bSJaewon Kim 	nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1640013339dfSShakeel Butt 					&stat, true);
164102c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
16422da9f630SNicholas Piggin 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
16432da9f630SNicholas Piggin 			    -(long)nr_reclaimed);
16441f318a9bSJaewon Kim 	/*
16451f318a9bSJaewon Kim 	 * Since lazyfree pages are isolated from file LRU from the beginning,
16461f318a9bSJaewon Kim 	 * they will rotate back to anonymous LRU in the end if it failed to
16471f318a9bSJaewon Kim 	 * discard so isolated count will be mismatched.
16481f318a9bSJaewon Kim 	 * Compensate the isolated count for both LRU lists.
16491f318a9bSJaewon Kim 	 */
16501f318a9bSJaewon Kim 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
16511f318a9bSJaewon Kim 			    stat.nr_lazyfree_fail);
16521f318a9bSJaewon Kim 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
16532da9f630SNicholas Piggin 			    -(long)stat.nr_lazyfree_fail);
16541f318a9bSJaewon Kim 	return nr_reclaimed;
165502c6de8dSMinchan Kim }
165602c6de8dSMinchan Kim 
16575ad333ebSAndy Whitcroft /*
16585ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
16595ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
16605ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
16615ad333ebSAndy Whitcroft  *
16625ad333ebSAndy Whitcroft  * page:	page to consider
16635ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
16645ad333ebSAndy Whitcroft  *
1665c2135f7cSAlex Shi  * returns true on success, false on failure.
16665ad333ebSAndy Whitcroft  */
1667c2135f7cSAlex Shi bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
16685ad333ebSAndy Whitcroft {
16695ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
16705ad333ebSAndy Whitcroft 	if (!PageLRU(page))
1671c2135f7cSAlex Shi 		return false;
16725ad333ebSAndy Whitcroft 
1673e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1674e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1675c2135f7cSAlex Shi 		return false;
1676894bc310SLee Schermerhorn 
1677c8244935SMel Gorman 	/*
1678c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1679c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1680c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1681c8244935SMel Gorman 	 *
1682c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1683c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1684c8244935SMel Gorman 	 */
16851276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1686c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1687c8244935SMel Gorman 		if (PageWriteback(page))
1688c2135f7cSAlex Shi 			return false;
168939deaf85SMinchan Kim 
1690c8244935SMel Gorman 		if (PageDirty(page)) {
1691c8244935SMel Gorman 			struct address_space *mapping;
169269d763fcSMel Gorman 			bool migrate_dirty;
1693c8244935SMel Gorman 
1694c8244935SMel Gorman 			/*
1695c8244935SMel Gorman 			 * Only pages without mappings or that have a
1696c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
169769d763fcSMel Gorman 			 * without blocking. However, we can be racing with
169869d763fcSMel Gorman 			 * truncation so it's necessary to lock the page
169969d763fcSMel Gorman 			 * to stabilise the mapping as truncation holds
170069d763fcSMel Gorman 			 * the page lock until after the page is removed
170169d763fcSMel Gorman 			 * from the page cache.
1702c8244935SMel Gorman 			 */
170369d763fcSMel Gorman 			if (!trylock_page(page))
1704c2135f7cSAlex Shi 				return false;
170569d763fcSMel Gorman 
1706c8244935SMel Gorman 			mapping = page_mapping(page);
1707145e1a71SHugh Dickins 			migrate_dirty = !mapping || mapping->a_ops->migratepage;
170869d763fcSMel Gorman 			unlock_page(page);
170969d763fcSMel Gorman 			if (!migrate_dirty)
1710c2135f7cSAlex Shi 				return false;
1711c8244935SMel Gorman 		}
1712c8244935SMel Gorman 	}
1713c8244935SMel Gorman 
1714f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1715c2135f7cSAlex Shi 		return false;
1716f80c0673SMinchan Kim 
1717c2135f7cSAlex Shi 	return true;
17185ad333ebSAndy Whitcroft }
17195ad333ebSAndy Whitcroft 
17207ee36a14SMel Gorman /*
17217ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
172255b65a57SEthon Paul  * be complete before mem_cgroup_update_lru_size due to a sanity check.
17237ee36a14SMel Gorman  */
17247ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1725b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
17267ee36a14SMel Gorman {
17277ee36a14SMel Gorman 	int zid;
17287ee36a14SMel Gorman 
17297ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
17307ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
17317ee36a14SMel Gorman 			continue;
17327ee36a14SMel Gorman 
1733a892cb6bSWei Yang 		update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
17347ee36a14SMel Gorman 	}
17357ee36a14SMel Gorman 
17367ee36a14SMel Gorman }
17377ee36a14SMel Gorman 
1738f4b7e272SAndrey Ryabinin /**
173915b44736SHugh Dickins  * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
174015b44736SHugh Dickins  *
174115b44736SHugh Dickins  * lruvec->lru_lock is heavily contended.  Some of the functions that
17421da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
17431da177e4SLinus Torvalds  * and working on them outside the LRU lock.
17441da177e4SLinus Torvalds  *
17451da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
17461da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
17471da177e4SLinus Torvalds  *
174815b44736SHugh Dickins  * Lru_lock must be held before calling this function.
17491da177e4SLinus Torvalds  *
1750791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
17515dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
17521da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1753f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1754fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
17553cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
17561da177e4SLinus Torvalds  *
17571da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
17581da177e4SLinus Torvalds  */
175969e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
17605dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1761fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
1762a9e7c39fSKirill Tkhai 		enum lru_list lru)
17631da177e4SLinus Torvalds {
176475b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
176569e05944SAndrew Morton 	unsigned long nr_taken = 0;
1766599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
17677cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
17683db65812SJohannes Weiner 	unsigned long skipped = 0;
1769791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
1770b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
1771a9e7c39fSKirill Tkhai 	isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
17721da177e4SLinus Torvalds 
177398879b3bSYang Shi 	total_scan = 0;
1774791b48b6SMinchan Kim 	scan = 0;
177598879b3bSYang Shi 	while (scan < nr_to_scan && !list_empty(src)) {
17765ad333ebSAndy Whitcroft 		struct page *page;
17775ad333ebSAndy Whitcroft 
17781da177e4SLinus Torvalds 		page = lru_to_page(src);
17791da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
17801da177e4SLinus Torvalds 
1781d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
178298879b3bSYang Shi 		total_scan += nr_pages;
178398879b3bSYang Shi 
1784b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1785b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
178698879b3bSYang Shi 			nr_skipped[page_zonenum(page)] += nr_pages;
1787b2e18757SMel Gorman 			continue;
1788b2e18757SMel Gorman 		}
1789b2e18757SMel Gorman 
1790791b48b6SMinchan Kim 		/*
1791791b48b6SMinchan Kim 		 * Do not count skipped pages because that makes the function
1792791b48b6SMinchan Kim 		 * return with no isolated pages if the LRU mostly contains
1793791b48b6SMinchan Kim 		 * ineligible pages.  This causes the VM to not reclaim any
1794791b48b6SMinchan Kim 		 * pages, triggering a premature OOM.
179598879b3bSYang Shi 		 *
179698879b3bSYang Shi 		 * Account all tail pages of THP.  This would not cause
179798879b3bSYang Shi 		 * premature OOM since __isolate_lru_page() returns -EBUSY
179898879b3bSYang Shi 		 * only when the page is being freed somewhere else.
1799791b48b6SMinchan Kim 		 */
180098879b3bSYang Shi 		scan += nr_pages;
1801c2135f7cSAlex Shi 		if (!__isolate_lru_page_prepare(page, mode)) {
1802c2135f7cSAlex Shi 			/* It is being freed elsewhere */
1803c2135f7cSAlex Shi 			list_move(&page->lru, src);
1804c2135f7cSAlex Shi 			continue;
1805c2135f7cSAlex Shi 		}
18069df41314SAlex Shi 		/*
18079df41314SAlex Shi 		 * Be careful not to clear PageLRU until after we're
18089df41314SAlex Shi 		 * sure the page is not being freed elsewhere -- the
18099df41314SAlex Shi 		 * page release code relies on it.
18109df41314SAlex Shi 		 */
1811c2135f7cSAlex Shi 		if (unlikely(!get_page_unless_zero(page))) {
1812c2135f7cSAlex Shi 			list_move(&page->lru, src);
1813c2135f7cSAlex Shi 			continue;
1814c2135f7cSAlex Shi 		}
18159df41314SAlex Shi 
18169df41314SAlex Shi 		if (!TestClearPageLRU(page)) {
1817c2135f7cSAlex Shi 			/* Another thread is already isolating this page */
18189df41314SAlex Shi 			put_page(page);
1819c2135f7cSAlex Shi 			list_move(&page->lru, src);
1820c2135f7cSAlex Shi 			continue;
18219df41314SAlex Shi 		}
18229df41314SAlex Shi 
1823599d0c95SMel Gorman 		nr_taken += nr_pages;
1824599d0c95SMel Gorman 		nr_zone_taken[page_zonenum(page)] += nr_pages;
18255ad333ebSAndy Whitcroft 		list_move(&page->lru, dst);
18265ad333ebSAndy Whitcroft 	}
18271da177e4SLinus Torvalds 
1828b2e18757SMel Gorman 	/*
1829b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1830b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1831b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1832b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1833b2e18757SMel Gorman 	 * system at risk of premature OOM.
1834b2e18757SMel Gorman 	 */
18357cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
18367cc30fcfSMel Gorman 		int zid;
18377cc30fcfSMel Gorman 
18383db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
18397cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
18407cc30fcfSMel Gorman 			if (!nr_skipped[zid])
18417cc30fcfSMel Gorman 				continue;
18427cc30fcfSMel Gorman 
18437cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
18441265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
18457cc30fcfSMel Gorman 		}
18467cc30fcfSMel Gorman 	}
1847791b48b6SMinchan Kim 	*nr_scanned = total_scan;
18481265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1849791b48b6SMinchan Kim 				    total_scan, skipped, nr_taken, mode, lru);
1850b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
18511da177e4SLinus Torvalds 	return nr_taken;
18521da177e4SLinus Torvalds }
18531da177e4SLinus Torvalds 
185462695a84SNick Piggin /**
185562695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
185662695a84SNick Piggin  * @page: page to isolate from its LRU list
185762695a84SNick Piggin  *
185862695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
185962695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
186062695a84SNick Piggin  *
186162695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
186262695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
186362695a84SNick Piggin  *
186462695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1865894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1866894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1867894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
186862695a84SNick Piggin  *
186962695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
187062695a84SNick Piggin  * found will be decremented.
187162695a84SNick Piggin  *
187262695a84SNick Piggin  * Restrictions:
1873a5d09bedSMike Rapoport  *
187462695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
187501c4776bSHui Su  *     fundamental difference from isolate_lru_pages (which is called
187662695a84SNick Piggin  *     without a stable reference).
187762695a84SNick Piggin  * (2) the lru_lock must not be held.
187862695a84SNick Piggin  * (3) interrupts must be enabled.
187962695a84SNick Piggin  */
188062695a84SNick Piggin int isolate_lru_page(struct page *page)
188162695a84SNick Piggin {
188262695a84SNick Piggin 	int ret = -EBUSY;
188362695a84SNick Piggin 
1884309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1885cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
18860c917313SKonstantin Khlebnikov 
1887d25b5bd8SAlex Shi 	if (TestClearPageLRU(page)) {
1888fa9add64SHugh Dickins 		struct lruvec *lruvec;
188962695a84SNick Piggin 
18900c917313SKonstantin Khlebnikov 		get_page(page);
18916168d0daSAlex Shi 		lruvec = lock_page_lruvec_irq(page);
189246ae6b2cSYu Zhao 		del_page_from_lru_list(page, lruvec);
18936168d0daSAlex Shi 		unlock_page_lruvec_irq(lruvec);
1894fa9add64SHugh Dickins 		ret = 0;
189562695a84SNick Piggin 	}
1896d25b5bd8SAlex Shi 
189762695a84SNick Piggin 	return ret;
189862695a84SNick Piggin }
189962695a84SNick Piggin 
19005ad333ebSAndy Whitcroft /*
1901d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1902178821b8SXianting Tian  * then get rescheduled. When there are massive number of tasks doing page
1903d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1904d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1905d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
190635cd7815SRik van Riel  */
1907599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
190835cd7815SRik van Riel 		struct scan_control *sc)
190935cd7815SRik van Riel {
191035cd7815SRik van Riel 	unsigned long inactive, isolated;
191135cd7815SRik van Riel 
191235cd7815SRik van Riel 	if (current_is_kswapd())
191335cd7815SRik van Riel 		return 0;
191435cd7815SRik van Riel 
1915b5ead35eSJohannes Weiner 	if (!writeback_throttling_sane(sc))
191635cd7815SRik van Riel 		return 0;
191735cd7815SRik van Riel 
191835cd7815SRik van Riel 	if (file) {
1919599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1920599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
192135cd7815SRik van Riel 	} else {
1922599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1923599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
192435cd7815SRik van Riel 	}
192535cd7815SRik van Riel 
19263cf23841SFengguang Wu 	/*
19273cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
19283cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
19293cf23841SFengguang Wu 	 * deadlock.
19303cf23841SFengguang Wu 	 */
1931d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
19323cf23841SFengguang Wu 		inactive >>= 3;
19333cf23841SFengguang Wu 
193435cd7815SRik van Riel 	return isolated > inactive;
193535cd7815SRik van Riel }
193635cd7815SRik van Riel 
1937a222f341SKirill Tkhai /*
193815b44736SHugh Dickins  * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
193915b44736SHugh Dickins  * On return, @list is reused as a list of pages to be freed by the caller.
1940a222f341SKirill Tkhai  *
1941a222f341SKirill Tkhai  * Returns the number of pages moved to the given lruvec.
1942a222f341SKirill Tkhai  */
1943a222f341SKirill Tkhai static unsigned noinline_for_stack move_pages_to_lru(struct lruvec *lruvec,
1944a222f341SKirill Tkhai 						     struct list_head *list)
194566635629SMel Gorman {
1946a222f341SKirill Tkhai 	int nr_pages, nr_moved = 0;
19473f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
1948a222f341SKirill Tkhai 	struct page *page;
194966635629SMel Gorman 
1950a222f341SKirill Tkhai 	while (!list_empty(list)) {
1951a222f341SKirill Tkhai 		page = lru_to_page(list);
1952309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
1953a222f341SKirill Tkhai 		list_del(&page->lru);
19543d06afabSAlex Shi 		if (unlikely(!page_evictable(page))) {
19556168d0daSAlex Shi 			spin_unlock_irq(&lruvec->lru_lock);
195666635629SMel Gorman 			putback_lru_page(page);
19576168d0daSAlex Shi 			spin_lock_irq(&lruvec->lru_lock);
195866635629SMel Gorman 			continue;
195966635629SMel Gorman 		}
1960fa9add64SHugh Dickins 
19613d06afabSAlex Shi 		/*
19623d06afabSAlex Shi 		 * The SetPageLRU needs to be kept here for list integrity.
19633d06afabSAlex Shi 		 * Otherwise:
19643d06afabSAlex Shi 		 *   #0 move_pages_to_lru             #1 release_pages
19653d06afabSAlex Shi 		 *   if !put_page_testzero
19663d06afabSAlex Shi 		 *				      if (put_page_testzero())
19673d06afabSAlex Shi 		 *				        !PageLRU //skip lru_lock
19683d06afabSAlex Shi 		 *     SetPageLRU()
19693d06afabSAlex Shi 		 *     list_add(&page->lru,)
19703d06afabSAlex Shi 		 *                                        list_add(&page->lru,)
19713d06afabSAlex Shi 		 */
19727a608572SLinus Torvalds 		SetPageLRU(page);
1973a222f341SKirill Tkhai 
19743d06afabSAlex Shi 		if (unlikely(put_page_testzero(page))) {
197587560179SYu Zhao 			__clear_page_lru_flags(page);
19762bcf8879SHugh Dickins 
19772bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
19786168d0daSAlex Shi 				spin_unlock_irq(&lruvec->lru_lock);
1979ff45fc3cSMatthew Wilcox (Oracle) 				destroy_compound_page(page);
19806168d0daSAlex Shi 				spin_lock_irq(&lruvec->lru_lock);
19812bcf8879SHugh Dickins 			} else
19822bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
19833d06afabSAlex Shi 
19843d06afabSAlex Shi 			continue;
19853d06afabSAlex Shi 		}
19863d06afabSAlex Shi 
1987afca9157SAlex Shi 		/*
1988afca9157SAlex Shi 		 * All pages were isolated from the same lruvec (and isolation
1989afca9157SAlex Shi 		 * inhibits memcg migration).
1990afca9157SAlex Shi 		 */
19912a5e4e34SAlexander Duyck 		VM_BUG_ON_PAGE(!lruvec_holds_page_lru_lock(page, lruvec), page);
19923a9c9788SYu Zhao 		add_page_to_lru_list(page, lruvec);
19933d06afabSAlex Shi 		nr_pages = thp_nr_pages(page);
1994a222f341SKirill Tkhai 		nr_moved += nr_pages;
199531d8fcacSJohannes Weiner 		if (PageActive(page))
199631d8fcacSJohannes Weiner 			workingset_age_nonresident(lruvec, nr_pages);
199766635629SMel Gorman 	}
199866635629SMel Gorman 
19993f79768fSHugh Dickins 	/*
20003f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
20013f79768fSHugh Dickins 	 */
2002a222f341SKirill Tkhai 	list_splice(&pages_to_free, list);
2003a222f341SKirill Tkhai 
2004a222f341SKirill Tkhai 	return nr_moved;
200566635629SMel Gorman }
200666635629SMel Gorman 
200766635629SMel Gorman /*
2008399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
2009a37b0715SNeilBrown  * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
2010399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
2011399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
2012399ba0b9SNeilBrown  */
2013399ba0b9SNeilBrown static int current_may_throttle(void)
2014399ba0b9SNeilBrown {
2015a37b0715SNeilBrown 	return !(current->flags & PF_LOCAL_THROTTLE) ||
2016399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
2017399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
2018399ba0b9SNeilBrown }
2019399ba0b9SNeilBrown 
2020399ba0b9SNeilBrown /*
2021b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
20221742f19fSAndrew Morton  * of reclaimed pages
20231da177e4SLinus Torvalds  */
202466635629SMel Gorman static noinline_for_stack unsigned long
20251a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
20269e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
20271da177e4SLinus Torvalds {
20281da177e4SLinus Torvalds 	LIST_HEAD(page_list);
2029e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
2030730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
2031e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
2032060f005fSKirill Tkhai 	struct reclaim_stat stat;
2033497a6c1bSJohannes Weiner 	bool file = is_file_lru(lru);
2034f46b7912SKirill Tkhai 	enum vm_event_item item;
2035599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2036db73ee0dSMichal Hocko 	bool stalled = false;
203778dc583dSKOSAKI Motohiro 
2038599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
2039db73ee0dSMichal Hocko 		if (stalled)
2040db73ee0dSMichal Hocko 			return 0;
2041db73ee0dSMichal Hocko 
2042db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
2043db73ee0dSMichal Hocko 		msleep(100);
2044db73ee0dSMichal Hocko 		stalled = true;
204535cd7815SRik van Riel 
204635cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
204735cd7815SRik van Riel 		if (fatal_signal_pending(current))
204835cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
204935cd7815SRik van Riel 	}
205035cd7815SRik van Riel 
20511da177e4SLinus Torvalds 	lru_add_drain();
2052f80c0673SMinchan Kim 
20536168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
20541da177e4SLinus Torvalds 
20555dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
2056a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
205795d918fcSKonstantin Khlebnikov 
2058599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2059f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
2060b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
2061f46b7912SKirill Tkhai 		__count_vm_events(item, nr_scanned);
2062f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
2063497a6c1bSJohannes Weiner 	__count_vm_events(PGSCAN_ANON + file, nr_scanned);
2064497a6c1bSJohannes Weiner 
20656168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
2066d563c050SHillf Danton 
2067d563c050SHillf Danton 	if (nr_taken == 0)
206866635629SMel Gorman 		return 0;
2069b35ea17bSKOSAKI Motohiro 
2070013339dfSShakeel Butt 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
2071c661b078SAndy Whitcroft 
20726168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2073497a6c1bSJohannes Weiner 	move_pages_to_lru(lruvec, &page_list);
2074497a6c1bSJohannes Weiner 
2075497a6c1bSJohannes Weiner 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2076f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
2077b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
2078f46b7912SKirill Tkhai 		__count_vm_events(item, nr_reclaimed);
2079f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
2080497a6c1bSJohannes Weiner 	__count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
20816168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
20823f79768fSHugh Dickins 
208375cc3c91SAlex Shi 	lru_note_cost(lruvec, file, stat.nr_pageout);
2084747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
20852d4894b5SMel Gorman 	free_unref_page_list(&page_list);
2086e11da5b4SMel Gorman 
208792df3a72SMel Gorman 	/*
20881c610d5fSAndrey Ryabinin 	 * If dirty pages are scanned that are not queued for IO, it
20891c610d5fSAndrey Ryabinin 	 * implies that flushers are not doing their job. This can
20901c610d5fSAndrey Ryabinin 	 * happen when memory pressure pushes dirty pages to the end of
20911c610d5fSAndrey Ryabinin 	 * the LRU before the dirty limits are breached and the dirty
20921c610d5fSAndrey Ryabinin 	 * data has expired. It can also happen when the proportion of
20931c610d5fSAndrey Ryabinin 	 * dirty pages grows not through writes but through memory
20941c610d5fSAndrey Ryabinin 	 * pressure reclaiming all the clean cache. And in some cases,
20951c610d5fSAndrey Ryabinin 	 * the flushers simply cannot keep up with the allocation
20961c610d5fSAndrey Ryabinin 	 * rate. Nudge the flusher threads in case they are asleep.
20971c610d5fSAndrey Ryabinin 	 */
20981c610d5fSAndrey Ryabinin 	if (stat.nr_unqueued_dirty == nr_taken)
20991c610d5fSAndrey Ryabinin 		wakeup_flusher_threads(WB_REASON_VMSCAN);
21001c610d5fSAndrey Ryabinin 
2101d108c772SAndrey Ryabinin 	sc->nr.dirty += stat.nr_dirty;
2102d108c772SAndrey Ryabinin 	sc->nr.congested += stat.nr_congested;
2103d108c772SAndrey Ryabinin 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2104d108c772SAndrey Ryabinin 	sc->nr.writeback += stat.nr_writeback;
2105d108c772SAndrey Ryabinin 	sc->nr.immediate += stat.nr_immediate;
2106d108c772SAndrey Ryabinin 	sc->nr.taken += nr_taken;
2107d108c772SAndrey Ryabinin 	if (file)
2108d108c772SAndrey Ryabinin 		sc->nr.file_taken += nr_taken;
21098e950282SMel Gorman 
2110599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2111d51d1e64SSteven Rostedt 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
211205ff5137SAndrew Morton 	return nr_reclaimed;
21131da177e4SLinus Torvalds }
21141da177e4SLinus Torvalds 
211515b44736SHugh Dickins /*
211615b44736SHugh Dickins  * shrink_active_list() moves pages from the active LRU to the inactive LRU.
211715b44736SHugh Dickins  *
211815b44736SHugh Dickins  * We move them the other way if the page is referenced by one or more
211915b44736SHugh Dickins  * processes.
212015b44736SHugh Dickins  *
212115b44736SHugh Dickins  * If the pages are mostly unmapped, the processing is fast and it is
212215b44736SHugh Dickins  * appropriate to hold lru_lock across the whole operation.  But if
212315b44736SHugh Dickins  * the pages are mapped, the processing is slow (page_referenced()), so
212415b44736SHugh Dickins  * we should drop lru_lock around each page.  It's impossible to balance
212515b44736SHugh Dickins  * this, so instead we remove the pages from the LRU while processing them.
212615b44736SHugh Dickins  * It is safe to rely on PG_active against the non-LRU pages in here because
212715b44736SHugh Dickins  * nobody will play with that bit on a non-LRU page.
212815b44736SHugh Dickins  *
212915b44736SHugh Dickins  * The downside is that we have to touch page->_refcount against each page.
213015b44736SHugh Dickins  * But we had to alter page->flags anyway.
213115b44736SHugh Dickins  */
2132f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
21331a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
2134f16015fbSJohannes Weiner 			       struct scan_control *sc,
21359e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
21361cfb419bSKAMEZAWA Hiroyuki {
213744c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
2138f626012dSHugh Dickins 	unsigned long nr_scanned;
21396fe6b7e3SWu Fengguang 	unsigned long vm_flags;
21401cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
21418cab4754SWu Fengguang 	LIST_HEAD(l_active);
2142b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
21431cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
21449d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
21459d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
21463cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
2147599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
21481cfb419bSKAMEZAWA Hiroyuki 
21491da177e4SLinus Torvalds 	lru_add_drain();
2150f80c0673SMinchan Kim 
21516168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2152925b7673SJohannes Weiner 
21535dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2154a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
215589b5fae5SJohannes Weiner 
2156599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
21571cfb419bSKAMEZAWA Hiroyuki 
2158912c0572SShakeel Butt 	if (!cgroup_reclaim(sc))
2159599d0c95SMel Gorman 		__count_vm_events(PGREFILL, nr_scanned);
21602fa2690cSYafang Shao 	__count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
21619d5e6a9fSHugh Dickins 
21626168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
21631da177e4SLinus Torvalds 
21641da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
21651da177e4SLinus Torvalds 		cond_resched();
21661da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
21671da177e4SLinus Torvalds 		list_del(&page->lru);
21687e9cd484SRik van Riel 
216939b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
2170894bc310SLee Schermerhorn 			putback_lru_page(page);
2171894bc310SLee Schermerhorn 			continue;
2172894bc310SLee Schermerhorn 		}
2173894bc310SLee Schermerhorn 
2174cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
2175cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
2176cc715d99SMel Gorman 				if (page_has_private(page))
2177cc715d99SMel Gorman 					try_to_release_page(page, 0);
2178cc715d99SMel Gorman 				unlock_page(page);
2179cc715d99SMel Gorman 			}
2180cc715d99SMel Gorman 		}
2181cc715d99SMel Gorman 
2182c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
2183c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
21848cab4754SWu Fengguang 			/*
21858cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
21868cab4754SWu Fengguang 			 * give them one more trip around the active list. So
21878cab4754SWu Fengguang 			 * that executable code get better chances to stay in
21888cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
21898cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
21908cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
21918cab4754SWu Fengguang 			 * so we ignore them here.
21928cab4754SWu Fengguang 			 */
21939de4f22aSHuang Ying 			if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
21946c357848SMatthew Wilcox (Oracle) 				nr_rotated += thp_nr_pages(page);
21958cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
21968cab4754SWu Fengguang 				continue;
21978cab4754SWu Fengguang 			}
21988cab4754SWu Fengguang 		}
21997e9cd484SRik van Riel 
22005205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
22011899ad18SJohannes Weiner 		SetPageWorkingset(page);
22021da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
22031da177e4SLinus Torvalds 	}
22041da177e4SLinus Torvalds 
2205b555749aSAndrew Morton 	/*
22068cab4754SWu Fengguang 	 * Move pages back to the lru list.
2207b555749aSAndrew Morton 	 */
22086168d0daSAlex Shi 	spin_lock_irq(&lruvec->lru_lock);
2209556adecbSRik van Riel 
2210a222f341SKirill Tkhai 	nr_activate = move_pages_to_lru(lruvec, &l_active);
2211a222f341SKirill Tkhai 	nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2212f372d89eSKirill Tkhai 	/* Keep all free pages in l_active list */
2213f372d89eSKirill Tkhai 	list_splice(&l_inactive, &l_active);
22149851ac13SKirill Tkhai 
22159851ac13SKirill Tkhai 	__count_vm_events(PGDEACTIVATE, nr_deactivate);
22169851ac13SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
22179851ac13SKirill Tkhai 
2218599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
22196168d0daSAlex Shi 	spin_unlock_irq(&lruvec->lru_lock);
22202bcf8879SHugh Dickins 
2221f372d89eSKirill Tkhai 	mem_cgroup_uncharge_list(&l_active);
2222f372d89eSKirill Tkhai 	free_unref_page_list(&l_active);
22239d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
22249d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
22251da177e4SLinus Torvalds }
22261da177e4SLinus Torvalds 
22271a4e58ccSMinchan Kim unsigned long reclaim_pages(struct list_head *page_list)
22281a4e58ccSMinchan Kim {
2229f661d007SYang Shi 	int nid = NUMA_NO_NODE;
2230730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
22311a4e58ccSMinchan Kim 	LIST_HEAD(node_page_list);
22321a4e58ccSMinchan Kim 	struct reclaim_stat dummy_stat;
22331a4e58ccSMinchan Kim 	struct page *page;
22341a4e58ccSMinchan Kim 	struct scan_control sc = {
22351a4e58ccSMinchan Kim 		.gfp_mask = GFP_KERNEL,
22361a4e58ccSMinchan Kim 		.priority = DEF_PRIORITY,
22371a4e58ccSMinchan Kim 		.may_writepage = 1,
22381a4e58ccSMinchan Kim 		.may_unmap = 1,
22391a4e58ccSMinchan Kim 		.may_swap = 1,
22401a4e58ccSMinchan Kim 	};
22411a4e58ccSMinchan Kim 
22421a4e58ccSMinchan Kim 	while (!list_empty(page_list)) {
22431a4e58ccSMinchan Kim 		page = lru_to_page(page_list);
2244f661d007SYang Shi 		if (nid == NUMA_NO_NODE) {
22451a4e58ccSMinchan Kim 			nid = page_to_nid(page);
22461a4e58ccSMinchan Kim 			INIT_LIST_HEAD(&node_page_list);
22471a4e58ccSMinchan Kim 		}
22481a4e58ccSMinchan Kim 
22491a4e58ccSMinchan Kim 		if (nid == page_to_nid(page)) {
22501a4e58ccSMinchan Kim 			ClearPageActive(page);
22511a4e58ccSMinchan Kim 			list_move(&page->lru, &node_page_list);
22521a4e58ccSMinchan Kim 			continue;
22531a4e58ccSMinchan Kim 		}
22541a4e58ccSMinchan Kim 
22551a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
22561a4e58ccSMinchan Kim 						NODE_DATA(nid),
2257013339dfSShakeel Butt 						&sc, &dummy_stat, false);
22581a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
22591a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
22601a4e58ccSMinchan Kim 			list_del(&page->lru);
22611a4e58ccSMinchan Kim 			putback_lru_page(page);
22621a4e58ccSMinchan Kim 		}
22631a4e58ccSMinchan Kim 
2264f661d007SYang Shi 		nid = NUMA_NO_NODE;
22651a4e58ccSMinchan Kim 	}
22661a4e58ccSMinchan Kim 
22671a4e58ccSMinchan Kim 	if (!list_empty(&node_page_list)) {
22681a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
22691a4e58ccSMinchan Kim 						NODE_DATA(nid),
2270013339dfSShakeel Butt 						&sc, &dummy_stat, false);
22711a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
22721a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
22731a4e58ccSMinchan Kim 			list_del(&page->lru);
22741a4e58ccSMinchan Kim 			putback_lru_page(page);
22751a4e58ccSMinchan Kim 		}
22761a4e58ccSMinchan Kim 	}
22771a4e58ccSMinchan Kim 
22781a4e58ccSMinchan Kim 	return nr_reclaimed;
22791a4e58ccSMinchan Kim }
22801a4e58ccSMinchan Kim 
2281b91ac374SJohannes Weiner static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2282b91ac374SJohannes Weiner 				 struct lruvec *lruvec, struct scan_control *sc)
2283b91ac374SJohannes Weiner {
2284b91ac374SJohannes Weiner 	if (is_active_lru(lru)) {
2285b91ac374SJohannes Weiner 		if (sc->may_deactivate & (1 << is_file_lru(lru)))
2286b91ac374SJohannes Weiner 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2287b91ac374SJohannes Weiner 		else
2288b91ac374SJohannes Weiner 			sc->skipped_deactivate = 1;
2289b91ac374SJohannes Weiner 		return 0;
2290b91ac374SJohannes Weiner 	}
2291b91ac374SJohannes Weiner 
2292b91ac374SJohannes Weiner 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2293b91ac374SJohannes Weiner }
2294b91ac374SJohannes Weiner 
229559dc76b0SRik van Riel /*
229659dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
229759dc76b0SRik van Riel  * to do too much work.
229814797e23SKOSAKI Motohiro  *
229959dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
230059dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
230159dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
230259dc76b0SRik van Riel  *
230359dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
230459dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
230559dc76b0SRik van Riel  *
23062a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
23072a2e4885SJohannes Weiner  *
230859dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
23093a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
231059dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
231159dc76b0SRik van Riel  *
231259dc76b0SRik van Riel  * total     target    max
231359dc76b0SRik van Riel  * memory    ratio     inactive
231459dc76b0SRik van Riel  * -------------------------------------
231559dc76b0SRik van Riel  *   10MB       1         5MB
231659dc76b0SRik van Riel  *  100MB       1        50MB
231759dc76b0SRik van Riel  *    1GB       3       250MB
231859dc76b0SRik van Riel  *   10GB      10       0.9GB
231959dc76b0SRik van Riel  *  100GB      31         3GB
232059dc76b0SRik van Riel  *    1TB     101        10GB
232159dc76b0SRik van Riel  *   10TB     320        32GB
232214797e23SKOSAKI Motohiro  */
2323b91ac374SJohannes Weiner static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
232414797e23SKOSAKI Motohiro {
2325b91ac374SJohannes Weiner 	enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
23262a2e4885SJohannes Weiner 	unsigned long inactive, active;
23272a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
232859dc76b0SRik van Riel 	unsigned long gb;
232959dc76b0SRik van Riel 
2330b91ac374SJohannes Weiner 	inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2331b91ac374SJohannes Weiner 	active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2332f8d1a311SMel Gorman 
233359dc76b0SRik van Riel 	gb = (inactive + active) >> (30 - PAGE_SHIFT);
23344002570cSJoonsoo Kim 	if (gb)
233559dc76b0SRik van Riel 		inactive_ratio = int_sqrt(10 * gb);
2336b39415b2SRik van Riel 	else
233759dc76b0SRik van Riel 		inactive_ratio = 1;
2338fd538803SMichal Hocko 
233959dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2340b39415b2SRik van Riel }
2341b39415b2SRik van Riel 
23429a265114SJohannes Weiner enum scan_balance {
23439a265114SJohannes Weiner 	SCAN_EQUAL,
23449a265114SJohannes Weiner 	SCAN_FRACT,
23459a265114SJohannes Weiner 	SCAN_ANON,
23469a265114SJohannes Weiner 	SCAN_FILE,
23479a265114SJohannes Weiner };
23489a265114SJohannes Weiner 
23491da177e4SLinus Torvalds /*
23504f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
23514f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
23524f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
23534f98a2feSRik van Riel  * onto the active list instead of evict.
23544f98a2feSRik van Riel  *
2355be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2356be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
23574f98a2feSRik van Riel  */
2358afaf07a6SJohannes Weiner static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2359afaf07a6SJohannes Weiner 			   unsigned long *nr)
23604f98a2feSRik van Riel {
2361afaf07a6SJohannes Weiner 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2362d483a5ddSJohannes Weiner 	unsigned long anon_cost, file_cost, total_cost;
236333377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
2364ed017373SYu Zhao 	u64 fraction[ANON_AND_FILE];
23659a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
23669a265114SJohannes Weiner 	enum scan_balance scan_balance;
23679a265114SJohannes Weiner 	unsigned long ap, fp;
23689a265114SJohannes Weiner 	enum lru_list lru;
236976a33fc3SShaohua Li 
237076a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2371d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
23729a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
237376a33fc3SShaohua Li 		goto out;
237476a33fc3SShaohua Li 	}
23754f98a2feSRik van Riel 
237610316b31SJohannes Weiner 	/*
237710316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
237810316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
237910316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
238010316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
238110316b31SJohannes Weiner 	 * too expensive.
238210316b31SJohannes Weiner 	 */
2383b5ead35eSJohannes Weiner 	if (cgroup_reclaim(sc) && !swappiness) {
23849a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
238510316b31SJohannes Weiner 		goto out;
238610316b31SJohannes Weiner 	}
238710316b31SJohannes Weiner 
238810316b31SJohannes Weiner 	/*
238910316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
239010316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
239110316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
239210316b31SJohannes Weiner 	 */
239302695175SJohannes Weiner 	if (!sc->priority && swappiness) {
23949a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
239510316b31SJohannes Weiner 		goto out;
239610316b31SJohannes Weiner 	}
239710316b31SJohannes Weiner 
239811d16c25SJohannes Weiner 	/*
239953138ceaSJohannes Weiner 	 * If the system is almost out of file pages, force-scan anon.
240062376251SJohannes Weiner 	 */
2401b91ac374SJohannes Weiner 	if (sc->file_is_tiny) {
240262376251SJohannes Weiner 		scan_balance = SCAN_ANON;
240362376251SJohannes Weiner 		goto out;
240462376251SJohannes Weiner 	}
240562376251SJohannes Weiner 
240662376251SJohannes Weiner 	/*
2407b91ac374SJohannes Weiner 	 * If there is enough inactive page cache, we do not reclaim
2408b91ac374SJohannes Weiner 	 * anything from the anonymous working right now.
2409e9868505SRik van Riel 	 */
2410b91ac374SJohannes Weiner 	if (sc->cache_trim_mode) {
24119a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2412e9868505SRik van Riel 		goto out;
24134f98a2feSRik van Riel 	}
24144f98a2feSRik van Riel 
24159a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
24164f98a2feSRik van Riel 	/*
2417314b57fbSJohannes Weiner 	 * Calculate the pressure balance between anon and file pages.
2418314b57fbSJohannes Weiner 	 *
2419314b57fbSJohannes Weiner 	 * The amount of pressure we put on each LRU is inversely
2420314b57fbSJohannes Weiner 	 * proportional to the cost of reclaiming each list, as
2421314b57fbSJohannes Weiner 	 * determined by the share of pages that are refaulting, times
2422314b57fbSJohannes Weiner 	 * the relative IO cost of bringing back a swapped out
2423314b57fbSJohannes Weiner 	 * anonymous page vs reloading a filesystem page (swappiness).
2424314b57fbSJohannes Weiner 	 *
2425d483a5ddSJohannes Weiner 	 * Although we limit that influence to ensure no list gets
2426d483a5ddSJohannes Weiner 	 * left behind completely: at least a third of the pressure is
2427d483a5ddSJohannes Weiner 	 * applied, before swappiness.
2428d483a5ddSJohannes Weiner 	 *
2429314b57fbSJohannes Weiner 	 * With swappiness at 100, anon and file have equal IO cost.
243058c37f6eSKOSAKI Motohiro 	 */
2431d483a5ddSJohannes Weiner 	total_cost = sc->anon_cost + sc->file_cost;
2432d483a5ddSJohannes Weiner 	anon_cost = total_cost + sc->anon_cost;
2433d483a5ddSJohannes Weiner 	file_cost = total_cost + sc->file_cost;
2434d483a5ddSJohannes Weiner 	total_cost = anon_cost + file_cost;
243558c37f6eSKOSAKI Motohiro 
2436d483a5ddSJohannes Weiner 	ap = swappiness * (total_cost + 1);
2437d483a5ddSJohannes Weiner 	ap /= anon_cost + 1;
24384f98a2feSRik van Riel 
2439d483a5ddSJohannes Weiner 	fp = (200 - swappiness) * (total_cost + 1);
2440d483a5ddSJohannes Weiner 	fp /= file_cost + 1;
24414f98a2feSRik van Riel 
244276a33fc3SShaohua Li 	fraction[0] = ap;
244376a33fc3SShaohua Li 	fraction[1] = fp;
2444a4fe1631SJohannes Weiner 	denominator = ap + fp;
244576a33fc3SShaohua Li out:
24464111304dSHugh Dickins 	for_each_evictable_lru(lru) {
24474111304dSHugh Dickins 		int file = is_file_lru(lru);
24489783aa99SChris Down 		unsigned long lruvec_size;
244976a33fc3SShaohua Li 		unsigned long scan;
24501bc63fb1SChris Down 		unsigned long protection;
245176a33fc3SShaohua Li 
24529783aa99SChris Down 		lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
245322f7496fSYafang Shao 		protection = mem_cgroup_protection(sc->target_mem_cgroup,
245422f7496fSYafang Shao 						   memcg,
24551bc63fb1SChris Down 						   sc->memcg_low_reclaim);
24569783aa99SChris Down 
24571bc63fb1SChris Down 		if (protection) {
24589783aa99SChris Down 			/*
24599783aa99SChris Down 			 * Scale a cgroup's reclaim pressure by proportioning
24609783aa99SChris Down 			 * its current usage to its memory.low or memory.min
24619783aa99SChris Down 			 * setting.
24629783aa99SChris Down 			 *
24639783aa99SChris Down 			 * This is important, as otherwise scanning aggression
24649783aa99SChris Down 			 * becomes extremely binary -- from nothing as we
24659783aa99SChris Down 			 * approach the memory protection threshold, to totally
24669783aa99SChris Down 			 * nominal as we exceed it.  This results in requiring
24679783aa99SChris Down 			 * setting extremely liberal protection thresholds. It
24689783aa99SChris Down 			 * also means we simply get no protection at all if we
24699783aa99SChris Down 			 * set it too low, which is not ideal.
24701bc63fb1SChris Down 			 *
24711bc63fb1SChris Down 			 * If there is any protection in place, we reduce scan
24721bc63fb1SChris Down 			 * pressure by how much of the total memory used is
24731bc63fb1SChris Down 			 * within protection thresholds.
24749783aa99SChris Down 			 *
24759de7ca46SChris Down 			 * There is one special case: in the first reclaim pass,
24769de7ca46SChris Down 			 * we skip over all groups that are within their low
24779de7ca46SChris Down 			 * protection. If that fails to reclaim enough pages to
24789de7ca46SChris Down 			 * satisfy the reclaim goal, we come back and override
24799de7ca46SChris Down 			 * the best-effort low protection. However, we still
24809de7ca46SChris Down 			 * ideally want to honor how well-behaved groups are in
24819de7ca46SChris Down 			 * that case instead of simply punishing them all
24829de7ca46SChris Down 			 * equally. As such, we reclaim them based on how much
24831bc63fb1SChris Down 			 * memory they are using, reducing the scan pressure
24841bc63fb1SChris Down 			 * again by how much of the total memory used is under
24851bc63fb1SChris Down 			 * hard protection.
24869783aa99SChris Down 			 */
24871bc63fb1SChris Down 			unsigned long cgroup_size = mem_cgroup_size(memcg);
24881bc63fb1SChris Down 
24891bc63fb1SChris Down 			/* Avoid TOCTOU with earlier protection check */
24901bc63fb1SChris Down 			cgroup_size = max(cgroup_size, protection);
24911bc63fb1SChris Down 
24921bc63fb1SChris Down 			scan = lruvec_size - lruvec_size * protection /
24931bc63fb1SChris Down 				cgroup_size;
24949783aa99SChris Down 
24959783aa99SChris Down 			/*
24961bc63fb1SChris Down 			 * Minimally target SWAP_CLUSTER_MAX pages to keep
249755b65a57SEthon Paul 			 * reclaim moving forwards, avoiding decrementing
24989de7ca46SChris Down 			 * sc->priority further than desirable.
24999783aa99SChris Down 			 */
25001bc63fb1SChris Down 			scan = max(scan, SWAP_CLUSTER_MAX);
25019783aa99SChris Down 		} else {
25029783aa99SChris Down 			scan = lruvec_size;
25039783aa99SChris Down 		}
25049783aa99SChris Down 
25059783aa99SChris Down 		scan >>= sc->priority;
25069783aa99SChris Down 
2507688035f7SJohannes Weiner 		/*
2508688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2509688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2510688035f7SJohannes Weiner 		 */
2511688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
25129783aa99SChris Down 			scan = min(lruvec_size, SWAP_CLUSTER_MAX);
25139a265114SJohannes Weiner 
25149a265114SJohannes Weiner 		switch (scan_balance) {
25159a265114SJohannes Weiner 		case SCAN_EQUAL:
25169a265114SJohannes Weiner 			/* Scan lists relative to size */
25179a265114SJohannes Weiner 			break;
25189a265114SJohannes Weiner 		case SCAN_FRACT:
25199a265114SJohannes Weiner 			/*
25209a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
25219a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
252276073c64SGavin Shan 			 * Make sure we don't miss the last page on
252376073c64SGavin Shan 			 * the offlined memory cgroups because of a
252476073c64SGavin Shan 			 * round-off error.
25259a265114SJohannes Weiner 			 */
252676073c64SGavin Shan 			scan = mem_cgroup_online(memcg) ?
252776073c64SGavin Shan 			       div64_u64(scan * fraction[file], denominator) :
252876073c64SGavin Shan 			       DIV64_U64_ROUND_UP(scan * fraction[file],
25296f04f48dSSuleiman Souhlal 						  denominator);
25309a265114SJohannes Weiner 			break;
25319a265114SJohannes Weiner 		case SCAN_FILE:
25329a265114SJohannes Weiner 		case SCAN_ANON:
25339a265114SJohannes Weiner 			/* Scan one type exclusively */
2534e072bff6SMateusz Nosek 			if ((scan_balance == SCAN_FILE) != file)
25359a265114SJohannes Weiner 				scan = 0;
25369a265114SJohannes Weiner 			break;
25379a265114SJohannes Weiner 		default:
25389a265114SJohannes Weiner 			/* Look ma, no brain */
25399a265114SJohannes Weiner 			BUG();
25409a265114SJohannes Weiner 		}
25416b4f7799SJohannes Weiner 
25424111304dSHugh Dickins 		nr[lru] = scan;
254376a33fc3SShaohua Li 	}
25446e08a369SWu Fengguang }
25454f98a2feSRik van Riel 
2546afaf07a6SJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
25479b4f98cdSJohannes Weiner {
25489b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2549e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
25509b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
25519b4f98cdSJohannes Weiner 	enum lru_list lru;
25529b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
25539b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
25549b4f98cdSJohannes Weiner 	struct blk_plug plug;
25551a501907SMel Gorman 	bool scan_adjusted;
25569b4f98cdSJohannes Weiner 
2557afaf07a6SJohannes Weiner 	get_scan_count(lruvec, sc, nr);
25589b4f98cdSJohannes Weiner 
2559e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2560e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2561e82e0561SMel Gorman 
25621a501907SMel Gorman 	/*
25631a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
25641a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
25651a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
25661a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
25671a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
25681a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
25691a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
25701a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
25711a501907SMel Gorman 	 * dropped to zero at the first pass.
25721a501907SMel Gorman 	 */
2573b5ead35eSJohannes Weiner 	scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
25741a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
25751a501907SMel Gorman 
25769b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
25779b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
25789b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2579e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2580e82e0561SMel Gorman 		unsigned long nr_scanned;
2581e82e0561SMel Gorman 
25829b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
25839b4f98cdSJohannes Weiner 			if (nr[lru]) {
25849b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
25859b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
25869b4f98cdSJohannes Weiner 
25879b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
25883b991208SJohannes Weiner 							    lruvec, sc);
25899b4f98cdSJohannes Weiner 			}
25909b4f98cdSJohannes Weiner 		}
2591e82e0561SMel Gorman 
2592bd041733SMichal Hocko 		cond_resched();
2593bd041733SMichal Hocko 
2594e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2595e82e0561SMel Gorman 			continue;
2596e82e0561SMel Gorman 
25979b4f98cdSJohannes Weiner 		/*
2598e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
25991a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2600e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2601e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2602e82e0561SMel Gorman 		 * proportional to the original scan target.
2603e82e0561SMel Gorman 		 */
2604e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2605e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2606e82e0561SMel Gorman 
26071a501907SMel Gorman 		/*
26081a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
26091a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
26101a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
26111a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
26121a501907SMel Gorman 		 */
26131a501907SMel Gorman 		if (!nr_file || !nr_anon)
26141a501907SMel Gorman 			break;
26151a501907SMel Gorman 
2616e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2617e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2618e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2619e82e0561SMel Gorman 			lru = LRU_BASE;
2620e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2621e82e0561SMel Gorman 		} else {
2622e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2623e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2624e82e0561SMel Gorman 			lru = LRU_FILE;
2625e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2626e82e0561SMel Gorman 		}
2627e82e0561SMel Gorman 
2628e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2629e82e0561SMel Gorman 		nr[lru] = 0;
2630e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2631e82e0561SMel Gorman 
2632e82e0561SMel Gorman 		/*
2633e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2634e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2635e82e0561SMel Gorman 		 */
2636e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2637e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2638e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2639e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2640e82e0561SMel Gorman 
2641e82e0561SMel Gorman 		lru += LRU_ACTIVE;
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 		scan_adjusted = true;
26479b4f98cdSJohannes Weiner 	}
26489b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
26499b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
26509b4f98cdSJohannes Weiner 
26519b4f98cdSJohannes Weiner 	/*
26529b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
26539b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
26549b4f98cdSJohannes Weiner 	 */
2655b91ac374SJohannes Weiner 	if (total_swap_pages && inactive_is_low(lruvec, LRU_INACTIVE_ANON))
26569b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
26579b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
26589b4f98cdSJohannes Weiner }
26599b4f98cdSJohannes Weiner 
266023b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
26619e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
266223b9da55SMel Gorman {
2663d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
266423b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
26659e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
266623b9da55SMel Gorman 		return true;
266723b9da55SMel Gorman 
266823b9da55SMel Gorman 	return false;
266923b9da55SMel Gorman }
267023b9da55SMel Gorman 
26714f98a2feSRik van Riel /*
267223b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
267323b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
267423b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
2675df3a45f9SQiwu Chen  * calls try_to_compact_pages() that it will have enough free pages to succeed.
267623b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
26773e7d3449SMel Gorman  */
2678a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
26793e7d3449SMel Gorman 					unsigned long nr_reclaimed,
26803e7d3449SMel Gorman 					struct scan_control *sc)
26813e7d3449SMel Gorman {
26823e7d3449SMel Gorman 	unsigned long pages_for_compaction;
26833e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2684a9dd0a83SMel Gorman 	int z;
26853e7d3449SMel Gorman 
26863e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
26879e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
26883e7d3449SMel Gorman 		return false;
26893e7d3449SMel Gorman 
26903e7d3449SMel Gorman 	/*
26915ee04716SVlastimil Babka 	 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
26925ee04716SVlastimil Babka 	 * number of pages that were scanned. This will return to the caller
26935ee04716SVlastimil Babka 	 * with the risk reclaim/compaction and the resulting allocation attempt
26945ee04716SVlastimil Babka 	 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
26955ee04716SVlastimil Babka 	 * allocations through requiring that the full LRU list has been scanned
26965ee04716SVlastimil Babka 	 * first, by assuming that zero delta of sc->nr_scanned means full LRU
26975ee04716SVlastimil Babka 	 * scan, but that approximation was wrong, and there were corner cases
26985ee04716SVlastimil Babka 	 * where always a non-zero amount of pages were scanned.
26992876592fSMel Gorman 	 */
27002876592fSMel Gorman 	if (!nr_reclaimed)
27012876592fSMel Gorman 		return false;
27023e7d3449SMel Gorman 
27033e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2704a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2705a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
27066aa303deSMel Gorman 		if (!managed_zone(zone))
2707a9dd0a83SMel Gorman 			continue;
2708a9dd0a83SMel Gorman 
2709a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2710cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
27113e7d3449SMel Gorman 		case COMPACT_CONTINUE:
27123e7d3449SMel Gorman 			return false;
27133e7d3449SMel Gorman 		default:
2714a9dd0a83SMel Gorman 			/* check next zone */
2715a9dd0a83SMel Gorman 			;
27163e7d3449SMel Gorman 		}
27173e7d3449SMel Gorman 	}
27181c6c1597SHillf Danton 
27191c6c1597SHillf Danton 	/*
27201c6c1597SHillf Danton 	 * If we have not reclaimed enough pages for compaction and the
27211c6c1597SHillf Danton 	 * inactive lists are large enough, continue reclaiming
27221c6c1597SHillf Danton 	 */
27231c6c1597SHillf Danton 	pages_for_compaction = compact_gap(sc->order);
27241c6c1597SHillf Danton 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
27251c6c1597SHillf Danton 	if (get_nr_swap_pages() > 0)
27261c6c1597SHillf Danton 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
27271c6c1597SHillf Danton 
27285ee04716SVlastimil Babka 	return inactive_lru_pages > pages_for_compaction;
2729a9dd0a83SMel Gorman }
27303e7d3449SMel Gorman 
27310f6a5cffSJohannes Weiner static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
2732f16015fbSJohannes Weiner {
27330f6a5cffSJohannes Weiner 	struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
2734694fbc0fSAndrew Morton 	struct mem_cgroup *memcg;
2735d108c772SAndrey Ryabinin 
27360f6a5cffSJohannes Weiner 	memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
2737694fbc0fSAndrew Morton 	do {
2738afaf07a6SJohannes Weiner 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
27398e8ae645SJohannes Weiner 		unsigned long reclaimed;
2740cb731d6cSVladimir Davydov 		unsigned long scanned;
27419b4f98cdSJohannes Weiner 
2742e3336cabSXunlei Pang 		/*
2743e3336cabSXunlei Pang 		 * This loop can become CPU-bound when target memcgs
2744e3336cabSXunlei Pang 		 * aren't eligible for reclaim - either because they
2745e3336cabSXunlei Pang 		 * don't have any reclaimable pages, or because their
2746e3336cabSXunlei Pang 		 * memory is explicitly protected. Avoid soft lockups.
2747e3336cabSXunlei Pang 		 */
2748e3336cabSXunlei Pang 		cond_resched();
2749e3336cabSXunlei Pang 
275045c7f7e1SChris Down 		mem_cgroup_calculate_protection(target_memcg, memcg);
275145c7f7e1SChris Down 
275245c7f7e1SChris Down 		if (mem_cgroup_below_min(memcg)) {
2753bf8d5d52SRoman Gushchin 			/*
2754bf8d5d52SRoman Gushchin 			 * Hard protection.
2755bf8d5d52SRoman Gushchin 			 * If there is no reclaimable memory, OOM.
2756bf8d5d52SRoman Gushchin 			 */
2757bf8d5d52SRoman Gushchin 			continue;
275845c7f7e1SChris Down 		} else if (mem_cgroup_below_low(memcg)) {
2759bf8d5d52SRoman Gushchin 			/*
2760bf8d5d52SRoman Gushchin 			 * Soft protection.
2761bf8d5d52SRoman Gushchin 			 * Respect the protection only as long as
2762bf8d5d52SRoman Gushchin 			 * there is an unprotected supply
2763bf8d5d52SRoman Gushchin 			 * of reclaimable memory from other cgroups.
2764bf8d5d52SRoman Gushchin 			 */
2765d6622f63SYisheng Xie 			if (!sc->memcg_low_reclaim) {
2766d6622f63SYisheng Xie 				sc->memcg_low_skipped = 1;
2767241994edSJohannes Weiner 				continue;
2768d6622f63SYisheng Xie 			}
2769e27be240SJohannes Weiner 			memcg_memory_event(memcg, MEMCG_LOW);
2770241994edSJohannes Weiner 		}
2771241994edSJohannes Weiner 
27728e8ae645SJohannes Weiner 		reclaimed = sc->nr_reclaimed;
2773cb731d6cSVladimir Davydov 		scanned = sc->nr_scanned;
2774afaf07a6SJohannes Weiner 
2775afaf07a6SJohannes Weiner 		shrink_lruvec(lruvec, sc);
2776f9be23d6SKonstantin Khlebnikov 
277728360f39SMel Gorman 		shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
277828360f39SMel Gorman 			    sc->priority);
2779cb731d6cSVladimir Davydov 
27808e8ae645SJohannes Weiner 		/* Record the group's reclaim efficiency */
27818e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, memcg, false,
27828e8ae645SJohannes Weiner 			   sc->nr_scanned - scanned,
27838e8ae645SJohannes Weiner 			   sc->nr_reclaimed - reclaimed);
27848e8ae645SJohannes Weiner 
27850f6a5cffSJohannes Weiner 	} while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
27860f6a5cffSJohannes Weiner }
27870f6a5cffSJohannes Weiner 
27886c9e0907SLiu Song static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
27890f6a5cffSJohannes Weiner {
27900f6a5cffSJohannes Weiner 	struct reclaim_state *reclaim_state = current->reclaim_state;
27910f6a5cffSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
27921b05117dSJohannes Weiner 	struct lruvec *target_lruvec;
27930f6a5cffSJohannes Weiner 	bool reclaimable = false;
2794b91ac374SJohannes Weiner 	unsigned long file;
27950f6a5cffSJohannes Weiner 
27961b05117dSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
27971b05117dSJohannes Weiner 
27980f6a5cffSJohannes Weiner again:
27990f6a5cffSJohannes Weiner 	memset(&sc->nr, 0, sizeof(sc->nr));
28000f6a5cffSJohannes Weiner 
28010f6a5cffSJohannes Weiner 	nr_reclaimed = sc->nr_reclaimed;
28020f6a5cffSJohannes Weiner 	nr_scanned = sc->nr_scanned;
28030f6a5cffSJohannes Weiner 
280453138ceaSJohannes Weiner 	/*
28057cf111bcSJohannes Weiner 	 * Determine the scan balance between anon and file LRUs.
28067cf111bcSJohannes Weiner 	 */
28076168d0daSAlex Shi 	spin_lock_irq(&target_lruvec->lru_lock);
28087cf111bcSJohannes Weiner 	sc->anon_cost = target_lruvec->anon_cost;
28097cf111bcSJohannes Weiner 	sc->file_cost = target_lruvec->file_cost;
28106168d0daSAlex Shi 	spin_unlock_irq(&target_lruvec->lru_lock);
28117cf111bcSJohannes Weiner 
28127cf111bcSJohannes Weiner 	/*
2813b91ac374SJohannes Weiner 	 * Target desirable inactive:active list ratios for the anon
2814b91ac374SJohannes Weiner 	 * and file LRU lists.
2815b91ac374SJohannes Weiner 	 */
2816b91ac374SJohannes Weiner 	if (!sc->force_deactivate) {
2817b91ac374SJohannes Weiner 		unsigned long refaults;
2818b91ac374SJohannes Weiner 
2819170b04b7SJoonsoo Kim 		refaults = lruvec_page_state(target_lruvec,
2820170b04b7SJoonsoo Kim 				WORKINGSET_ACTIVATE_ANON);
2821170b04b7SJoonsoo Kim 		if (refaults != target_lruvec->refaults[0] ||
2822170b04b7SJoonsoo Kim 			inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2823b91ac374SJohannes Weiner 			sc->may_deactivate |= DEACTIVATE_ANON;
2824b91ac374SJohannes Weiner 		else
2825b91ac374SJohannes Weiner 			sc->may_deactivate &= ~DEACTIVATE_ANON;
2826b91ac374SJohannes Weiner 
2827b91ac374SJohannes Weiner 		/*
2828b91ac374SJohannes Weiner 		 * When refaults are being observed, it means a new
2829b91ac374SJohannes Weiner 		 * workingset is being established. Deactivate to get
2830b91ac374SJohannes Weiner 		 * rid of any stale active pages quickly.
2831b91ac374SJohannes Weiner 		 */
2832b91ac374SJohannes Weiner 		refaults = lruvec_page_state(target_lruvec,
2833170b04b7SJoonsoo Kim 				WORKINGSET_ACTIVATE_FILE);
2834170b04b7SJoonsoo Kim 		if (refaults != target_lruvec->refaults[1] ||
2835b91ac374SJohannes Weiner 		    inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2836b91ac374SJohannes Weiner 			sc->may_deactivate |= DEACTIVATE_FILE;
2837b91ac374SJohannes Weiner 		else
2838b91ac374SJohannes Weiner 			sc->may_deactivate &= ~DEACTIVATE_FILE;
2839b91ac374SJohannes Weiner 	} else
2840b91ac374SJohannes Weiner 		sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2841b91ac374SJohannes Weiner 
2842b91ac374SJohannes Weiner 	/*
2843b91ac374SJohannes Weiner 	 * If we have plenty of inactive file pages that aren't
2844b91ac374SJohannes Weiner 	 * thrashing, try to reclaim those first before touching
2845b91ac374SJohannes Weiner 	 * anonymous pages.
2846b91ac374SJohannes Weiner 	 */
2847b91ac374SJohannes Weiner 	file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2848b91ac374SJohannes Weiner 	if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2849b91ac374SJohannes Weiner 		sc->cache_trim_mode = 1;
2850b91ac374SJohannes Weiner 	else
2851b91ac374SJohannes Weiner 		sc->cache_trim_mode = 0;
2852b91ac374SJohannes Weiner 
2853b91ac374SJohannes Weiner 	/*
285453138ceaSJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
285553138ceaSJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
285653138ceaSJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
285753138ceaSJohannes Weiner 	 * shrinks, so does the window for rotation from references.
285853138ceaSJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
285953138ceaSJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
286053138ceaSJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
286153138ceaSJohannes Weiner 	 */
286253138ceaSJohannes Weiner 	if (!cgroup_reclaim(sc)) {
286353138ceaSJohannes Weiner 		unsigned long total_high_wmark = 0;
2864b91ac374SJohannes Weiner 		unsigned long free, anon;
2865b91ac374SJohannes Weiner 		int z;
286653138ceaSJohannes Weiner 
286753138ceaSJohannes Weiner 		free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
286853138ceaSJohannes Weiner 		file = node_page_state(pgdat, NR_ACTIVE_FILE) +
286953138ceaSJohannes Weiner 			   node_page_state(pgdat, NR_INACTIVE_FILE);
287053138ceaSJohannes Weiner 
287153138ceaSJohannes Weiner 		for (z = 0; z < MAX_NR_ZONES; z++) {
287253138ceaSJohannes Weiner 			struct zone *zone = &pgdat->node_zones[z];
287353138ceaSJohannes Weiner 			if (!managed_zone(zone))
287453138ceaSJohannes Weiner 				continue;
287553138ceaSJohannes Weiner 
287653138ceaSJohannes Weiner 			total_high_wmark += high_wmark_pages(zone);
287753138ceaSJohannes Weiner 		}
287853138ceaSJohannes Weiner 
2879b91ac374SJohannes Weiner 		/*
2880b91ac374SJohannes Weiner 		 * Consider anon: if that's low too, this isn't a
2881b91ac374SJohannes Weiner 		 * runaway file reclaim problem, but rather just
2882b91ac374SJohannes Weiner 		 * extreme pressure. Reclaim as per usual then.
2883b91ac374SJohannes Weiner 		 */
2884b91ac374SJohannes Weiner 		anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2885b91ac374SJohannes Weiner 
2886b91ac374SJohannes Weiner 		sc->file_is_tiny =
2887b91ac374SJohannes Weiner 			file + free <= total_high_wmark &&
2888b91ac374SJohannes Weiner 			!(sc->may_deactivate & DEACTIVATE_ANON) &&
2889b91ac374SJohannes Weiner 			anon >> sc->priority;
289053138ceaSJohannes Weiner 	}
289153138ceaSJohannes Weiner 
28920f6a5cffSJohannes Weiner 	shrink_node_memcgs(pgdat, sc);
289370ddf637SAnton Vorontsov 
28946b4f7799SJohannes Weiner 	if (reclaim_state) {
2895cb731d6cSVladimir Davydov 		sc->nr_reclaimed += reclaim_state->reclaimed_slab;
28966b4f7799SJohannes Weiner 		reclaim_state->reclaimed_slab = 0;
28976b4f7799SJohannes Weiner 	}
28986b4f7799SJohannes Weiner 
28998e8ae645SJohannes Weiner 	/* Record the subtree's reclaim efficiency */
29001b05117dSJohannes Weiner 	vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
290170ddf637SAnton Vorontsov 		   sc->nr_scanned - nr_scanned,
290270ddf637SAnton Vorontsov 		   sc->nr_reclaimed - nr_reclaimed);
290370ddf637SAnton Vorontsov 
29042344d7e4SJohannes Weiner 	if (sc->nr_reclaimed - nr_reclaimed)
29052344d7e4SJohannes Weiner 		reclaimable = true;
29062344d7e4SJohannes Weiner 
2907e3c1ac58SAndrey Ryabinin 	if (current_is_kswapd()) {
2908d108c772SAndrey Ryabinin 		/*
2909e3c1ac58SAndrey Ryabinin 		 * If reclaim is isolating dirty pages under writeback,
2910e3c1ac58SAndrey Ryabinin 		 * it implies that the long-lived page allocation rate
2911e3c1ac58SAndrey Ryabinin 		 * is exceeding the page laundering rate. Either the
2912e3c1ac58SAndrey Ryabinin 		 * global limits are not being effective at throttling
2913e3c1ac58SAndrey Ryabinin 		 * processes due to the page distribution throughout
2914e3c1ac58SAndrey Ryabinin 		 * zones or there is heavy usage of a slow backing
2915e3c1ac58SAndrey Ryabinin 		 * device. The only option is to throttle from reclaim
2916e3c1ac58SAndrey Ryabinin 		 * context which is not ideal as there is no guarantee
2917d108c772SAndrey Ryabinin 		 * the dirtying process is throttled in the same way
2918d108c772SAndrey Ryabinin 		 * balance_dirty_pages() manages.
2919d108c772SAndrey Ryabinin 		 *
2920e3c1ac58SAndrey Ryabinin 		 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
2921e3c1ac58SAndrey Ryabinin 		 * count the number of pages under pages flagged for
2922e3c1ac58SAndrey Ryabinin 		 * immediate reclaim and stall if any are encountered
2923e3c1ac58SAndrey Ryabinin 		 * in the nr_immediate check below.
2924d108c772SAndrey Ryabinin 		 */
2925d108c772SAndrey Ryabinin 		if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
2926d108c772SAndrey Ryabinin 			set_bit(PGDAT_WRITEBACK, &pgdat->flags);
2927d108c772SAndrey Ryabinin 
2928d108c772SAndrey Ryabinin 		/* Allow kswapd to start writing pages during reclaim.*/
2929d108c772SAndrey Ryabinin 		if (sc->nr.unqueued_dirty == sc->nr.file_taken)
2930d108c772SAndrey Ryabinin 			set_bit(PGDAT_DIRTY, &pgdat->flags);
2931d108c772SAndrey Ryabinin 
2932d108c772SAndrey Ryabinin 		/*
29331eba09c1SRandy Dunlap 		 * If kswapd scans pages marked for immediate
2934d108c772SAndrey Ryabinin 		 * reclaim and under writeback (nr_immediate), it
2935d108c772SAndrey Ryabinin 		 * implies that pages are cycling through the LRU
2936d108c772SAndrey Ryabinin 		 * faster than they are written so also forcibly stall.
2937d108c772SAndrey Ryabinin 		 */
2938d108c772SAndrey Ryabinin 		if (sc->nr.immediate)
2939d108c772SAndrey Ryabinin 			congestion_wait(BLK_RW_ASYNC, HZ/10);
2940d108c772SAndrey Ryabinin 	}
2941d108c772SAndrey Ryabinin 
2942d108c772SAndrey Ryabinin 	/*
29431b05117dSJohannes Weiner 	 * Tag a node/memcg as congested if all the dirty pages
29441b05117dSJohannes Weiner 	 * scanned were backed by a congested BDI and
29451b05117dSJohannes Weiner 	 * wait_iff_congested will stall.
29461b05117dSJohannes Weiner 	 *
2947e3c1ac58SAndrey Ryabinin 	 * Legacy memcg will stall in page writeback so avoid forcibly
2948e3c1ac58SAndrey Ryabinin 	 * stalling in wait_iff_congested().
2949e3c1ac58SAndrey Ryabinin 	 */
29501b05117dSJohannes Weiner 	if ((current_is_kswapd() ||
29511b05117dSJohannes Weiner 	     (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
2952e3c1ac58SAndrey Ryabinin 	    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
29531b05117dSJohannes Weiner 		set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
2954e3c1ac58SAndrey Ryabinin 
2955e3c1ac58SAndrey Ryabinin 	/*
2956d108c772SAndrey Ryabinin 	 * Stall direct reclaim for IO completions if underlying BDIs
2957d108c772SAndrey Ryabinin 	 * and node is congested. Allow kswapd to continue until it
2958d108c772SAndrey Ryabinin 	 * starts encountering unqueued dirty pages or cycling through
2959d108c772SAndrey Ryabinin 	 * the LRU too quickly.
2960d108c772SAndrey Ryabinin 	 */
29611b05117dSJohannes Weiner 	if (!current_is_kswapd() && current_may_throttle() &&
29621b05117dSJohannes Weiner 	    !sc->hibernation_mode &&
29631b05117dSJohannes Weiner 	    test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
2964e3c1ac58SAndrey Ryabinin 		wait_iff_congested(BLK_RW_ASYNC, HZ/10);
2965d108c772SAndrey Ryabinin 
2966d2af3397SJohannes Weiner 	if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
2967d2af3397SJohannes Weiner 				    sc))
2968d2af3397SJohannes Weiner 		goto again;
29692344d7e4SJohannes Weiner 
2970c73322d0SJohannes Weiner 	/*
2971c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
2972c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
2973c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
2974c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
2975c73322d0SJohannes Weiner 	 */
2976c73322d0SJohannes Weiner 	if (reclaimable)
2977c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
2978f16015fbSJohannes Weiner }
2979f16015fbSJohannes Weiner 
298053853e2dSVlastimil Babka /*
2981fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
2982fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
2983fdd4c614SVlastimil Babka  * should reclaim first.
298453853e2dSVlastimil Babka  */
29854f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2986fe4b1b24SMel Gorman {
298731483b6aSMel Gorman 	unsigned long watermark;
2988fdd4c614SVlastimil Babka 	enum compact_result suitable;
2989fe4b1b24SMel Gorman 
2990fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2991fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
2992fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
2993fdd4c614SVlastimil Babka 		return true;
2994fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
2995fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
2996fe4b1b24SMel Gorman 		return false;
2997fe4b1b24SMel Gorman 
2998fdd4c614SVlastimil Babka 	/*
2999fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
3000fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
3001fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
3002fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
3003fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
3004fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
3005fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
3006fdd4c614SVlastimil Babka 	 */
3007fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
3008fdd4c614SVlastimil Babka 
3009fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
3010fe4b1b24SMel Gorman }
3011fe4b1b24SMel Gorman 
30121da177e4SLinus Torvalds /*
30131da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
30141da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
30151da177e4SLinus Torvalds  * request.
30161da177e4SLinus Torvalds  *
30171da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
30181da177e4SLinus Torvalds  * scan then give up on it.
30191da177e4SLinus Torvalds  */
30200a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
30211da177e4SLinus Torvalds {
3022dd1a239fSMel Gorman 	struct zoneref *z;
302354a6eb5cSMel Gorman 	struct zone *zone;
30240608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
30250608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3026619d0d76SWeijie Yang 	gfp_t orig_mask;
302779dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
30281cfb419bSKAMEZAWA Hiroyuki 
3029cc715d99SMel Gorman 	/*
3030cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
3031cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
3032cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
3033cc715d99SMel Gorman 	 */
3034619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
3035b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
3036cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
30374f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
3038b2e18757SMel Gorman 	}
3039cc715d99SMel Gorman 
3040d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
3041b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
3042b2e18757SMel Gorman 		/*
30431cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
30441cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
30451cfb419bSKAMEZAWA Hiroyuki 		 */
3046b5ead35eSJohannes Weiner 		if (!cgroup_reclaim(sc)) {
3047344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
3048344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
30491da177e4SLinus Torvalds 				continue;
305065ec02cbSVladimir Davydov 
3051e0887c19SRik van Riel 			/*
3052e0c23279SMel Gorman 			 * If we already have plenty of memory free for
3053e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
3054e0c23279SMel Gorman 			 * Even though compaction is invoked for any
3055e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
3056e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
3057c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
3058c7cfa37bSCopot Alexandru 			 * page allocations.
3059e0887c19SRik van Riel 			 */
30600b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
30610b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
30624f588331SMel Gorman 			    compaction_ready(zone, sc)) {
30630b06496aSJohannes Weiner 				sc->compaction_ready = true;
3064e0887c19SRik van Riel 				continue;
3065e0887c19SRik van Riel 			}
30660b06496aSJohannes Weiner 
30670608f43dSAndrew Morton 			/*
306879dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
306979dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
307079dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
307179dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
307279dafcdcSMel Gorman 			 */
307379dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
307479dafcdcSMel Gorman 				continue;
307579dafcdcSMel Gorman 
307679dafcdcSMel Gorman 			/*
30770608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
30780608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
30790608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
30800608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
30810608f43dSAndrew Morton 			 */
30820608f43dSAndrew Morton 			nr_soft_scanned = 0;
3083ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
30840608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
30850608f43dSAndrew Morton 						&nr_soft_scanned);
30860608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
30870608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
3088ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
3089ac34a1a3SKAMEZAWA Hiroyuki 		}
3090d149e3b2SYing Han 
309179dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
309279dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
309379dafcdcSMel Gorman 			continue;
309479dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
3095970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
30961da177e4SLinus Torvalds 	}
3097e0c23279SMel Gorman 
309865ec02cbSVladimir Davydov 	/*
3099619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
3100619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
3101619d0d76SWeijie Yang 	 */
3102619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
31031da177e4SLinus Torvalds }
31041da177e4SLinus Torvalds 
3105b910718aSJohannes Weiner static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
31062a2e4885SJohannes Weiner {
3107b910718aSJohannes Weiner 	struct lruvec *target_lruvec;
31082a2e4885SJohannes Weiner 	unsigned long refaults;
31092a2e4885SJohannes Weiner 
3110b910718aSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
3111170b04b7SJoonsoo Kim 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
3112170b04b7SJoonsoo Kim 	target_lruvec->refaults[0] = refaults;
3113170b04b7SJoonsoo Kim 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
3114170b04b7SJoonsoo Kim 	target_lruvec->refaults[1] = refaults;
31152a2e4885SJohannes Weiner }
31162a2e4885SJohannes Weiner 
31171da177e4SLinus Torvalds /*
31181da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
31191da177e4SLinus Torvalds  *
31201da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
31211da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
31221da177e4SLinus Torvalds  *
31231da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
31241da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
31255b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
31265b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
31275b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
31285b0830cbSJens Axboe  * work, and the allocation attempt will fail.
3129a41f24eaSNishanth Aravamudan  *
3130a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
3131a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
31321da177e4SLinus Torvalds  */
3133dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
31343115cd91SVladimir Davydov 					  struct scan_control *sc)
31351da177e4SLinus Torvalds {
3136241994edSJohannes Weiner 	int initial_priority = sc->priority;
31372a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
31382a2e4885SJohannes Weiner 	struct zoneref *z;
31392a2e4885SJohannes Weiner 	struct zone *zone;
3140241994edSJohannes Weiner retry:
3141873b4771SKeika Kobayashi 	delayacct_freepages_start();
3142873b4771SKeika Kobayashi 
3143b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
31447cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
31451da177e4SLinus Torvalds 
31469e3b2f8cSKonstantin Khlebnikov 	do {
314770ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
314870ddf637SAnton Vorontsov 				sc->priority);
314966e1707bSBalbir Singh 		sc->nr_scanned = 0;
31500a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
3151e0c23279SMel Gorman 
3152bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
31530b06496aSJohannes Weiner 			break;
31540b06496aSJohannes Weiner 
31550b06496aSJohannes Weiner 		if (sc->compaction_ready)
31560b06496aSJohannes Weiner 			break;
31571da177e4SLinus Torvalds 
31581da177e4SLinus Torvalds 		/*
31590e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
31600e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
31610e50ce3bSMinchan Kim 		 */
31620e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
31630e50ce3bSMinchan Kim 			sc->may_writepage = 1;
31640b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
3165bb21c7ceSKOSAKI Motohiro 
31662a2e4885SJohannes Weiner 	last_pgdat = NULL;
31672a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
31682a2e4885SJohannes Weiner 					sc->nodemask) {
31692a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
31702a2e4885SJohannes Weiner 			continue;
31712a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
31721b05117dSJohannes Weiner 
31732a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
31741b05117dSJohannes Weiner 
31751b05117dSJohannes Weiner 		if (cgroup_reclaim(sc)) {
31761b05117dSJohannes Weiner 			struct lruvec *lruvec;
31771b05117dSJohannes Weiner 
31781b05117dSJohannes Weiner 			lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
31791b05117dSJohannes Weiner 						   zone->zone_pgdat);
31801b05117dSJohannes Weiner 			clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
31811b05117dSJohannes Weiner 		}
31822a2e4885SJohannes Weiner 	}
31832a2e4885SJohannes Weiner 
3184873b4771SKeika Kobayashi 	delayacct_freepages_end();
3185873b4771SKeika Kobayashi 
3186bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
3187bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
3188bb21c7ceSKOSAKI Motohiro 
31890cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
31900b06496aSJohannes Weiner 	if (sc->compaction_ready)
31917335084dSMel Gorman 		return 1;
31927335084dSMel Gorman 
3193b91ac374SJohannes Weiner 	/*
3194b91ac374SJohannes Weiner 	 * We make inactive:active ratio decisions based on the node's
3195b91ac374SJohannes Weiner 	 * composition of memory, but a restrictive reclaim_idx or a
3196b91ac374SJohannes Weiner 	 * memory.low cgroup setting can exempt large amounts of
3197b91ac374SJohannes Weiner 	 * memory from reclaim. Neither of which are very common, so
3198b91ac374SJohannes Weiner 	 * instead of doing costly eligibility calculations of the
3199b91ac374SJohannes Weiner 	 * entire cgroup subtree up front, we assume the estimates are
3200b91ac374SJohannes Weiner 	 * good, and retry with forcible deactivation if that fails.
3201b91ac374SJohannes Weiner 	 */
3202b91ac374SJohannes Weiner 	if (sc->skipped_deactivate) {
3203b91ac374SJohannes Weiner 		sc->priority = initial_priority;
3204b91ac374SJohannes Weiner 		sc->force_deactivate = 1;
3205b91ac374SJohannes Weiner 		sc->skipped_deactivate = 0;
3206b91ac374SJohannes Weiner 		goto retry;
3207b91ac374SJohannes Weiner 	}
3208b91ac374SJohannes Weiner 
3209241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
3210d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
3211241994edSJohannes Weiner 		sc->priority = initial_priority;
3212b91ac374SJohannes Weiner 		sc->force_deactivate = 0;
3213d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
3214d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
3215241994edSJohannes Weiner 		goto retry;
3216241994edSJohannes Weiner 	}
3217241994edSJohannes Weiner 
3218bb21c7ceSKOSAKI Motohiro 	return 0;
32191da177e4SLinus Torvalds }
32201da177e4SLinus Torvalds 
3221c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
32225515061dSMel Gorman {
32235515061dSMel Gorman 	struct zone *zone;
32245515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
32255515061dSMel Gorman 	unsigned long free_pages = 0;
32265515061dSMel Gorman 	int i;
32275515061dSMel Gorman 	bool wmark_ok;
32285515061dSMel Gorman 
3229c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3230c73322d0SJohannes Weiner 		return true;
3231c73322d0SJohannes Weiner 
32325515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
32335515061dSMel Gorman 		zone = &pgdat->node_zones[i];
3234d450abd8SJohannes Weiner 		if (!managed_zone(zone))
3235d450abd8SJohannes Weiner 			continue;
3236d450abd8SJohannes Weiner 
3237d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
3238675becceSMel Gorman 			continue;
3239675becceSMel Gorman 
32405515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
32415515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
32425515061dSMel Gorman 	}
32435515061dSMel Gorman 
3244675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
3245675becceSMel Gorman 	if (!pfmemalloc_reserve)
3246675becceSMel Gorman 		return true;
3247675becceSMel Gorman 
32485515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
32495515061dSMel Gorman 
32505515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
32515515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
325297a225e6SJoonsoo Kim 		if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
325397a225e6SJoonsoo Kim 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
32545644e1fbSQian Cai 
32555515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
32565515061dSMel Gorman 	}
32575515061dSMel Gorman 
32585515061dSMel Gorman 	return wmark_ok;
32595515061dSMel Gorman }
32605515061dSMel Gorman 
32615515061dSMel Gorman /*
32625515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
32635515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
32645515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
326550694c28SMel Gorman  * when the low watermark is reached.
326650694c28SMel Gorman  *
326750694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
326850694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
32695515061dSMel Gorman  */
327050694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
32715515061dSMel Gorman 					nodemask_t *nodemask)
32725515061dSMel Gorman {
3273675becceSMel Gorman 	struct zoneref *z;
32745515061dSMel Gorman 	struct zone *zone;
3275675becceSMel Gorman 	pg_data_t *pgdat = NULL;
32765515061dSMel Gorman 
32775515061dSMel Gorman 	/*
32785515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
32795515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
32805515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
32815515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
32825515061dSMel Gorman 	 * processes to block on log_wait_commit().
32835515061dSMel Gorman 	 */
32845515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
328550694c28SMel Gorman 		goto out;
328650694c28SMel Gorman 
328750694c28SMel Gorman 	/*
328850694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
328950694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
329050694c28SMel Gorman 	 */
329150694c28SMel Gorman 	if (fatal_signal_pending(current))
329250694c28SMel Gorman 		goto out;
32935515061dSMel Gorman 
3294675becceSMel Gorman 	/*
3295675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
3296675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3297675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
3298675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
3299675becceSMel Gorman 	 *
3300675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
3301675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
3302675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
3303675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
3304675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
3305675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
3306675becceSMel Gorman 	 * should make reasonable progress.
3307675becceSMel Gorman 	 */
3308675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
330917636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
3310675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
3311675becceSMel Gorman 			continue;
3312675becceSMel Gorman 
3313675becceSMel Gorman 		/* Throttle based on the first usable node */
33145515061dSMel Gorman 		pgdat = zone->zone_pgdat;
3315c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
331650694c28SMel Gorman 			goto out;
3317675becceSMel Gorman 		break;
3318675becceSMel Gorman 	}
3319675becceSMel Gorman 
3320675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
3321675becceSMel Gorman 	if (!pgdat)
3322675becceSMel Gorman 		goto out;
33235515061dSMel Gorman 
332468243e76SMel Gorman 	/* Account for the throttling */
332568243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
332668243e76SMel Gorman 
33275515061dSMel Gorman 	/*
33285515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
33295515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
33305515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
33315515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
33325515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
33335515061dSMel Gorman 	 * second before continuing.
33345515061dSMel Gorman 	 */
33355515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
33365515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3337c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
333850694c28SMel Gorman 
333950694c28SMel Gorman 		goto check_pending;
33405515061dSMel Gorman 	}
33415515061dSMel Gorman 
33425515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
33435515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3344c73322d0SJohannes Weiner 		allow_direct_reclaim(pgdat));
334550694c28SMel Gorman 
334650694c28SMel Gorman check_pending:
334750694c28SMel Gorman 	if (fatal_signal_pending(current))
334850694c28SMel Gorman 		return true;
334950694c28SMel Gorman 
335050694c28SMel Gorman out:
335150694c28SMel Gorman 	return false;
33525515061dSMel Gorman }
33535515061dSMel Gorman 
3354dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3355327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
335666e1707bSBalbir Singh {
335733906bc5SMel Gorman 	unsigned long nr_reclaimed;
335866e1707bSBalbir Singh 	struct scan_control sc = {
335922fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3360f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3361b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
3362ee814fe2SJohannes Weiner 		.order = order,
3363ee814fe2SJohannes Weiner 		.nodemask = nodemask,
3364ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
3365ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3366a6dc60f8SJohannes Weiner 		.may_unmap = 1,
33672e2e4259SKOSAKI Motohiro 		.may_swap = 1,
336866e1707bSBalbir Singh 	};
336966e1707bSBalbir Singh 
33705515061dSMel Gorman 	/*
3371bb451fdfSGreg Thelen 	 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3372bb451fdfSGreg Thelen 	 * Confirm they are large enough for max values.
3373bb451fdfSGreg Thelen 	 */
3374bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3375bb451fdfSGreg Thelen 	BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3376bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3377bb451fdfSGreg Thelen 
3378bb451fdfSGreg Thelen 	/*
337950694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
338050694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
338150694c28SMel Gorman 	 * point.
33825515061dSMel Gorman 	 */
3383f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
33845515061dSMel Gorman 		return 1;
33855515061dSMel Gorman 
33861732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
33873481c37fSYafang Shao 	trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
338833906bc5SMel Gorman 
33893115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
339033906bc5SMel Gorman 
339133906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
33921732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
339333906bc5SMel Gorman 
339433906bc5SMel Gorman 	return nr_reclaimed;
339566e1707bSBalbir Singh }
339666e1707bSBalbir Singh 
3397c255a458SAndrew Morton #ifdef CONFIG_MEMCG
339866e1707bSBalbir Singh 
3399d2e5fb92SMichal Hocko /* Only used by soft limit reclaim. Do not reuse for anything else. */
3400a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
34014e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
3402ef8f2327SMel Gorman 						pg_data_t *pgdat,
34030ae5e89cSYing Han 						unsigned long *nr_scanned)
34044e416953SBalbir Singh {
3405afaf07a6SJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
34064e416953SBalbir Singh 	struct scan_control sc = {
3407b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3408ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
34094e416953SBalbir Singh 		.may_writepage = !laptop_mode,
34104e416953SBalbir Singh 		.may_unmap = 1,
3411b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
34124e416953SBalbir Singh 		.may_swap = !noswap,
34134e416953SBalbir Singh 	};
34140ae5e89cSYing Han 
3415d2e5fb92SMichal Hocko 	WARN_ON_ONCE(!current->reclaim_state);
3416d2e5fb92SMichal Hocko 
34174e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
34184e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3419bdce6d9eSKOSAKI Motohiro 
34209e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
34213481c37fSYafang Shao 						      sc.gfp_mask);
3422bdce6d9eSKOSAKI Motohiro 
34234e416953SBalbir Singh 	/*
34244e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
34254e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3426a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
34274e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
34284e416953SBalbir Singh 	 * the priority and make it zero.
34294e416953SBalbir Singh 	 */
3430afaf07a6SJohannes Weiner 	shrink_lruvec(lruvec, &sc);
3431bdce6d9eSKOSAKI Motohiro 
3432bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3433bdce6d9eSKOSAKI Motohiro 
34340ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
34350308f7cfSYafang Shao 
34364e416953SBalbir Singh 	return sc.nr_reclaimed;
34374e416953SBalbir Singh }
34384e416953SBalbir Singh 
343972835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3440b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
34418c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3442b70a2a21SJohannes Weiner 					   bool may_swap)
344366e1707bSBalbir Singh {
3444bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3445499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
344666e1707bSBalbir Singh 	struct scan_control sc = {
3447b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
34487dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3449ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3450b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3451ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3452ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
345366e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3454a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3455b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3456a09ed5e0SYing Han 	};
3457fa40d1eeSShakeel Butt 	/*
3458fa40d1eeSShakeel Butt 	 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
3459fa40d1eeSShakeel Butt 	 * equal pressure on all the nodes. This is based on the assumption that
3460fa40d1eeSShakeel Butt 	 * the reclaim does not bail out early.
3461fa40d1eeSShakeel Butt 	 */
3462fa40d1eeSShakeel Butt 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
346366e1707bSBalbir Singh 
34641732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
34653481c37fSYafang Shao 	trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
3466499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3467eb414681SJohannes Weiner 
34683115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3469eb414681SJohannes Weiner 
3470499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3471bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
34721732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3473bdce6d9eSKOSAKI Motohiro 
3474bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
347566e1707bSBalbir Singh }
347666e1707bSBalbir Singh #endif
347766e1707bSBalbir Singh 
34781d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3479ef8f2327SMel Gorman 				struct scan_control *sc)
3480f16015fbSJohannes Weiner {
3481b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3482b91ac374SJohannes Weiner 	struct lruvec *lruvec;
3483b95a2f2dSJohannes Weiner 
3484b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3485b95a2f2dSJohannes Weiner 		return;
3486b95a2f2dSJohannes Weiner 
3487b91ac374SJohannes Weiner 	lruvec = mem_cgroup_lruvec(NULL, pgdat);
3488b91ac374SJohannes Weiner 	if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
3489b91ac374SJohannes Weiner 		return;
3490b91ac374SJohannes Weiner 
3491b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3492b95a2f2dSJohannes Weiner 	do {
3493b91ac374SJohannes Weiner 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
34941a93be0eSKonstantin Khlebnikov 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
34959e3b2f8cSKonstantin Khlebnikov 				   sc, LRU_ACTIVE_ANON);
3496b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3497b95a2f2dSJohannes Weiner 	} while (memcg);
3498f16015fbSJohannes Weiner }
3499f16015fbSJohannes Weiner 
350097a225e6SJoonsoo Kim static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
35011c30844dSMel Gorman {
35021c30844dSMel Gorman 	int i;
35031c30844dSMel Gorman 	struct zone *zone;
35041c30844dSMel Gorman 
35051c30844dSMel Gorman 	/*
35061c30844dSMel Gorman 	 * Check for watermark boosts top-down as the higher zones
35071c30844dSMel Gorman 	 * are more likely to be boosted. Both watermarks and boosts
35081eba09c1SRandy Dunlap 	 * should not be checked at the same time as reclaim would
35091c30844dSMel Gorman 	 * start prematurely when there is no boosting and a lower
35101c30844dSMel Gorman 	 * zone is balanced.
35111c30844dSMel Gorman 	 */
351297a225e6SJoonsoo Kim 	for (i = highest_zoneidx; i >= 0; i--) {
35131c30844dSMel Gorman 		zone = pgdat->node_zones + i;
35141c30844dSMel Gorman 		if (!managed_zone(zone))
35151c30844dSMel Gorman 			continue;
35161c30844dSMel Gorman 
35171c30844dSMel Gorman 		if (zone->watermark_boost)
35181c30844dSMel Gorman 			return true;
35191c30844dSMel Gorman 	}
35201c30844dSMel Gorman 
35211c30844dSMel Gorman 	return false;
35221c30844dSMel Gorman }
35231c30844dSMel Gorman 
3524e716f2ebSMel Gorman /*
3525e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
352697a225e6SJoonsoo Kim  * and highest_zoneidx
3527e716f2ebSMel Gorman  */
352897a225e6SJoonsoo Kim static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
352960cefed4SJohannes Weiner {
3530e716f2ebSMel Gorman 	int i;
3531e716f2ebSMel Gorman 	unsigned long mark = -1;
3532e716f2ebSMel Gorman 	struct zone *zone;
353360cefed4SJohannes Weiner 
35341c30844dSMel Gorman 	/*
35351c30844dSMel Gorman 	 * Check watermarks bottom-up as lower zones are more likely to
35361c30844dSMel Gorman 	 * meet watermarks.
35371c30844dSMel Gorman 	 */
353897a225e6SJoonsoo Kim 	for (i = 0; i <= highest_zoneidx; i++) {
3539e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
35406256c6b4SMel Gorman 
3541e716f2ebSMel Gorman 		if (!managed_zone(zone))
3542e716f2ebSMel Gorman 			continue;
3543e716f2ebSMel Gorman 
3544e716f2ebSMel Gorman 		mark = high_wmark_pages(zone);
354597a225e6SJoonsoo Kim 		if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
35466256c6b4SMel Gorman 			return true;
354760cefed4SJohannes Weiner 	}
354860cefed4SJohannes Weiner 
3549e716f2ebSMel Gorman 	/*
355097a225e6SJoonsoo Kim 	 * If a node has no populated zone within highest_zoneidx, it does not
3551e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3552e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3553e716f2ebSMel Gorman 	 */
3554e716f2ebSMel Gorman 	if (mark == -1)
3555e716f2ebSMel Gorman 		return true;
3556e716f2ebSMel Gorman 
3557e716f2ebSMel Gorman 	return false;
3558e716f2ebSMel Gorman }
3559e716f2ebSMel Gorman 
3560631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
3561631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
3562631b6e08SMel Gorman {
35631b05117dSJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
35641b05117dSJohannes Weiner 
35651b05117dSJohannes Weiner 	clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3566631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
3567631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3568631b6e08SMel Gorman }
3569631b6e08SMel Gorman 
35701741c877SMel Gorman /*
35715515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
35725515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
35735515061dSMel Gorman  *
35745515061dSMel Gorman  * Returns true if kswapd is ready to sleep
35755515061dSMel Gorman  */
357697a225e6SJoonsoo Kim static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
357797a225e6SJoonsoo Kim 				int highest_zoneidx)
3578f50de2d3SMel Gorman {
35795515061dSMel Gorman 	/*
35809e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3581c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
35829e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
35839e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
35849e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
35859e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
35869e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
35879e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
35889e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
35899e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
35909e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
35915515061dSMel Gorman 	 */
35929e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
35939e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3594f50de2d3SMel Gorman 
3595c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3596c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3597c73322d0SJohannes Weiner 		return true;
3598c73322d0SJohannes Weiner 
359997a225e6SJoonsoo Kim 	if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
3600631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
3601333b0a45SShantanu Goel 		return true;
36021d82de61SMel Gorman 	}
36031d82de61SMel Gorman 
3604333b0a45SShantanu Goel 	return false;
3605f50de2d3SMel Gorman }
3606f50de2d3SMel Gorman 
36071da177e4SLinus Torvalds /*
36081d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
36091d82de61SMel Gorman  * zone that is currently unbalanced.
3610b8e83b94SMel Gorman  *
3611b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3612283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3613283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
361475485363SMel Gorman  */
36151d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3616accf6242SVlastimil Babka 			       struct scan_control *sc)
361775485363SMel Gorman {
36181d82de61SMel Gorman 	struct zone *zone;
36191d82de61SMel Gorman 	int z;
362075485363SMel Gorman 
36211d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
36221d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3623970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
36241d82de61SMel Gorman 		zone = pgdat->node_zones + z;
36256aa303deSMel Gorman 		if (!managed_zone(zone))
36261d82de61SMel Gorman 			continue;
36277c954f6dSMel Gorman 
36281d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
36297c954f6dSMel Gorman 	}
36307c954f6dSMel Gorman 
36311d82de61SMel Gorman 	/*
36321d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
36331d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
36341d82de61SMel Gorman 	 */
3635970a39a3SMel Gorman 	shrink_node(pgdat, sc);
36361d82de61SMel Gorman 
36371d82de61SMel Gorman 	/*
36381d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
36391d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
36401d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
36411d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
36421d82de61SMel Gorman 	 * can direct reclaim/compact.
36431d82de61SMel Gorman 	 */
36449861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
36451d82de61SMel Gorman 		sc->order = 0;
36461d82de61SMel Gorman 
3647b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
364875485363SMel Gorman }
364975485363SMel Gorman 
365075485363SMel Gorman /*
36511d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
36521d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
36531d82de61SMel Gorman  * balanced.
36541da177e4SLinus Torvalds  *
36551d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
36561da177e4SLinus Torvalds  *
36571da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
365841858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
36598bb4e7a2SWei Yang  * found to have free_pages <= high_wmark_pages(zone), any page in that zone
36601d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
36611d82de61SMel Gorman  * balanced.
36621da177e4SLinus Torvalds  */
366397a225e6SJoonsoo Kim static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
36641da177e4SLinus Torvalds {
36651da177e4SLinus Torvalds 	int i;
36660608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
36670608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3668eb414681SJohannes Weiner 	unsigned long pflags;
36691c30844dSMel Gorman 	unsigned long nr_boost_reclaim;
36701c30844dSMel Gorman 	unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
36711c30844dSMel Gorman 	bool boosted;
36721d82de61SMel Gorman 	struct zone *zone;
3673179e9639SAndrew Morton 	struct scan_control sc = {
3674179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3675ee814fe2SJohannes Weiner 		.order = order,
3676a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3677179e9639SAndrew Morton 	};
367893781325SOmar Sandoval 
36791732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
3680eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
368193781325SOmar Sandoval 	__fs_reclaim_acquire();
368293781325SOmar Sandoval 
3683f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
36841da177e4SLinus Torvalds 
36851c30844dSMel Gorman 	/*
36861c30844dSMel Gorman 	 * Account for the reclaim boost. Note that the zone boost is left in
36871c30844dSMel Gorman 	 * place so that parallel allocations that are near the watermark will
36881c30844dSMel Gorman 	 * stall or direct reclaim until kswapd is finished.
36891c30844dSMel Gorman 	 */
36901c30844dSMel Gorman 	nr_boost_reclaim = 0;
369197a225e6SJoonsoo Kim 	for (i = 0; i <= highest_zoneidx; i++) {
36921c30844dSMel Gorman 		zone = pgdat->node_zones + i;
36931c30844dSMel Gorman 		if (!managed_zone(zone))
36941c30844dSMel Gorman 			continue;
36951c30844dSMel Gorman 
36961c30844dSMel Gorman 		nr_boost_reclaim += zone->watermark_boost;
36971c30844dSMel Gorman 		zone_boosts[i] = zone->watermark_boost;
36981c30844dSMel Gorman 	}
36991c30844dSMel Gorman 	boosted = nr_boost_reclaim;
37001c30844dSMel Gorman 
37011c30844dSMel Gorman restart:
37021c30844dSMel Gorman 	sc.priority = DEF_PRIORITY;
37039e3b2f8cSKonstantin Khlebnikov 	do {
3704c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
3705b8e83b94SMel Gorman 		bool raise_priority = true;
37061c30844dSMel Gorman 		bool balanced;
370793781325SOmar Sandoval 		bool ret;
3708b8e83b94SMel Gorman 
370997a225e6SJoonsoo Kim 		sc.reclaim_idx = highest_zoneidx;
37101da177e4SLinus Torvalds 
371186c79f6bSMel Gorman 		/*
371284c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
371384c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
371484c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
371584c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
371684c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
371784c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
371884c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
371984c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
372086c79f6bSMel Gorman 		 */
372186c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
372286c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
372386c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
37246aa303deSMel Gorman 				if (!managed_zone(zone))
372586c79f6bSMel Gorman 					continue;
372686c79f6bSMel Gorman 
3727970a39a3SMel Gorman 				sc.reclaim_idx = i;
372886c79f6bSMel Gorman 				break;
372986c79f6bSMel Gorman 			}
373086c79f6bSMel Gorman 		}
373186c79f6bSMel Gorman 
373286c79f6bSMel Gorman 		/*
37331c30844dSMel Gorman 		 * If the pgdat is imbalanced then ignore boosting and preserve
37341c30844dSMel Gorman 		 * the watermarks for a later time and restart. Note that the
37351c30844dSMel Gorman 		 * zone watermarks will be still reset at the end of balancing
37361c30844dSMel Gorman 		 * on the grounds that the normal reclaim should be enough to
37371c30844dSMel Gorman 		 * re-evaluate if boosting is required when kswapd next wakes.
373886c79f6bSMel Gorman 		 */
373997a225e6SJoonsoo Kim 		balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
37401c30844dSMel Gorman 		if (!balanced && nr_boost_reclaim) {
37411c30844dSMel Gorman 			nr_boost_reclaim = 0;
37421c30844dSMel Gorman 			goto restart;
37431c30844dSMel Gorman 		}
37441c30844dSMel Gorman 
37451c30844dSMel Gorman 		/*
37461c30844dSMel Gorman 		 * If boosting is not active then only reclaim if there are no
37471c30844dSMel Gorman 		 * eligible zones. Note that sc.reclaim_idx is not used as
37481c30844dSMel Gorman 		 * buffer_heads_over_limit may have adjusted it.
37491c30844dSMel Gorman 		 */
37501c30844dSMel Gorman 		if (!nr_boost_reclaim && balanced)
37511da177e4SLinus Torvalds 			goto out;
3752e1dbeda6SAndrew Morton 
37531c30844dSMel Gorman 		/* Limit the priority of boosting to avoid reclaim writeback */
37541c30844dSMel Gorman 		if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
37551c30844dSMel Gorman 			raise_priority = false;
37561c30844dSMel Gorman 
37571c30844dSMel Gorman 		/*
37581c30844dSMel Gorman 		 * Do not writeback or swap pages for boosted reclaim. The
37591c30844dSMel Gorman 		 * intent is to relieve pressure not issue sub-optimal IO
37601c30844dSMel Gorman 		 * from reclaim context. If no pages are reclaimed, the
37611c30844dSMel Gorman 		 * reclaim will be aborted.
37621c30844dSMel Gorman 		 */
37631c30844dSMel Gorman 		sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
37641c30844dSMel Gorman 		sc.may_swap = !nr_boost_reclaim;
37651c30844dSMel Gorman 
37661da177e4SLinus Torvalds 		/*
37671d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
37681d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
37691d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
37701d82de61SMel Gorman 		 * about consistent aging.
37711d82de61SMel Gorman 		 */
3772ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
37731d82de61SMel Gorman 
37741d82de61SMel Gorman 		/*
3775b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3776b7ea3c41SMel Gorman 		 * even in laptop mode.
3777b7ea3c41SMel Gorman 		 */
3778047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
3779b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3780b7ea3c41SMel Gorman 
37811d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
37821da177e4SLinus Torvalds 		sc.nr_scanned = 0;
37830608f43dSAndrew Morton 		nr_soft_scanned = 0;
3784ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
37851d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
37860608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
37870608f43dSAndrew Morton 
378832a4330dSRik van Riel 		/*
37891d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
37901d82de61SMel Gorman 		 * enough pages are already being scanned that that high
37911d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
379232a4330dSRik van Riel 		 */
3793970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3794b8e83b94SMel Gorman 			raise_priority = false;
3795d7868daeSMel Gorman 
37965515061dSMel Gorman 		/*
37975515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
37985515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
37995515061dSMel Gorman 		 * able to safely make forward progress. Wake them
38005515061dSMel Gorman 		 */
38015515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3802c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
3803cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
38045515061dSMel Gorman 
3805b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
380693781325SOmar Sandoval 		__fs_reclaim_release();
380793781325SOmar Sandoval 		ret = try_to_freeze();
380893781325SOmar Sandoval 		__fs_reclaim_acquire();
380993781325SOmar Sandoval 		if (ret || kthread_should_stop())
3810b8e83b94SMel Gorman 			break;
3811b8e83b94SMel Gorman 
3812b8e83b94SMel Gorman 		/*
3813b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3814b8e83b94SMel Gorman 		 * progress in reclaiming pages
3815b8e83b94SMel Gorman 		 */
3816c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
38171c30844dSMel Gorman 		nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
38181c30844dSMel Gorman 
38191c30844dSMel Gorman 		/*
38201c30844dSMel Gorman 		 * If reclaim made no progress for a boost, stop reclaim as
38211c30844dSMel Gorman 		 * IO cannot be queued and it could be an infinite loop in
38221c30844dSMel Gorman 		 * extreme circumstances.
38231c30844dSMel Gorman 		 */
38241c30844dSMel Gorman 		if (nr_boost_reclaim && !nr_reclaimed)
38251c30844dSMel Gorman 			break;
38261c30844dSMel Gorman 
3827c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
3828b8e83b94SMel Gorman 			sc.priority--;
38291d82de61SMel Gorman 	} while (sc.priority >= 1);
38301da177e4SLinus Torvalds 
3831c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
3832c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
3833c73322d0SJohannes Weiner 
3834b8e83b94SMel Gorman out:
38351c30844dSMel Gorman 	/* If reclaim was boosted, account for the reclaim done in this pass */
38361c30844dSMel Gorman 	if (boosted) {
38371c30844dSMel Gorman 		unsigned long flags;
38381c30844dSMel Gorman 
383997a225e6SJoonsoo Kim 		for (i = 0; i <= highest_zoneidx; i++) {
38401c30844dSMel Gorman 			if (!zone_boosts[i])
38411c30844dSMel Gorman 				continue;
38421c30844dSMel Gorman 
38431c30844dSMel Gorman 			/* Increments are under the zone lock */
38441c30844dSMel Gorman 			zone = pgdat->node_zones + i;
38451c30844dSMel Gorman 			spin_lock_irqsave(&zone->lock, flags);
38461c30844dSMel Gorman 			zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
38471c30844dSMel Gorman 			spin_unlock_irqrestore(&zone->lock, flags);
38481c30844dSMel Gorman 		}
38491c30844dSMel Gorman 
38501c30844dSMel Gorman 		/*
38511c30844dSMel Gorman 		 * As there is now likely space, wakeup kcompact to defragment
38521c30844dSMel Gorman 		 * pageblocks.
38531c30844dSMel Gorman 		 */
385497a225e6SJoonsoo Kim 		wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
38551c30844dSMel Gorman 	}
38561c30844dSMel Gorman 
38572a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
385893781325SOmar Sandoval 	__fs_reclaim_release();
3859eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
38601732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3861e5ca8071SYafang Shao 
38620abdee2bSMel Gorman 	/*
38631d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
38641d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
38651d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
38661d82de61SMel Gorman 	 * remain at the higher level.
38670abdee2bSMel Gorman 	 */
38681d82de61SMel Gorman 	return sc.order;
38691da177e4SLinus Torvalds }
38701da177e4SLinus Torvalds 
3871e716f2ebSMel Gorman /*
387297a225e6SJoonsoo Kim  * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
387397a225e6SJoonsoo Kim  * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
387497a225e6SJoonsoo Kim  * not a valid index then either kswapd runs for first time or kswapd couldn't
387597a225e6SJoonsoo Kim  * sleep after previous reclaim attempt (node is still unbalanced). In that
387697a225e6SJoonsoo Kim  * case return the zone index of the previous kswapd reclaim cycle.
3877e716f2ebSMel Gorman  */
387897a225e6SJoonsoo Kim static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
387997a225e6SJoonsoo Kim 					   enum zone_type prev_highest_zoneidx)
3880e716f2ebSMel Gorman {
388197a225e6SJoonsoo Kim 	enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
38825644e1fbSQian Cai 
388397a225e6SJoonsoo Kim 	return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
3884e716f2ebSMel Gorman }
3885e716f2ebSMel Gorman 
388638087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
388797a225e6SJoonsoo Kim 				unsigned int highest_zoneidx)
3888f0bc0a60SKOSAKI Motohiro {
3889f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3890f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3891f0bc0a60SKOSAKI Motohiro 
3892f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3893f0bc0a60SKOSAKI Motohiro 		return;
3894f0bc0a60SKOSAKI Motohiro 
3895f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3896f0bc0a60SKOSAKI Motohiro 
3897333b0a45SShantanu Goel 	/*
3898333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
3899333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
3900333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
3901333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
3902333b0a45SShantanu Goel 	 * succeed.
3903333b0a45SShantanu Goel 	 */
390497a225e6SJoonsoo Kim 	if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
3905fd901c95SVlastimil Babka 		/*
3906fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3907fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3908fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3909fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3910fd901c95SVlastimil Babka 		 */
3911fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3912fd901c95SVlastimil Babka 
3913fd901c95SVlastimil Babka 		/*
3914fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3915fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3916fd901c95SVlastimil Babka 		 */
391797a225e6SJoonsoo Kim 		wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
3918fd901c95SVlastimil Babka 
3919f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
392038087d9bSMel Gorman 
392138087d9bSMel Gorman 		/*
392297a225e6SJoonsoo Kim 		 * If woken prematurely then reset kswapd_highest_zoneidx and
392338087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
392438087d9bSMel Gorman 		 * the previous request that slept prematurely.
392538087d9bSMel Gorman 		 */
392638087d9bSMel Gorman 		if (remaining) {
392797a225e6SJoonsoo Kim 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
392897a225e6SJoonsoo Kim 					kswapd_highest_zoneidx(pgdat,
392997a225e6SJoonsoo Kim 							highest_zoneidx));
39305644e1fbSQian Cai 
39315644e1fbSQian Cai 			if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
39325644e1fbSQian Cai 				WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
393338087d9bSMel Gorman 		}
393438087d9bSMel Gorman 
3935f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3936f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3937f0bc0a60SKOSAKI Motohiro 	}
3938f0bc0a60SKOSAKI Motohiro 
3939f0bc0a60SKOSAKI Motohiro 	/*
3940f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3941f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3942f0bc0a60SKOSAKI Motohiro 	 */
3943d9f21d42SMel Gorman 	if (!remaining &&
394497a225e6SJoonsoo Kim 	    prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
3945f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3946f0bc0a60SKOSAKI Motohiro 
3947f0bc0a60SKOSAKI Motohiro 		/*
3948f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3949f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3950f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3951f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3952f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3953f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3954f0bc0a60SKOSAKI Motohiro 		 */
3955f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
39561c7e7f6cSAaditya Kumar 
39571c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3958f0bc0a60SKOSAKI Motohiro 			schedule();
39591c7e7f6cSAaditya Kumar 
3960f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3961f0bc0a60SKOSAKI Motohiro 	} else {
3962f0bc0a60SKOSAKI Motohiro 		if (remaining)
3963f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3964f0bc0a60SKOSAKI Motohiro 		else
3965f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3966f0bc0a60SKOSAKI Motohiro 	}
3967f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3968f0bc0a60SKOSAKI Motohiro }
3969f0bc0a60SKOSAKI Motohiro 
39701da177e4SLinus Torvalds /*
39711da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
39721da177e4SLinus Torvalds  * from the init process.
39731da177e4SLinus Torvalds  *
39741da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
39751da177e4SLinus Torvalds  * free memory available even if there is no other activity
39761da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
39771da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
39781da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
39791da177e4SLinus Torvalds  *
39801da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
39811da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
39821da177e4SLinus Torvalds  */
39831da177e4SLinus Torvalds static int kswapd(void *p)
39841da177e4SLinus Torvalds {
3985e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
398697a225e6SJoonsoo Kim 	unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
39871da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
39881da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3989a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
39901da177e4SLinus Torvalds 
3991174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3992c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
39931da177e4SLinus Torvalds 
39941da177e4SLinus Torvalds 	/*
39951da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
39961da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
39971da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
39981da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
39991da177e4SLinus Torvalds 	 *
40001da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
40011da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
40021da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
40031da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
40041da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
40051da177e4SLinus Torvalds 	 */
4006930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
400783144186SRafael J. Wysocki 	set_freezable();
40081da177e4SLinus Torvalds 
40095644e1fbSQian Cai 	WRITE_ONCE(pgdat->kswapd_order, 0);
401097a225e6SJoonsoo Kim 	WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
40111da177e4SLinus Torvalds 	for ( ; ; ) {
40126f6313d4SJeff Liu 		bool ret;
40133e1d1d28SChristoph Lameter 
40145644e1fbSQian Cai 		alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
401597a225e6SJoonsoo Kim 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
401697a225e6SJoonsoo Kim 							highest_zoneidx);
4017e716f2ebSMel Gorman 
401838087d9bSMel Gorman kswapd_try_sleep:
401938087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
402097a225e6SJoonsoo Kim 					highest_zoneidx);
4021215ddd66SMel Gorman 
402297a225e6SJoonsoo Kim 		/* Read the new order and highest_zoneidx */
40232b47a24cSLukas Bulwahn 		alloc_order = READ_ONCE(pgdat->kswapd_order);
402497a225e6SJoonsoo Kim 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
402597a225e6SJoonsoo Kim 							highest_zoneidx);
40265644e1fbSQian Cai 		WRITE_ONCE(pgdat->kswapd_order, 0);
402797a225e6SJoonsoo Kim 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
40281da177e4SLinus Torvalds 
40298fe23e05SDavid Rientjes 		ret = try_to_freeze();
40308fe23e05SDavid Rientjes 		if (kthread_should_stop())
40318fe23e05SDavid Rientjes 			break;
40328fe23e05SDavid Rientjes 
40338fe23e05SDavid Rientjes 		/*
40348fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
40358fe23e05SDavid Rientjes 		 * after returning from the refrigerator
4036b1296cc4SRafael J. Wysocki 		 */
403738087d9bSMel Gorman 		if (ret)
403838087d9bSMel Gorman 			continue;
40391d82de61SMel Gorman 
404038087d9bSMel Gorman 		/*
404138087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
404238087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
404338087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
404438087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
404538087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
404638087d9bSMel Gorman 		 * request (alloc_order).
404738087d9bSMel Gorman 		 */
404897a225e6SJoonsoo Kim 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
4049e5146b12SMel Gorman 						alloc_order);
405097a225e6SJoonsoo Kim 		reclaim_order = balance_pgdat(pgdat, alloc_order,
405197a225e6SJoonsoo Kim 						highest_zoneidx);
405238087d9bSMel Gorman 		if (reclaim_order < alloc_order)
405338087d9bSMel Gorman 			goto kswapd_try_sleep;
405433906bc5SMel Gorman 	}
4055b0a8cc58STakamori Yamaguchi 
405671abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
405771abdc15SJohannes Weiner 
40581da177e4SLinus Torvalds 	return 0;
40591da177e4SLinus Torvalds }
40601da177e4SLinus Torvalds 
40611da177e4SLinus Torvalds /*
40625ecd9d40SDavid Rientjes  * A zone is low on free memory or too fragmented for high-order memory.  If
40635ecd9d40SDavid Rientjes  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
40645ecd9d40SDavid Rientjes  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
40655ecd9d40SDavid Rientjes  * has failed or is not needed, still wake up kcompactd if only compaction is
40665ecd9d40SDavid Rientjes  * needed.
40671da177e4SLinus Torvalds  */
40685ecd9d40SDavid Rientjes void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
406997a225e6SJoonsoo Kim 		   enum zone_type highest_zoneidx)
40701da177e4SLinus Torvalds {
40711da177e4SLinus Torvalds 	pg_data_t *pgdat;
40725644e1fbSQian Cai 	enum zone_type curr_idx;
40731da177e4SLinus Torvalds 
40746aa303deSMel Gorman 	if (!managed_zone(zone))
40751da177e4SLinus Torvalds 		return;
40761da177e4SLinus Torvalds 
40775ecd9d40SDavid Rientjes 	if (!cpuset_zone_allowed(zone, gfp_flags))
40781da177e4SLinus Torvalds 		return;
4079dffcac2cSShakeel Butt 
40805644e1fbSQian Cai 	pgdat = zone->zone_pgdat;
408197a225e6SJoonsoo Kim 	curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
40825644e1fbSQian Cai 
408397a225e6SJoonsoo Kim 	if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
408497a225e6SJoonsoo Kim 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
40855644e1fbSQian Cai 
40865644e1fbSQian Cai 	if (READ_ONCE(pgdat->kswapd_order) < order)
40875644e1fbSQian Cai 		WRITE_ONCE(pgdat->kswapd_order, order);
40885644e1fbSQian Cai 
40898d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
40901da177e4SLinus Torvalds 		return;
4091e1a55637SMel Gorman 
40925ecd9d40SDavid Rientjes 	/* Hopeless node, leave it to direct reclaim if possible */
40935ecd9d40SDavid Rientjes 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
409497a225e6SJoonsoo Kim 	    (pgdat_balanced(pgdat, order, highest_zoneidx) &&
409597a225e6SJoonsoo Kim 	     !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
40965ecd9d40SDavid Rientjes 		/*
40975ecd9d40SDavid Rientjes 		 * There may be plenty of free memory available, but it's too
40985ecd9d40SDavid Rientjes 		 * fragmented for high-order allocations.  Wake up kcompactd
40995ecd9d40SDavid Rientjes 		 * and rely on compaction_suitable() to determine if it's
41005ecd9d40SDavid Rientjes 		 * needed.  If it fails, it will defer subsequent attempts to
41015ecd9d40SDavid Rientjes 		 * ratelimit its work.
41025ecd9d40SDavid Rientjes 		 */
41035ecd9d40SDavid Rientjes 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
410497a225e6SJoonsoo Kim 			wakeup_kcompactd(pgdat, order, highest_zoneidx);
4105c73322d0SJohannes Weiner 		return;
41065ecd9d40SDavid Rientjes 	}
4107c73322d0SJohannes Weiner 
410897a225e6SJoonsoo Kim 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
41095ecd9d40SDavid Rientjes 				      gfp_flags);
41108d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
41111da177e4SLinus Torvalds }
41121da177e4SLinus Torvalds 
4113c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
41141da177e4SLinus Torvalds /*
41157b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
4116d6277db4SRafael J. Wysocki  * freed pages.
4117d6277db4SRafael J. Wysocki  *
4118d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
4119d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
4120d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
41211da177e4SLinus Torvalds  */
41227b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
41231da177e4SLinus Torvalds {
4124d6277db4SRafael J. Wysocki 	struct scan_control sc = {
41257b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
4126ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
4127b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
41289e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
4129ee814fe2SJohannes Weiner 		.may_writepage = 1,
4130ee814fe2SJohannes Weiner 		.may_unmap = 1,
4131ee814fe2SJohannes Weiner 		.may_swap = 1,
4132ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
41331da177e4SLinus Torvalds 	};
41347b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
41357b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
4136499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
41371da177e4SLinus Torvalds 
4138d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
413993781325SOmar Sandoval 	noreclaim_flag = memalloc_noreclaim_save();
41401732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
4141d6277db4SRafael J. Wysocki 
41423115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4143d6277db4SRafael J. Wysocki 
41441732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
4145499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
414693781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4147d6277db4SRafael J. Wysocki 
41487b51755cSKOSAKI Motohiro 	return nr_reclaimed;
41491da177e4SLinus Torvalds }
4150c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
41511da177e4SLinus Torvalds 
41523218ae14SYasunori Goto /*
41533218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
41543218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
41553218ae14SYasunori Goto  */
41563218ae14SYasunori Goto int kswapd_run(int nid)
41573218ae14SYasunori Goto {
41583218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
41593218ae14SYasunori Goto 	int ret = 0;
41603218ae14SYasunori Goto 
41613218ae14SYasunori Goto 	if (pgdat->kswapd)
41623218ae14SYasunori Goto 		return 0;
41633218ae14SYasunori Goto 
41643218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
41653218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
41663218ae14SYasunori Goto 		/* failure at boot is fatal */
4167c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
4168d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
4169d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
4170d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
41713218ae14SYasunori Goto 	}
41723218ae14SYasunori Goto 	return ret;
41733218ae14SYasunori Goto }
41743218ae14SYasunori Goto 
41758fe23e05SDavid Rientjes /*
4176d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
4177bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
41788fe23e05SDavid Rientjes  */
41798fe23e05SDavid Rientjes void kswapd_stop(int nid)
41808fe23e05SDavid Rientjes {
41818fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
41828fe23e05SDavid Rientjes 
4183d8adde17SJiang Liu 	if (kswapd) {
41848fe23e05SDavid Rientjes 		kthread_stop(kswapd);
4185d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
4186d8adde17SJiang Liu 	}
41878fe23e05SDavid Rientjes }
41888fe23e05SDavid Rientjes 
41891da177e4SLinus Torvalds static int __init kswapd_init(void)
41901da177e4SLinus Torvalds {
41916b700b5bSWei Yang 	int nid;
419269e05944SAndrew Morton 
41931da177e4SLinus Torvalds 	swap_setup();
419448fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
41953218ae14SYasunori Goto  		kswapd_run(nid);
41961da177e4SLinus Torvalds 	return 0;
41971da177e4SLinus Torvalds }
41981da177e4SLinus Torvalds 
41991da177e4SLinus Torvalds module_init(kswapd_init)
42009eeff239SChristoph Lameter 
42019eeff239SChristoph Lameter #ifdef CONFIG_NUMA
42029eeff239SChristoph Lameter /*
4203a5f5f91dSMel Gorman  * Node reclaim mode
42049eeff239SChristoph Lameter  *
4205a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
42069eeff239SChristoph Lameter  * the watermarks.
42079eeff239SChristoph Lameter  */
4208a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
42099eeff239SChristoph Lameter 
421051998364SDave Hansen /*
4211a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
4212a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
4213a92f7126SChristoph Lameter  * a zone.
4214a92f7126SChristoph Lameter  */
4215a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
4216a92f7126SChristoph Lameter 
42179eeff239SChristoph Lameter /*
4218a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
42199614634fSChristoph Lameter  * occur.
42209614634fSChristoph Lameter  */
42219614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
42229614634fSChristoph Lameter 
42239614634fSChristoph Lameter /*
42240ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
42250ff38490SChristoph Lameter  * slab reclaim needs to occur.
42260ff38490SChristoph Lameter  */
42270ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
42280ff38490SChristoph Lameter 
422911fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
423090afa5deSMel Gorman {
423111fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
423211fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
423311fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
423490afa5deSMel Gorman 
423590afa5deSMel Gorman 	/*
423690afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
423790afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
423890afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
423990afa5deSMel Gorman 	 */
424090afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
424190afa5deSMel Gorman }
424290afa5deSMel Gorman 
424390afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4244a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
424590afa5deSMel Gorman {
4246d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
4247d031a157SAlexandru Moise 	unsigned long delta = 0;
424890afa5deSMel Gorman 
424990afa5deSMel Gorman 	/*
425095bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
425190afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
425211fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
425390afa5deSMel Gorman 	 * a better estimate
425490afa5deSMel Gorman 	 */
4255a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
4256a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
425790afa5deSMel Gorman 	else
4258a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
425990afa5deSMel Gorman 
426090afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
4261a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
4262a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
426390afa5deSMel Gorman 
426490afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
426590afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
426690afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
426790afa5deSMel Gorman 
426890afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
426990afa5deSMel Gorman }
427090afa5deSMel Gorman 
42710ff38490SChristoph Lameter /*
4272a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
42739eeff239SChristoph Lameter  */
4274a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
42759eeff239SChristoph Lameter {
42767fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
427769e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
42789eeff239SChristoph Lameter 	struct task_struct *p = current;
4279499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
4280179e9639SAndrew Morton 	struct scan_control sc = {
428162b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4282f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
4283bd2f6199SJohannes Weiner 		.order = order,
4284a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
4285a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4286a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4287ee814fe2SJohannes Weiner 		.may_swap = 1,
4288f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
4289179e9639SAndrew Morton 	};
42909eeff239SChristoph Lameter 
4291132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4292132bb8cfSYafang Shao 					   sc.gfp_mask);
4293132bb8cfSYafang Shao 
42949eeff239SChristoph Lameter 	cond_resched();
429593781325SOmar Sandoval 	fs_reclaim_acquire(sc.gfp_mask);
4296d4f7796eSChristoph Lameter 	/*
429795bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4298d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
429995bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
4300d4f7796eSChristoph Lameter 	 */
4301499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
4302499118e9SVlastimil Babka 	p->flags |= PF_SWAPWRITE;
43031732d2b0SAndrew Morton 	set_task_reclaim_state(p, &sc.reclaim_state);
4304c84db23cSChristoph Lameter 
4305a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
4306a92f7126SChristoph Lameter 		/*
4307894befecSAndrey Ryabinin 		 * Free memory by calling shrink node with increasing
43080ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
4309a92f7126SChristoph Lameter 		 */
4310a92f7126SChristoph Lameter 		do {
4311970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
43129e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
43130ff38490SChristoph Lameter 	}
4314a92f7126SChristoph Lameter 
43151732d2b0SAndrew Morton 	set_task_reclaim_state(p, NULL);
4316499118e9SVlastimil Babka 	current->flags &= ~PF_SWAPWRITE;
4317499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
431893781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4319132bb8cfSYafang Shao 
4320132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4321132bb8cfSYafang Shao 
4322a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
43239eeff239SChristoph Lameter }
4324179e9639SAndrew Morton 
4325a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4326179e9639SAndrew Morton {
4327d773ed6bSDavid Rientjes 	int ret;
4328179e9639SAndrew Morton 
4329179e9639SAndrew Morton 	/*
4330a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
43310ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
433234aa1330SChristoph Lameter 	 *
43339614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
43349614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
4335a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
4336a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
43379614634fSChristoph Lameter 	 * unmapped file backed pages.
4338179e9639SAndrew Morton 	 */
4339a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4340d42f3245SRoman Gushchin 	    node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
4341d42f3245SRoman Gushchin 	    pgdat->min_slab_pages)
4342a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
4343179e9639SAndrew Morton 
4344179e9639SAndrew Morton 	/*
4345d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
4346179e9639SAndrew Morton 	 */
4347d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4348a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4349179e9639SAndrew Morton 
4350179e9639SAndrew Morton 	/*
4351a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
4352179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
4353179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
4354179e9639SAndrew Morton 	 * as wide as possible.
4355179e9639SAndrew Morton 	 */
4356a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4357a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4358d773ed6bSDavid Rientjes 
4359a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4360a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4361fa5e084eSMel Gorman 
4362a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
4363a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4364d773ed6bSDavid Rientjes 
436524cf7251SMel Gorman 	if (!ret)
436624cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
436724cf7251SMel Gorman 
4368d773ed6bSDavid Rientjes 	return ret;
4369179e9639SAndrew Morton }
43709eeff239SChristoph Lameter #endif
4371894bc310SLee Schermerhorn 
437289e004eaSLee Schermerhorn /**
437364e3d12fSKuo-Hsin Yang  * check_move_unevictable_pages - check pages for evictability and move to
437464e3d12fSKuo-Hsin Yang  * appropriate zone lru list
437564e3d12fSKuo-Hsin Yang  * @pvec: pagevec with lru pages to check
437689e004eaSLee Schermerhorn  *
437764e3d12fSKuo-Hsin Yang  * Checks pages for evictability, if an evictable page is in the unevictable
437864e3d12fSKuo-Hsin Yang  * lru list, moves it to the appropriate evictable lru list. This function
437964e3d12fSKuo-Hsin Yang  * should be only used for lru pages.
438089e004eaSLee Schermerhorn  */
438164e3d12fSKuo-Hsin Yang void check_move_unevictable_pages(struct pagevec *pvec)
438289e004eaSLee Schermerhorn {
43836168d0daSAlex Shi 	struct lruvec *lruvec = NULL;
438424513264SHugh Dickins 	int pgscanned = 0;
438524513264SHugh Dickins 	int pgrescued = 0;
438689e004eaSLee Schermerhorn 	int i;
438789e004eaSLee Schermerhorn 
438864e3d12fSKuo-Hsin Yang 	for (i = 0; i < pvec->nr; i++) {
438964e3d12fSKuo-Hsin Yang 		struct page *page = pvec->pages[i];
43908d8869caSHugh Dickins 		int nr_pages;
439189e004eaSLee Schermerhorn 
43928d8869caSHugh Dickins 		if (PageTransTail(page))
43938d8869caSHugh Dickins 			continue;
43948d8869caSHugh Dickins 
43958d8869caSHugh Dickins 		nr_pages = thp_nr_pages(page);
43968d8869caSHugh Dickins 		pgscanned += nr_pages;
43978d8869caSHugh Dickins 
4398d25b5bd8SAlex Shi 		/* block memcg migration during page moving between lru */
4399d25b5bd8SAlex Shi 		if (!TestClearPageLRU(page))
4400d25b5bd8SAlex Shi 			continue;
4401d25b5bd8SAlex Shi 
44022a5e4e34SAlexander Duyck 		lruvec = relock_page_lruvec_irq(page, lruvec);
4403d25b5bd8SAlex Shi 		if (page_evictable(page) && PageUnevictable(page)) {
440446ae6b2cSYu Zhao 			del_page_from_lru_list(page, lruvec);
440524513264SHugh Dickins 			ClearPageUnevictable(page);
44063a9c9788SYu Zhao 			add_page_to_lru_list(page, lruvec);
44078d8869caSHugh Dickins 			pgrescued += nr_pages;
440889e004eaSLee Schermerhorn 		}
4409d25b5bd8SAlex Shi 		SetPageLRU(page);
441089e004eaSLee Schermerhorn 	}
441124513264SHugh Dickins 
44126168d0daSAlex Shi 	if (lruvec) {
441324513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
441424513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
44156168d0daSAlex Shi 		unlock_page_lruvec_irq(lruvec);
4416d25b5bd8SAlex Shi 	} else if (pgscanned) {
4417d25b5bd8SAlex Shi 		count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
441824513264SHugh Dickins 	}
441985046579SHugh Dickins }
442064e3d12fSKuo-Hsin Yang EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
4421