xref: /openbmc/linux/mm/vmscan.c (revision afca9157fd426451eb182c9de4bfe4b9382a873a)
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
1887e010df5SKirill Tkhai /*
1897e010df5SKirill Tkhai  * We allow subsystems to populate their shrinker-related
1907e010df5SKirill Tkhai  * LRU lists before register_shrinker_prepared() is called
1917e010df5SKirill Tkhai  * for the shrinker, since we don't want to impose
1927e010df5SKirill Tkhai  * restrictions on their internal registration order.
1937e010df5SKirill Tkhai  * In this case shrink_slab_memcg() may find corresponding
1947e010df5SKirill Tkhai  * bit is set in the shrinkers map.
1957e010df5SKirill Tkhai  *
1967e010df5SKirill Tkhai  * This value is used by the function to detect registering
1977e010df5SKirill Tkhai  * shrinkers and to skip do_shrink_slab() calls for them.
1987e010df5SKirill Tkhai  */
1997e010df5SKirill Tkhai #define SHRINKER_REGISTERING ((struct shrinker *)~0UL)
2007e010df5SKirill Tkhai 
201b4c2b231SKirill Tkhai static DEFINE_IDR(shrinker_idr);
202b4c2b231SKirill Tkhai static int shrinker_nr_max;
203b4c2b231SKirill Tkhai 
204b4c2b231SKirill Tkhai static int prealloc_memcg_shrinker(struct shrinker *shrinker)
205b4c2b231SKirill Tkhai {
206b4c2b231SKirill Tkhai 	int id, ret = -ENOMEM;
207b4c2b231SKirill Tkhai 
208b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
209b4c2b231SKirill Tkhai 	/* This may call shrinker, so it must use down_read_trylock() */
2107e010df5SKirill Tkhai 	id = idr_alloc(&shrinker_idr, SHRINKER_REGISTERING, 0, 0, GFP_KERNEL);
211b4c2b231SKirill Tkhai 	if (id < 0)
212b4c2b231SKirill Tkhai 		goto unlock;
213b4c2b231SKirill Tkhai 
2140a4465d3SKirill Tkhai 	if (id >= shrinker_nr_max) {
2150a4465d3SKirill Tkhai 		if (memcg_expand_shrinker_maps(id)) {
2160a4465d3SKirill Tkhai 			idr_remove(&shrinker_idr, id);
2170a4465d3SKirill Tkhai 			goto unlock;
2180a4465d3SKirill Tkhai 		}
2190a4465d3SKirill Tkhai 
220b4c2b231SKirill Tkhai 		shrinker_nr_max = id + 1;
2210a4465d3SKirill Tkhai 	}
222b4c2b231SKirill Tkhai 	shrinker->id = id;
223b4c2b231SKirill Tkhai 	ret = 0;
224b4c2b231SKirill Tkhai unlock:
225b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
226b4c2b231SKirill Tkhai 	return ret;
227b4c2b231SKirill Tkhai }
228b4c2b231SKirill Tkhai 
229b4c2b231SKirill Tkhai static void unregister_memcg_shrinker(struct shrinker *shrinker)
230b4c2b231SKirill Tkhai {
231b4c2b231SKirill Tkhai 	int id = shrinker->id;
232b4c2b231SKirill Tkhai 
233b4c2b231SKirill Tkhai 	BUG_ON(id < 0);
234b4c2b231SKirill Tkhai 
235b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
236b4c2b231SKirill Tkhai 	idr_remove(&shrinker_idr, id);
237b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
238b4c2b231SKirill Tkhai }
239b4c2b231SKirill Tkhai 
240b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
24189b5fae5SJohannes Weiner {
242b5ead35eSJohannes Weiner 	return sc->target_mem_cgroup;
24389b5fae5SJohannes Weiner }
24497c9341fSTejun Heo 
24597c9341fSTejun Heo /**
246b5ead35eSJohannes Weiner  * writeback_throttling_sane - is the usual dirty throttling mechanism available?
24797c9341fSTejun Heo  * @sc: scan_control in question
24897c9341fSTejun Heo  *
24997c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
25097c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
25197c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
25297c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
25397c9341fSTejun Heo  * allocation and configurability.
25497c9341fSTejun Heo  *
25597c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
25697c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
25797c9341fSTejun Heo  */
258b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
25997c9341fSTejun Heo {
260b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
26197c9341fSTejun Heo 		return true;
26297c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
26369234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
26497c9341fSTejun Heo 		return true;
26597c9341fSTejun Heo #endif
26697c9341fSTejun Heo 	return false;
26797c9341fSTejun Heo }
26891a45470SKAMEZAWA Hiroyuki #else
2690a432dcbSYang Shi static int prealloc_memcg_shrinker(struct shrinker *shrinker)
2700a432dcbSYang Shi {
2710a432dcbSYang Shi 	return 0;
2720a432dcbSYang Shi }
2730a432dcbSYang Shi 
2740a432dcbSYang Shi static void unregister_memcg_shrinker(struct shrinker *shrinker)
2750a432dcbSYang Shi {
2760a432dcbSYang Shi }
2770a432dcbSYang Shi 
278b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
27989b5fae5SJohannes Weiner {
280b5ead35eSJohannes Weiner 	return false;
28189b5fae5SJohannes Weiner }
28297c9341fSTejun Heo 
283b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
28497c9341fSTejun Heo {
28597c9341fSTejun Heo 	return true;
28697c9341fSTejun Heo }
28791a45470SKAMEZAWA Hiroyuki #endif
28891a45470SKAMEZAWA Hiroyuki 
2895a1c84b4SMel Gorman /*
2905a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
2915a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
2925a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
2935a1c84b4SMel Gorman  */
2945a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
2955a1c84b4SMel Gorman {
2965a1c84b4SMel Gorman 	unsigned long nr;
2975a1c84b4SMel Gorman 
2985a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
2995a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
3005a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
3015a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
3025a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
3035a1c84b4SMel Gorman 
3045a1c84b4SMel Gorman 	return nr;
3055a1c84b4SMel Gorman }
3065a1c84b4SMel Gorman 
307fd538803SMichal Hocko /**
308fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
309fd538803SMichal Hocko  * @lruvec: lru vector
310fd538803SMichal Hocko  * @lru: lru to use
311fd538803SMichal Hocko  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
312fd538803SMichal Hocko  */
313fd538803SMichal Hocko unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, int zone_idx)
314c9f299d9SKOSAKI Motohiro {
315de3b0150SJohannes Weiner 	unsigned long size = 0;
316fd538803SMichal Hocko 	int zid;
317a3d8e054SKOSAKI Motohiro 
318de3b0150SJohannes Weiner 	for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
319fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
320fd538803SMichal Hocko 
321fd538803SMichal Hocko 		if (!managed_zone(zone))
322fd538803SMichal Hocko 			continue;
323fd538803SMichal Hocko 
324fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
325de3b0150SJohannes Weiner 			size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
326fd538803SMichal Hocko 		else
327de3b0150SJohannes Weiner 			size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
328c9f299d9SKOSAKI Motohiro 	}
329de3b0150SJohannes Weiner 	return size;
330b4536f0cSMichal Hocko }
331b4536f0cSMichal Hocko 
3321da177e4SLinus Torvalds /*
3331d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
3341da177e4SLinus Torvalds  */
3358e04944fSTetsuo Handa int prealloc_shrinker(struct shrinker *shrinker)
3361da177e4SLinus Torvalds {
337b9726c26SAlexey Dobriyan 	unsigned int size = sizeof(*shrinker->nr_deferred);
3381d3d4437SGlauber Costa 
3391d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
3401d3d4437SGlauber Costa 		size *= nr_node_ids;
3411d3d4437SGlauber Costa 
3421d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
3431d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
3441d3d4437SGlauber Costa 		return -ENOMEM;
345b4c2b231SKirill Tkhai 
346b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
347b4c2b231SKirill Tkhai 		if (prealloc_memcg_shrinker(shrinker))
348b4c2b231SKirill Tkhai 			goto free_deferred;
349b4c2b231SKirill Tkhai 	}
350b4c2b231SKirill Tkhai 
3518e04944fSTetsuo Handa 	return 0;
352b4c2b231SKirill Tkhai 
353b4c2b231SKirill Tkhai free_deferred:
354b4c2b231SKirill Tkhai 	kfree(shrinker->nr_deferred);
355b4c2b231SKirill Tkhai 	shrinker->nr_deferred = NULL;
356b4c2b231SKirill Tkhai 	return -ENOMEM;
3578e04944fSTetsuo Handa }
3581d3d4437SGlauber Costa 
3598e04944fSTetsuo Handa void free_prealloced_shrinker(struct shrinker *shrinker)
3608e04944fSTetsuo Handa {
361b4c2b231SKirill Tkhai 	if (!shrinker->nr_deferred)
362b4c2b231SKirill Tkhai 		return;
363b4c2b231SKirill Tkhai 
364b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
365b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
366b4c2b231SKirill Tkhai 
3678e04944fSTetsuo Handa 	kfree(shrinker->nr_deferred);
3688e04944fSTetsuo Handa 	shrinker->nr_deferred = NULL;
3698e04944fSTetsuo Handa }
3708e04944fSTetsuo Handa 
3718e04944fSTetsuo Handa void register_shrinker_prepared(struct shrinker *shrinker)
3728e04944fSTetsuo Handa {
3731da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
3741da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
37542a9a53bSYang Shi #ifdef CONFIG_MEMCG
3768df4a44cSKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
3777e010df5SKirill Tkhai 		idr_replace(&shrinker_idr, shrinker, shrinker->id);
3787e010df5SKirill Tkhai #endif
3791da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
3808e04944fSTetsuo Handa }
3818e04944fSTetsuo Handa 
3828e04944fSTetsuo Handa int register_shrinker(struct shrinker *shrinker)
3838e04944fSTetsuo Handa {
3848e04944fSTetsuo Handa 	int err = prealloc_shrinker(shrinker);
3858e04944fSTetsuo Handa 
3868e04944fSTetsuo Handa 	if (err)
3878e04944fSTetsuo Handa 		return err;
3888e04944fSTetsuo Handa 	register_shrinker_prepared(shrinker);
3891d3d4437SGlauber Costa 	return 0;
3901da177e4SLinus Torvalds }
3918e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
3921da177e4SLinus Torvalds 
3931da177e4SLinus Torvalds /*
3941da177e4SLinus Torvalds  * Remove one
3951da177e4SLinus Torvalds  */
3968e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
3971da177e4SLinus Torvalds {
398bb422a73STetsuo Handa 	if (!shrinker->nr_deferred)
399bb422a73STetsuo Handa 		return;
400b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
401b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
4021da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
4031da177e4SLinus Torvalds 	list_del(&shrinker->list);
4041da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
405ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
406bb422a73STetsuo Handa 	shrinker->nr_deferred = NULL;
4071da177e4SLinus Torvalds }
4088e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
4091da177e4SLinus Torvalds 
4101da177e4SLinus Torvalds #define SHRINK_BATCH 128
4111d3d4437SGlauber Costa 
412cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
4139092c71bSJosef Bacik 				    struct shrinker *shrinker, int priority)
4141da177e4SLinus Torvalds {
41524f7c6b9SDave Chinner 	unsigned long freed = 0;
4161da177e4SLinus Torvalds 	unsigned long long delta;
417635697c6SKonstantin Khlebnikov 	long total_scan;
418d5bc5fd3SVladimir Davydov 	long freeable;
419acf92b48SDave Chinner 	long nr;
420acf92b48SDave Chinner 	long new_nr;
4211d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
422e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
423e9299f50SDave Chinner 					  : SHRINK_BATCH;
4245f33a080SShaohua Li 	long scanned = 0, next_deferred;
4251da177e4SLinus Torvalds 
426ac7fb3adSKirill Tkhai 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
427ac7fb3adSKirill Tkhai 		nid = 0;
428ac7fb3adSKirill Tkhai 
429d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
4309b996468SKirill Tkhai 	if (freeable == 0 || freeable == SHRINK_EMPTY)
4319b996468SKirill Tkhai 		return freeable;
432635697c6SKonstantin Khlebnikov 
433acf92b48SDave Chinner 	/*
434acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
435acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
436acf92b48SDave Chinner 	 * don't also do this scanning work.
437acf92b48SDave Chinner 	 */
4381d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
439acf92b48SDave Chinner 
440acf92b48SDave Chinner 	total_scan = nr;
4414b85afbdSJohannes Weiner 	if (shrinker->seeks) {
4429092c71bSJosef Bacik 		delta = freeable >> priority;
4439092c71bSJosef Bacik 		delta *= 4;
4449092c71bSJosef Bacik 		do_div(delta, shrinker->seeks);
4454b85afbdSJohannes Weiner 	} else {
4464b85afbdSJohannes Weiner 		/*
4474b85afbdSJohannes Weiner 		 * These objects don't require any IO to create. Trim
4484b85afbdSJohannes Weiner 		 * them aggressively under memory pressure to keep
4494b85afbdSJohannes Weiner 		 * them from causing refetches in the IO caches.
4504b85afbdSJohannes Weiner 		 */
4514b85afbdSJohannes Weiner 		delta = freeable / 2;
4524b85afbdSJohannes Weiner 	}
453172b06c3SRoman Gushchin 
454acf92b48SDave Chinner 	total_scan += delta;
455acf92b48SDave Chinner 	if (total_scan < 0) {
456d75f773cSSakari Ailus 		pr_err("shrink_slab: %pS negative objects to delete nr=%ld\n",
457a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
458d5bc5fd3SVladimir Davydov 		total_scan = freeable;
4595f33a080SShaohua Li 		next_deferred = nr;
4605f33a080SShaohua Li 	} else
4615f33a080SShaohua Li 		next_deferred = total_scan;
462ea164d73SAndrea Arcangeli 
463ea164d73SAndrea Arcangeli 	/*
4643567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
4653567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
4663567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
4673567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
4683567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
469d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
4703567b59aSDave Chinner 	 * memory.
4713567b59aSDave Chinner 	 *
4723567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
4733567b59aSDave Chinner 	 * a large delta change is calculated directly.
4743567b59aSDave Chinner 	 */
475d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
476d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
4773567b59aSDave Chinner 
4783567b59aSDave Chinner 	/*
479ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
480ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
481ea164d73SAndrea Arcangeli 	 * freeable entries.
482ea164d73SAndrea Arcangeli 	 */
483d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
484d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
4851da177e4SLinus Torvalds 
48624f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
4879092c71bSJosef Bacik 				   freeable, delta, total_scan, priority);
48809576073SDave Chinner 
4890b1fb40aSVladimir Davydov 	/*
4900b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
4910b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
4920b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
4930b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
4940b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
4950b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
4960b1fb40aSVladimir Davydov 	 * batch_size.
4970b1fb40aSVladimir Davydov 	 *
4980b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
4990b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
500d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
5010b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
5020b1fb40aSVladimir Davydov 	 * possible.
5030b1fb40aSVladimir Davydov 	 */
5040b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
505d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
50624f7c6b9SDave Chinner 		unsigned long ret;
5070b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
5081da177e4SLinus Torvalds 
5090b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
510d460acb5SChris Wilson 		shrinkctl->nr_scanned = nr_to_scan;
51124f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
51224f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
5131da177e4SLinus Torvalds 			break;
51424f7c6b9SDave Chinner 		freed += ret;
51524f7c6b9SDave Chinner 
516d460acb5SChris Wilson 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
517d460acb5SChris Wilson 		total_scan -= shrinkctl->nr_scanned;
518d460acb5SChris Wilson 		scanned += shrinkctl->nr_scanned;
5191da177e4SLinus Torvalds 
5201da177e4SLinus Torvalds 		cond_resched();
5211da177e4SLinus Torvalds 	}
5221da177e4SLinus Torvalds 
5235f33a080SShaohua Li 	if (next_deferred >= scanned)
5245f33a080SShaohua Li 		next_deferred -= scanned;
5255f33a080SShaohua Li 	else
5265f33a080SShaohua Li 		next_deferred = 0;
527acf92b48SDave Chinner 	/*
528acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
529acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
530acf92b48SDave Chinner 	 * scan, there is no need to do an update.
531acf92b48SDave Chinner 	 */
5325f33a080SShaohua Li 	if (next_deferred > 0)
5335f33a080SShaohua Li 		new_nr = atomic_long_add_return(next_deferred,
5341d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
53583aeeadaSKonstantin Khlebnikov 	else
5361d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
537acf92b48SDave Chinner 
538df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
5391d3d4437SGlauber Costa 	return freed;
5401d3d4437SGlauber Costa }
5411d3d4437SGlauber Costa 
5420a432dcbSYang Shi #ifdef CONFIG_MEMCG
543b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
544b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
545b0dedc49SKirill Tkhai {
546b0dedc49SKirill Tkhai 	struct memcg_shrinker_map *map;
547b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
548b8e57efaSKirill Tkhai 	int i;
549b0dedc49SKirill Tkhai 
5500a432dcbSYang Shi 	if (!mem_cgroup_online(memcg))
551b0dedc49SKirill Tkhai 		return 0;
552b0dedc49SKirill Tkhai 
553b0dedc49SKirill Tkhai 	if (!down_read_trylock(&shrinker_rwsem))
554b0dedc49SKirill Tkhai 		return 0;
555b0dedc49SKirill Tkhai 
556b0dedc49SKirill Tkhai 	map = rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_map,
557b0dedc49SKirill Tkhai 					true);
558b0dedc49SKirill Tkhai 	if (unlikely(!map))
559b0dedc49SKirill Tkhai 		goto unlock;
560b0dedc49SKirill Tkhai 
561b0dedc49SKirill Tkhai 	for_each_set_bit(i, map->map, shrinker_nr_max) {
562b0dedc49SKirill Tkhai 		struct shrink_control sc = {
563b0dedc49SKirill Tkhai 			.gfp_mask = gfp_mask,
564b0dedc49SKirill Tkhai 			.nid = nid,
565b0dedc49SKirill Tkhai 			.memcg = memcg,
566b0dedc49SKirill Tkhai 		};
567b0dedc49SKirill Tkhai 		struct shrinker *shrinker;
568b0dedc49SKirill Tkhai 
569b0dedc49SKirill Tkhai 		shrinker = idr_find(&shrinker_idr, i);
5707e010df5SKirill Tkhai 		if (unlikely(!shrinker || shrinker == SHRINKER_REGISTERING)) {
5717e010df5SKirill Tkhai 			if (!shrinker)
572b0dedc49SKirill Tkhai 				clear_bit(i, map->map);
573b0dedc49SKirill Tkhai 			continue;
574b0dedc49SKirill Tkhai 		}
575b0dedc49SKirill Tkhai 
5760a432dcbSYang Shi 		/* Call non-slab shrinkers even though kmem is disabled */
5770a432dcbSYang Shi 		if (!memcg_kmem_enabled() &&
5780a432dcbSYang Shi 		    !(shrinker->flags & SHRINKER_NONSLAB))
5790a432dcbSYang Shi 			continue;
5800a432dcbSYang Shi 
581b0dedc49SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
582f90280d6SKirill Tkhai 		if (ret == SHRINK_EMPTY) {
583f90280d6SKirill Tkhai 			clear_bit(i, map->map);
584f90280d6SKirill Tkhai 			/*
585f90280d6SKirill Tkhai 			 * After the shrinker reported that it had no objects to
586f90280d6SKirill Tkhai 			 * free, but before we cleared the corresponding bit in
587f90280d6SKirill Tkhai 			 * the memcg shrinker map, a new object might have been
588f90280d6SKirill Tkhai 			 * added. To make sure, we have the bit set in this
589f90280d6SKirill Tkhai 			 * case, we invoke the shrinker one more time and reset
590f90280d6SKirill Tkhai 			 * the bit if it reports that it is not empty anymore.
591f90280d6SKirill Tkhai 			 * The memory barrier here pairs with the barrier in
592f90280d6SKirill Tkhai 			 * memcg_set_shrinker_bit():
593f90280d6SKirill Tkhai 			 *
594f90280d6SKirill Tkhai 			 * list_lru_add()     shrink_slab_memcg()
595f90280d6SKirill Tkhai 			 *   list_add_tail()    clear_bit()
596f90280d6SKirill Tkhai 			 *   <MB>               <MB>
597f90280d6SKirill Tkhai 			 *   set_bit()          do_shrink_slab()
598f90280d6SKirill Tkhai 			 */
599f90280d6SKirill Tkhai 			smp_mb__after_atomic();
600f90280d6SKirill Tkhai 			ret = do_shrink_slab(&sc, shrinker, priority);
6019b996468SKirill Tkhai 			if (ret == SHRINK_EMPTY)
6029b996468SKirill Tkhai 				ret = 0;
603f90280d6SKirill Tkhai 			else
604f90280d6SKirill Tkhai 				memcg_set_shrinker_bit(memcg, nid, i);
605f90280d6SKirill Tkhai 		}
606b0dedc49SKirill Tkhai 		freed += ret;
607b0dedc49SKirill Tkhai 
608b0dedc49SKirill Tkhai 		if (rwsem_is_contended(&shrinker_rwsem)) {
609b0dedc49SKirill Tkhai 			freed = freed ? : 1;
610b0dedc49SKirill Tkhai 			break;
611b0dedc49SKirill Tkhai 		}
612b0dedc49SKirill Tkhai 	}
613b0dedc49SKirill Tkhai unlock:
614b0dedc49SKirill Tkhai 	up_read(&shrinker_rwsem);
615b0dedc49SKirill Tkhai 	return freed;
616b0dedc49SKirill Tkhai }
6170a432dcbSYang Shi #else /* CONFIG_MEMCG */
618b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
619b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
620b0dedc49SKirill Tkhai {
621b0dedc49SKirill Tkhai 	return 0;
622b0dedc49SKirill Tkhai }
6230a432dcbSYang Shi #endif /* CONFIG_MEMCG */
624b0dedc49SKirill Tkhai 
6256b4f7799SJohannes Weiner /**
626cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
6276b4f7799SJohannes Weiner  * @gfp_mask: allocation context
6286b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
629cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
6309092c71bSJosef Bacik  * @priority: the reclaim priority
6311d3d4437SGlauber Costa  *
6326b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
6331d3d4437SGlauber Costa  *
6346b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
6356b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
6361d3d4437SGlauber Costa  *
637aeed1d32SVladimir Davydov  * @memcg specifies the memory cgroup to target. Unaware shrinkers
638aeed1d32SVladimir Davydov  * are called only if it is the root cgroup.
639cb731d6cSVladimir Davydov  *
6409092c71bSJosef Bacik  * @priority is sc->priority, we take the number of objects and >> by priority
6419092c71bSJosef Bacik  * in order to get the scan target.
6421d3d4437SGlauber Costa  *
6436b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
6441d3d4437SGlauber Costa  */
645cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
646cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
6479092c71bSJosef Bacik 				 int priority)
6481d3d4437SGlauber Costa {
649b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
6501d3d4437SGlauber Costa 	struct shrinker *shrinker;
6511d3d4437SGlauber Costa 
652fa1e512fSYang Shi 	/*
653fa1e512fSYang Shi 	 * The root memcg might be allocated even though memcg is disabled
654fa1e512fSYang Shi 	 * via "cgroup_disable=memory" boot parameter.  This could make
655fa1e512fSYang Shi 	 * mem_cgroup_is_root() return false, then just run memcg slab
656fa1e512fSYang Shi 	 * shrink, but skip global shrink.  This may result in premature
657fa1e512fSYang Shi 	 * oom.
658fa1e512fSYang Shi 	 */
659fa1e512fSYang Shi 	if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
660b0dedc49SKirill Tkhai 		return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
661cb731d6cSVladimir Davydov 
662e830c63aSTetsuo Handa 	if (!down_read_trylock(&shrinker_rwsem))
6631d3d4437SGlauber Costa 		goto out;
6641d3d4437SGlauber Costa 
6651d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
6666b4f7799SJohannes Weiner 		struct shrink_control sc = {
6676b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
6686b4f7799SJohannes Weiner 			.nid = nid,
669cb731d6cSVladimir Davydov 			.memcg = memcg,
6706b4f7799SJohannes Weiner 		};
6716b4f7799SJohannes Weiner 
6729b996468SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
6739b996468SKirill Tkhai 		if (ret == SHRINK_EMPTY)
6749b996468SKirill Tkhai 			ret = 0;
6759b996468SKirill Tkhai 		freed += ret;
676e496612cSMinchan Kim 		/*
677e496612cSMinchan Kim 		 * Bail out if someone want to register a new shrinker to
67855b65a57SEthon Paul 		 * prevent the registration from being stalled for long periods
679e496612cSMinchan Kim 		 * by parallel ongoing shrinking.
680e496612cSMinchan Kim 		 */
681e496612cSMinchan Kim 		if (rwsem_is_contended(&shrinker_rwsem)) {
682e496612cSMinchan Kim 			freed = freed ? : 1;
683e496612cSMinchan Kim 			break;
684e496612cSMinchan Kim 		}
685ec97097bSVladimir Davydov 	}
6861d3d4437SGlauber Costa 
6871da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
688f06590bdSMinchan Kim out:
689f06590bdSMinchan Kim 	cond_resched();
69024f7c6b9SDave Chinner 	return freed;
6911da177e4SLinus Torvalds }
6921da177e4SLinus Torvalds 
693cb731d6cSVladimir Davydov void drop_slab_node(int nid)
694cb731d6cSVladimir Davydov {
695cb731d6cSVladimir Davydov 	unsigned long freed;
696cb731d6cSVladimir Davydov 
697cb731d6cSVladimir Davydov 	do {
698cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
699cb731d6cSVladimir Davydov 
700069c411dSChunxin Zang 		if (fatal_signal_pending(current))
701069c411dSChunxin Zang 			return;
702069c411dSChunxin Zang 
703cb731d6cSVladimir Davydov 		freed = 0;
704aeed1d32SVladimir Davydov 		memcg = mem_cgroup_iter(NULL, NULL, NULL);
705cb731d6cSVladimir Davydov 		do {
7069092c71bSJosef Bacik 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
707cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
708cb731d6cSVladimir Davydov 	} while (freed > 10);
709cb731d6cSVladimir Davydov }
710cb731d6cSVladimir Davydov 
711cb731d6cSVladimir Davydov void drop_slab(void)
712cb731d6cSVladimir Davydov {
713cb731d6cSVladimir Davydov 	int nid;
714cb731d6cSVladimir Davydov 
715cb731d6cSVladimir Davydov 	for_each_online_node(nid)
716cb731d6cSVladimir Davydov 		drop_slab_node(nid);
717cb731d6cSVladimir Davydov }
718cb731d6cSVladimir Davydov 
7191da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
7201da177e4SLinus Torvalds {
721ceddc3a5SJohannes Weiner 	/*
722ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
72367891fffSMatthew Wilcox 	 * that isolated the page, the page cache and optional buffer
72467891fffSMatthew Wilcox 	 * heads at page->private.
725ceddc3a5SJohannes Weiner 	 */
7263efe62e4SMatthew Wilcox (Oracle) 	int page_cache_pins = thp_nr_pages(page);
72767891fffSMatthew Wilcox 	return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
7281da177e4SLinus Torvalds }
7291da177e4SLinus Torvalds 
730cb16556dSYang Shi static int may_write_to_inode(struct inode *inode)
7311da177e4SLinus Torvalds {
732930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
7331da177e4SLinus Torvalds 		return 1;
734703c2708STejun Heo 	if (!inode_write_congested(inode))
7351da177e4SLinus Torvalds 		return 1;
736703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
7371da177e4SLinus Torvalds 		return 1;
7381da177e4SLinus Torvalds 	return 0;
7391da177e4SLinus Torvalds }
7401da177e4SLinus Torvalds 
7411da177e4SLinus Torvalds /*
7421da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
7431da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
7441da177e4SLinus Torvalds  * fsync(), msync() or close().
7451da177e4SLinus Torvalds  *
7461da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
7471da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
7481da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
7491da177e4SLinus Torvalds  *
7501da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
7511da177e4SLinus Torvalds  * __GFP_FS.
7521da177e4SLinus Torvalds  */
7531da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
7541da177e4SLinus Torvalds 				struct page *page, int error)
7551da177e4SLinus Torvalds {
7567eaceaccSJens Axboe 	lock_page(page);
7573e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
7583e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
7591da177e4SLinus Torvalds 	unlock_page(page);
7601da177e4SLinus Torvalds }
7611da177e4SLinus Torvalds 
76204e62a29SChristoph Lameter /* possible outcome of pageout() */
76304e62a29SChristoph Lameter typedef enum {
76404e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
76504e62a29SChristoph Lameter 	PAGE_KEEP,
76604e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
76704e62a29SChristoph Lameter 	PAGE_ACTIVATE,
76804e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
76904e62a29SChristoph Lameter 	PAGE_SUCCESS,
77004e62a29SChristoph Lameter 	/* page is clean and locked */
77104e62a29SChristoph Lameter 	PAGE_CLEAN,
77204e62a29SChristoph Lameter } pageout_t;
77304e62a29SChristoph Lameter 
7741da177e4SLinus Torvalds /*
7751742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
7761742f19fSAndrew Morton  * Calls ->writepage().
7771da177e4SLinus Torvalds  */
778cb16556dSYang Shi static pageout_t pageout(struct page *page, struct address_space *mapping)
7791da177e4SLinus Torvalds {
7801da177e4SLinus Torvalds 	/*
7811da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
7821da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
7831da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
7841da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
7851da177e4SLinus Torvalds 	 * PagePrivate for that.
7861da177e4SLinus Torvalds 	 *
7878174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
7881da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
7891da177e4SLinus Torvalds 	 * will block.
7901da177e4SLinus Torvalds 	 *
7911da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
7921da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
7931da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
7941da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
7951da177e4SLinus Torvalds 	 */
7961da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
7971da177e4SLinus Torvalds 		return PAGE_KEEP;
7981da177e4SLinus Torvalds 	if (!mapping) {
7991da177e4SLinus Torvalds 		/*
8001da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
8011da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
8021da177e4SLinus Torvalds 		 */
803266cf658SDavid Howells 		if (page_has_private(page)) {
8041da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
8051da177e4SLinus Torvalds 				ClearPageDirty(page);
806b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
8071da177e4SLinus Torvalds 				return PAGE_CLEAN;
8081da177e4SLinus Torvalds 			}
8091da177e4SLinus Torvalds 		}
8101da177e4SLinus Torvalds 		return PAGE_KEEP;
8111da177e4SLinus Torvalds 	}
8121da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
8131da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
814cb16556dSYang Shi 	if (!may_write_to_inode(mapping->host))
8151da177e4SLinus Torvalds 		return PAGE_KEEP;
8161da177e4SLinus Torvalds 
8171da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
8181da177e4SLinus Torvalds 		int res;
8191da177e4SLinus Torvalds 		struct writeback_control wbc = {
8201da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
8211da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
822111ebb6eSOGAWA Hirofumi 			.range_start = 0,
823111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
8241da177e4SLinus Torvalds 			.for_reclaim = 1,
8251da177e4SLinus Torvalds 		};
8261da177e4SLinus Torvalds 
8271da177e4SLinus Torvalds 		SetPageReclaim(page);
8281da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
8291da177e4SLinus Torvalds 		if (res < 0)
8301da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
831994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
8321da177e4SLinus Torvalds 			ClearPageReclaim(page);
8331da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
8341da177e4SLinus Torvalds 		}
835c661b078SAndy Whitcroft 
8361da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
8371da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
8381da177e4SLinus Torvalds 			ClearPageReclaim(page);
8391da177e4SLinus Torvalds 		}
8403aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
841c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
8421da177e4SLinus Torvalds 		return PAGE_SUCCESS;
8431da177e4SLinus Torvalds 	}
8441da177e4SLinus Torvalds 
8451da177e4SLinus Torvalds 	return PAGE_CLEAN;
8461da177e4SLinus Torvalds }
8471da177e4SLinus Torvalds 
848a649fd92SAndrew Morton /*
849e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
850e286781dSNick Piggin  * gets returned with a refcount of 0.
851a649fd92SAndrew Morton  */
852a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
853b910718aSJohannes Weiner 			    bool reclaimed, struct mem_cgroup *target_memcg)
85449d2e9ccSChristoph Lameter {
855c4843a75SGreg Thelen 	unsigned long flags;
856bd4c82c2SHuang Ying 	int refcount;
857aae466b0SJoonsoo Kim 	void *shadow = NULL;
858c4843a75SGreg Thelen 
85928e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
86028e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
86149d2e9ccSChristoph Lameter 
862b93b0163SMatthew Wilcox 	xa_lock_irqsave(&mapping->i_pages, flags);
86349d2e9ccSChristoph Lameter 	/*
8640fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
8650fd0e6b0SNick Piggin 	 *
8660fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
8670fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
8680fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
8690fd0e6b0SNick Piggin 	 * here, then the following race may occur:
8700fd0e6b0SNick Piggin 	 *
8710fd0e6b0SNick Piggin 	 * get_user_pages(&page);
8720fd0e6b0SNick Piggin 	 * [user mapping goes away]
8730fd0e6b0SNick Piggin 	 * write_to(page);
8740fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
8750fd0e6b0SNick Piggin 	 * SetPageDirty(page);
8760fd0e6b0SNick Piggin 	 * put_page(page);
8770fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
8780fd0e6b0SNick Piggin 	 *
8790fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
8800fd0e6b0SNick Piggin 	 *
8810fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
8820fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
8830139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
8840fd0e6b0SNick Piggin 	 *
8850fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
886b93b0163SMatthew Wilcox 	 * and thus under the i_pages lock, then this ordering is not required.
88749d2e9ccSChristoph Lameter 	 */
888906d278dSWilliam Kucharski 	refcount = 1 + compound_nr(page);
889bd4c82c2SHuang Ying 	if (!page_ref_freeze(page, refcount))
89049d2e9ccSChristoph Lameter 		goto cannot_free;
8911c4c3b99SJiang Biao 	/* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
892e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
893bd4c82c2SHuang Ying 		page_ref_unfreeze(page, refcount);
89449d2e9ccSChristoph Lameter 		goto cannot_free;
895e286781dSNick Piggin 	}
89649d2e9ccSChristoph Lameter 
89749d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
89849d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
8990a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
900aae466b0SJoonsoo Kim 		if (reclaimed && !mapping_exiting(mapping))
901aae466b0SJoonsoo Kim 			shadow = workingset_eviction(page, target_memcg);
902aae466b0SJoonsoo Kim 		__delete_from_swap_cache(page, swap, shadow);
903b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
90475f6d6d2SMinchan Kim 		put_swap_page(page, swap);
905e286781dSNick Piggin 	} else {
9066072d13cSLinus Torvalds 		void (*freepage)(struct page *);
9076072d13cSLinus Torvalds 
9086072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
909a528910eSJohannes Weiner 		/*
910a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
911a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
912a528910eSJohannes Weiner 		 *
913a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
914238c3046Sdylan-meiners 		 * already exiting.  This is not just an optimization,
915a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
916a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
917a528910eSJohannes Weiner 		 * back.
918f9fe48beSRoss Zwisler 		 *
919f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
920f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
921f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
922f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
923b93b0163SMatthew Wilcox 		 * same address_space.
924a528910eSJohannes Weiner 		 */
9259de4f22aSHuang Ying 		if (reclaimed && page_is_file_lru(page) &&
926f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
927b910718aSJohannes Weiner 			shadow = workingset_eviction(page, target_memcg);
92862cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
929b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
9306072d13cSLinus Torvalds 
9316072d13cSLinus Torvalds 		if (freepage != NULL)
9326072d13cSLinus Torvalds 			freepage(page);
933e286781dSNick Piggin 	}
934e286781dSNick Piggin 
93549d2e9ccSChristoph Lameter 	return 1;
93649d2e9ccSChristoph Lameter 
93749d2e9ccSChristoph Lameter cannot_free:
938b93b0163SMatthew Wilcox 	xa_unlock_irqrestore(&mapping->i_pages, flags);
93949d2e9ccSChristoph Lameter 	return 0;
94049d2e9ccSChristoph Lameter }
94149d2e9ccSChristoph Lameter 
9421da177e4SLinus Torvalds /*
943e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
944e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
945e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
946e286781dSNick Piggin  * this page.
947e286781dSNick Piggin  */
948e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
949e286781dSNick Piggin {
950b910718aSJohannes Weiner 	if (__remove_mapping(mapping, page, false, NULL)) {
951e286781dSNick Piggin 		/*
952e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
953e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
954e286781dSNick Piggin 		 * atomic operation.
955e286781dSNick Piggin 		 */
956fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
957e286781dSNick Piggin 		return 1;
958e286781dSNick Piggin 	}
959e286781dSNick Piggin 	return 0;
960e286781dSNick Piggin }
961e286781dSNick Piggin 
962894bc310SLee Schermerhorn /**
963894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
964894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
965894bc310SLee Schermerhorn  *
966894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
967894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
968894bc310SLee Schermerhorn  *
969894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
970894bc310SLee Schermerhorn  */
971894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
972894bc310SLee Schermerhorn {
973c53954a0SMel Gorman 	lru_cache_add(page);
974894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
975894bc310SLee Schermerhorn }
976894bc310SLee Schermerhorn 
977dfc8d636SJohannes Weiner enum page_references {
978dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
979dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
98064574746SJohannes Weiner 	PAGEREF_KEEP,
981dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
982dfc8d636SJohannes Weiner };
983dfc8d636SJohannes Weiner 
984dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
985dfc8d636SJohannes Weiner 						  struct scan_control *sc)
986dfc8d636SJohannes Weiner {
98764574746SJohannes Weiner 	int referenced_ptes, referenced_page;
988dfc8d636SJohannes Weiner 	unsigned long vm_flags;
989dfc8d636SJohannes Weiner 
990c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
991c3ac9a8aSJohannes Weiner 					  &vm_flags);
99264574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
993dfc8d636SJohannes Weiner 
994dfc8d636SJohannes Weiner 	/*
995dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
996dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
997dfc8d636SJohannes Weiner 	 */
998dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
999dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
1000dfc8d636SJohannes Weiner 
100164574746SJohannes Weiner 	if (referenced_ptes) {
100264574746SJohannes Weiner 		/*
100364574746SJohannes Weiner 		 * All mapped pages start out with page table
100464574746SJohannes Weiner 		 * references from the instantiating fault, so we need
100564574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
100664574746SJohannes Weiner 		 * than once.
100764574746SJohannes Weiner 		 *
100864574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
100964574746SJohannes Weiner 		 * inactive list.  Another page table reference will
101064574746SJohannes Weiner 		 * lead to its activation.
101164574746SJohannes Weiner 		 *
101264574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
101364574746SJohannes Weiner 		 * so that recently deactivated but used pages are
101464574746SJohannes Weiner 		 * quickly recovered.
101564574746SJohannes Weiner 		 */
101664574746SJohannes Weiner 		SetPageReferenced(page);
101764574746SJohannes Weiner 
101834dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
1019dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
1020dfc8d636SJohannes Weiner 
1021c909e993SKonstantin Khlebnikov 		/*
1022c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
1023c909e993SKonstantin Khlebnikov 		 */
1024b518154eSJoonsoo Kim 		if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
1025c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
1026c909e993SKonstantin Khlebnikov 
102764574746SJohannes Weiner 		return PAGEREF_KEEP;
102864574746SJohannes Weiner 	}
102964574746SJohannes Weiner 
1030dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
10312e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
1032dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
103364574746SJohannes Weiner 
103464574746SJohannes Weiner 	return PAGEREF_RECLAIM;
1035dfc8d636SJohannes Weiner }
1036dfc8d636SJohannes Weiner 
1037e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
1038e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
1039e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
1040e2be15f6SMel Gorman {
1041b4597226SMel Gorman 	struct address_space *mapping;
1042b4597226SMel Gorman 
1043e2be15f6SMel Gorman 	/*
1044e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
1045e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
1046e2be15f6SMel Gorman 	 */
10479de4f22aSHuang Ying 	if (!page_is_file_lru(page) ||
1048802a3a92SShaohua Li 	    (PageAnon(page) && !PageSwapBacked(page))) {
1049e2be15f6SMel Gorman 		*dirty = false;
1050e2be15f6SMel Gorman 		*writeback = false;
1051e2be15f6SMel Gorman 		return;
1052e2be15f6SMel Gorman 	}
1053e2be15f6SMel Gorman 
1054e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
1055e2be15f6SMel Gorman 	*dirty = PageDirty(page);
1056e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
1057b4597226SMel Gorman 
1058b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
1059b4597226SMel Gorman 	if (!page_has_private(page))
1060b4597226SMel Gorman 		return;
1061b4597226SMel Gorman 
1062b4597226SMel Gorman 	mapping = page_mapping(page);
1063b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
1064b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1065e2be15f6SMel Gorman }
1066e2be15f6SMel Gorman 
1067e286781dSNick Piggin /*
10681742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
10691da177e4SLinus Torvalds  */
1070730ec8c0SManinder Singh static unsigned int shrink_page_list(struct list_head *page_list,
1071599d0c95SMel Gorman 				     struct pglist_data *pgdat,
1072f84f6e2bSMel Gorman 				     struct scan_control *sc,
10733c710c1aSMichal Hocko 				     struct reclaim_stat *stat,
10748940b34aSMinchan Kim 				     bool ignore_references)
10751da177e4SLinus Torvalds {
10761da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
1077abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
1078730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
1079730ec8c0SManinder Singh 	unsigned int pgactivate = 0;
10801da177e4SLinus Torvalds 
1081060f005fSKirill Tkhai 	memset(stat, 0, sizeof(*stat));
10821da177e4SLinus Torvalds 	cond_resched();
10831da177e4SLinus Torvalds 
10841da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
10851da177e4SLinus Torvalds 		struct address_space *mapping;
10861da177e4SLinus Torvalds 		struct page *page;
10878940b34aSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM;
10884b793062SKirill Tkhai 		bool dirty, writeback, may_enter_fs;
108998879b3bSYang Shi 		unsigned int nr_pages;
10901da177e4SLinus Torvalds 
10911da177e4SLinus Torvalds 		cond_resched();
10921da177e4SLinus Torvalds 
10931da177e4SLinus Torvalds 		page = lru_to_page(page_list);
10941da177e4SLinus Torvalds 		list_del(&page->lru);
10951da177e4SLinus Torvalds 
1096529ae9aaSNick Piggin 		if (!trylock_page(page))
10971da177e4SLinus Torvalds 			goto keep;
10981da177e4SLinus Torvalds 
1099309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
11001da177e4SLinus Torvalds 
1101d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
110298879b3bSYang Shi 
110398879b3bSYang Shi 		/* Account the number of base pages even though THP */
110498879b3bSYang Shi 		sc->nr_scanned += nr_pages;
110580e43426SChristoph Lameter 
110639b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
1107ad6b6704SMinchan Kim 			goto activate_locked;
1108894bc310SLee Schermerhorn 
1109a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
111080e43426SChristoph Lameter 			goto keep_locked;
111180e43426SChristoph Lameter 
1112c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1113c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1114c661b078SAndy Whitcroft 
1115e62e384eSMichal Hocko 		/*
1116894befecSAndrey Ryabinin 		 * The number of dirty pages determines if a node is marked
1117e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
1118e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
1119e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
1120e2be15f6SMel Gorman 		 */
1121e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
1122e2be15f6SMel Gorman 		if (dirty || writeback)
1123060f005fSKirill Tkhai 			stat->nr_dirty++;
1124e2be15f6SMel Gorman 
1125e2be15f6SMel Gorman 		if (dirty && !writeback)
1126060f005fSKirill Tkhai 			stat->nr_unqueued_dirty++;
1127e2be15f6SMel Gorman 
1128d04e8acdSMel Gorman 		/*
1129d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
1130d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
1131d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
1132d04e8acdSMel Gorman 		 * end of the LRU a second time.
1133d04e8acdSMel Gorman 		 */
1134e2be15f6SMel Gorman 		mapping = page_mapping(page);
11351da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
1136703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
1137d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
1138060f005fSKirill Tkhai 			stat->nr_congested++;
1139e2be15f6SMel Gorman 
1140e2be15f6SMel Gorman 		/*
1141283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
1142283aba9fSMel Gorman 		 * are three cases to consider.
1143e62e384eSMichal Hocko 		 *
1144283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
1145283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
1146283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
1147283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
1148283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
1149283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
1150283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
1151b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
1152b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
1153c3b94f44SHugh Dickins 		 *
115497c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
1155ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1156ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1157ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
115897c9341fSTejun Heo 		 *    reclaim and continue scanning.
1159283aba9fSMel Gorman 		 *
1160ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1161ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1162283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1163283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1164283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1165283aba9fSMel Gorman 		 *    would probably show more reasons.
1166283aba9fSMel Gorman 		 *
11677fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1168283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1169283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1170283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1171283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1172c55e8d03SJohannes Weiner 		 *
1173c55e8d03SJohannes Weiner 		 * In cases 1) and 2) we activate the pages to get them out of
1174c55e8d03SJohannes Weiner 		 * the way while we continue scanning for clean pages on the
1175c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1176c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1177c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1178c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1179c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1180c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1181e62e384eSMichal Hocko 		 */
1182283aba9fSMel Gorman 		if (PageWriteback(page)) {
1183283aba9fSMel Gorman 			/* Case 1 above */
1184283aba9fSMel Gorman 			if (current_is_kswapd() &&
1185283aba9fSMel Gorman 			    PageReclaim(page) &&
1186599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1187060f005fSKirill Tkhai 				stat->nr_immediate++;
1188c55e8d03SJohannes Weiner 				goto activate_locked;
1189283aba9fSMel Gorman 
1190283aba9fSMel Gorman 			/* Case 2 above */
1191b5ead35eSJohannes Weiner 			} else if (writeback_throttling_sane(sc) ||
1192ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1193c3b94f44SHugh Dickins 				/*
1194c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1195c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1196c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1197c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1198c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1199c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1200c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1201c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1202c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1203c3b94f44SHugh Dickins 				 */
1204c3b94f44SHugh Dickins 				SetPageReclaim(page);
1205060f005fSKirill Tkhai 				stat->nr_writeback++;
1206c55e8d03SJohannes Weiner 				goto activate_locked;
1207283aba9fSMel Gorman 
1208283aba9fSMel Gorman 			/* Case 3 above */
1209283aba9fSMel Gorman 			} else {
12107fadc820SHugh Dickins 				unlock_page(page);
1211c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
12127fadc820SHugh Dickins 				/* then go back and try same page again */
12137fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
12147fadc820SHugh Dickins 				continue;
1215e62e384eSMichal Hocko 			}
1216283aba9fSMel Gorman 		}
12171da177e4SLinus Torvalds 
12188940b34aSMinchan Kim 		if (!ignore_references)
12196a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
122002c6de8dSMinchan Kim 
1221dfc8d636SJohannes Weiner 		switch (references) {
1222dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
12231da177e4SLinus Torvalds 			goto activate_locked;
122464574746SJohannes Weiner 		case PAGEREF_KEEP:
122598879b3bSYang Shi 			stat->nr_ref_keep += nr_pages;
122664574746SJohannes Weiner 			goto keep_locked;
1227dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1228dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1229dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1230dfc8d636SJohannes Weiner 		}
12311da177e4SLinus Torvalds 
12321da177e4SLinus Torvalds 		/*
12331da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
12341da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1235802a3a92SShaohua Li 		 * Lazyfree page could be freed directly
12361da177e4SLinus Torvalds 		 */
1237bd4c82c2SHuang Ying 		if (PageAnon(page) && PageSwapBacked(page)) {
1238bd4c82c2SHuang Ying 			if (!PageSwapCache(page)) {
123963eb6b93SHugh Dickins 				if (!(sc->gfp_mask & __GFP_IO))
124063eb6b93SHugh Dickins 					goto keep_locked;
1241747552b1SHuang Ying 				if (PageTransHuge(page)) {
1242b8f593cdSHuang Ying 					/* cannot split THP, skip it */
1243747552b1SHuang Ying 					if (!can_split_huge_page(page, NULL))
1244b8f593cdSHuang Ying 						goto activate_locked;
1245747552b1SHuang Ying 					/*
1246747552b1SHuang Ying 					 * Split pages without a PMD map right
1247747552b1SHuang Ying 					 * away. Chances are some or all of the
1248747552b1SHuang Ying 					 * tail pages can be freed without IO.
1249747552b1SHuang Ying 					 */
1250747552b1SHuang Ying 					if (!compound_mapcount(page) &&
1251bd4c82c2SHuang Ying 					    split_huge_page_to_list(page,
1252bd4c82c2SHuang Ying 								    page_list))
1253747552b1SHuang Ying 						goto activate_locked;
1254747552b1SHuang Ying 				}
12550f074658SMinchan Kim 				if (!add_to_swap(page)) {
12560f074658SMinchan Kim 					if (!PageTransHuge(page))
125798879b3bSYang Shi 						goto activate_locked_split;
1258bd4c82c2SHuang Ying 					/* Fallback to swap normal pages */
1259bd4c82c2SHuang Ying 					if (split_huge_page_to_list(page,
1260bd4c82c2SHuang Ying 								    page_list))
12610f074658SMinchan Kim 						goto activate_locked;
1262fe490cc0SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1263fe490cc0SHuang Ying 					count_vm_event(THP_SWPOUT_FALLBACK);
1264fe490cc0SHuang Ying #endif
12650f074658SMinchan Kim 					if (!add_to_swap(page))
126698879b3bSYang Shi 						goto activate_locked_split;
12670f074658SMinchan Kim 				}
12680f074658SMinchan Kim 
12694b793062SKirill Tkhai 				may_enter_fs = true;
12701da177e4SLinus Torvalds 
1271e2be15f6SMel Gorman 				/* Adding to swap updated mapping */
12721da177e4SLinus Torvalds 				mapping = page_mapping(page);
1273bd4c82c2SHuang Ying 			}
12747751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
12757751b2daSKirill A. Shutemov 			/* Split file THP */
12767751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
12777751b2daSKirill A. Shutemov 				goto keep_locked;
1278e2be15f6SMel Gorman 		}
12791da177e4SLinus Torvalds 
12801da177e4SLinus Torvalds 		/*
128198879b3bSYang Shi 		 * THP may get split above, need minus tail pages and update
128298879b3bSYang Shi 		 * nr_pages to avoid accounting tail pages twice.
128398879b3bSYang Shi 		 *
128498879b3bSYang Shi 		 * The tail pages that are added into swap cache successfully
128598879b3bSYang Shi 		 * reach here.
128698879b3bSYang Shi 		 */
128798879b3bSYang Shi 		if ((nr_pages > 1) && !PageTransHuge(page)) {
128898879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
128998879b3bSYang Shi 			nr_pages = 1;
129098879b3bSYang Shi 		}
129198879b3bSYang Shi 
129298879b3bSYang Shi 		/*
12931da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
12941da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
12951da177e4SLinus Torvalds 		 */
1296802a3a92SShaohua Li 		if (page_mapped(page)) {
1297013339dfSShakeel Butt 			enum ttu_flags flags = TTU_BATCH_FLUSH;
12981f318a9bSJaewon Kim 			bool was_swapbacked = PageSwapBacked(page);
1299bd4c82c2SHuang Ying 
1300bd4c82c2SHuang Ying 			if (unlikely(PageTransHuge(page)))
1301bd4c82c2SHuang Ying 				flags |= TTU_SPLIT_HUGE_PMD;
13021f318a9bSJaewon Kim 
1303bd4c82c2SHuang Ying 			if (!try_to_unmap(page, flags)) {
130498879b3bSYang Shi 				stat->nr_unmap_fail += nr_pages;
13051f318a9bSJaewon Kim 				if (!was_swapbacked && PageSwapBacked(page))
13061f318a9bSJaewon Kim 					stat->nr_lazyfree_fail += nr_pages;
13071da177e4SLinus Torvalds 				goto activate_locked;
13081da177e4SLinus Torvalds 			}
13091da177e4SLinus Torvalds 		}
13101da177e4SLinus Torvalds 
13111da177e4SLinus Torvalds 		if (PageDirty(page)) {
1312ee72886dSMel Gorman 			/*
13134eda4823SJohannes Weiner 			 * Only kswapd can writeback filesystem pages
13144eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
13154eda4823SJohannes Weiner 			 * injecting inefficient single-page IO into
13164eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
13174eda4823SJohannes Weiner 			 * write pages when we've encountered many
13184eda4823SJohannes Weiner 			 * dirty pages, and when we've already scanned
13194eda4823SJohannes Weiner 			 * the rest of the LRU for clean pages and see
13204eda4823SJohannes Weiner 			 * the same dirty pages again (PageReclaim).
1321ee72886dSMel Gorman 			 */
13229de4f22aSHuang Ying 			if (page_is_file_lru(page) &&
13234eda4823SJohannes Weiner 			    (!current_is_kswapd() || !PageReclaim(page) ||
1324599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
132549ea7eb6SMel Gorman 				/*
132649ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
132749ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
132849ea7eb6SMel Gorman 				 * except we already have the page isolated
132949ea7eb6SMel Gorman 				 * and know it's dirty
133049ea7eb6SMel Gorman 				 */
1331c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
133249ea7eb6SMel Gorman 				SetPageReclaim(page);
133349ea7eb6SMel Gorman 
1334c55e8d03SJohannes Weiner 				goto activate_locked;
1335ee72886dSMel Gorman 			}
1336ee72886dSMel Gorman 
1337dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
13381da177e4SLinus Torvalds 				goto keep_locked;
13394dd4b920SAndrew Morton 			if (!may_enter_fs)
13401da177e4SLinus Torvalds 				goto keep_locked;
134152a8363eSChristoph Lameter 			if (!sc->may_writepage)
13421da177e4SLinus Torvalds 				goto keep_locked;
13431da177e4SLinus Torvalds 
1344d950c947SMel Gorman 			/*
1345d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1346d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1347d950c947SMel Gorman 			 * starts and then write it out here.
1348d950c947SMel Gorman 			 */
1349d950c947SMel Gorman 			try_to_unmap_flush_dirty();
1350cb16556dSYang Shi 			switch (pageout(page, mapping)) {
13511da177e4SLinus Torvalds 			case PAGE_KEEP:
13521da177e4SLinus Torvalds 				goto keep_locked;
13531da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
13541da177e4SLinus Torvalds 				goto activate_locked;
13551da177e4SLinus Torvalds 			case PAGE_SUCCESS:
13566c357848SMatthew Wilcox (Oracle) 				stat->nr_pageout += thp_nr_pages(page);
135796f8bf4fSJohannes Weiner 
13587d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
135941ac1999SMel Gorman 					goto keep;
13607d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
13611da177e4SLinus Torvalds 					goto keep;
13627d3579e8SKOSAKI Motohiro 
13631da177e4SLinus Torvalds 				/*
13641da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
13651da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
13661da177e4SLinus Torvalds 				 */
1367529ae9aaSNick Piggin 				if (!trylock_page(page))
13681da177e4SLinus Torvalds 					goto keep;
13691da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
13701da177e4SLinus Torvalds 					goto keep_locked;
13711da177e4SLinus Torvalds 				mapping = page_mapping(page);
137201359eb2SGustavo A. R. Silva 				fallthrough;
13731da177e4SLinus Torvalds 			case PAGE_CLEAN:
13741da177e4SLinus Torvalds 				; /* try to free the page below */
13751da177e4SLinus Torvalds 			}
13761da177e4SLinus Torvalds 		}
13771da177e4SLinus Torvalds 
13781da177e4SLinus Torvalds 		/*
13791da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
13801da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
13811da177e4SLinus Torvalds 		 * the page as well.
13821da177e4SLinus Torvalds 		 *
13831da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
13841da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
13851da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
13861da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
13871da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
13881da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
13891da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
13901da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
13911da177e4SLinus Torvalds 		 *
13921da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
13931da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
1394d12b8951SYang Shi 		 * truncate_cleanup_page().  We try to drop those buffers here
13951da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
13961da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
13971da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
13981da177e4SLinus Torvalds 		 */
1399266cf658SDavid Howells 		if (page_has_private(page)) {
14001da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
14011da177e4SLinus Torvalds 				goto activate_locked;
1402e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1403e286781dSNick Piggin 				unlock_page(page);
1404e286781dSNick Piggin 				if (put_page_testzero(page))
14051da177e4SLinus Torvalds 					goto free_it;
1406e286781dSNick Piggin 				else {
1407e286781dSNick Piggin 					/*
1408e286781dSNick Piggin 					 * rare race with speculative reference.
1409e286781dSNick Piggin 					 * the speculative reference will free
1410e286781dSNick Piggin 					 * this page shortly, so we may
1411e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1412e286781dSNick Piggin 					 * leave it off the LRU).
1413e286781dSNick Piggin 					 */
1414e286781dSNick Piggin 					nr_reclaimed++;
1415e286781dSNick Piggin 					continue;
1416e286781dSNick Piggin 				}
1417e286781dSNick Piggin 			}
14181da177e4SLinus Torvalds 		}
14191da177e4SLinus Torvalds 
1420802a3a92SShaohua Li 		if (PageAnon(page) && !PageSwapBacked(page)) {
1421802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
1422802a3a92SShaohua Li 			if (!page_ref_freeze(page, 1))
142349d2e9ccSChristoph Lameter 				goto keep_locked;
1424802a3a92SShaohua Li 			if (PageDirty(page)) {
1425802a3a92SShaohua Li 				page_ref_unfreeze(page, 1);
1426802a3a92SShaohua Li 				goto keep_locked;
1427802a3a92SShaohua Li 			}
14281da177e4SLinus Torvalds 
1429802a3a92SShaohua Li 			count_vm_event(PGLAZYFREED);
14302262185cSRoman Gushchin 			count_memcg_page_event(page, PGLAZYFREED);
1431b910718aSJohannes Weiner 		} else if (!mapping || !__remove_mapping(mapping, page, true,
1432b910718aSJohannes Weiner 							 sc->target_mem_cgroup))
1433802a3a92SShaohua Li 			goto keep_locked;
14349a1ea439SHugh Dickins 
14359a1ea439SHugh Dickins 		unlock_page(page);
1436e286781dSNick Piggin free_it:
143798879b3bSYang Shi 		/*
143898879b3bSYang Shi 		 * THP may get swapped out in a whole, need account
143998879b3bSYang Shi 		 * all base pages.
144098879b3bSYang Shi 		 */
144198879b3bSYang Shi 		nr_reclaimed += nr_pages;
1442abe4c3b5SMel Gorman 
1443abe4c3b5SMel Gorman 		/*
1444abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1445abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1446abe4c3b5SMel Gorman 		 */
14477ae88534SYang Shi 		if (unlikely(PageTransHuge(page)))
1448ff45fc3cSMatthew Wilcox (Oracle) 			destroy_compound_page(page);
14497ae88534SYang Shi 		else
1450abe4c3b5SMel Gorman 			list_add(&page->lru, &free_pages);
14511da177e4SLinus Torvalds 		continue;
14521da177e4SLinus Torvalds 
145398879b3bSYang Shi activate_locked_split:
145498879b3bSYang Shi 		/*
145598879b3bSYang Shi 		 * The tail pages that are failed to add into swap cache
145698879b3bSYang Shi 		 * reach here.  Fixup nr_scanned and nr_pages.
145798879b3bSYang Shi 		 */
145898879b3bSYang Shi 		if (nr_pages > 1) {
145998879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
146098879b3bSYang Shi 			nr_pages = 1;
146198879b3bSYang Shi 		}
14621da177e4SLinus Torvalds activate_locked:
146368a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
1464ad6b6704SMinchan Kim 		if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1465ad6b6704SMinchan Kim 						PageMlocked(page)))
1466a2c43eedSHugh Dickins 			try_to_free_swap(page);
1467309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
1468ad6b6704SMinchan Kim 		if (!PageMlocked(page)) {
14699de4f22aSHuang Ying 			int type = page_is_file_lru(page);
14701da177e4SLinus Torvalds 			SetPageActive(page);
147198879b3bSYang Shi 			stat->nr_activate[type] += nr_pages;
14722262185cSRoman Gushchin 			count_memcg_page_event(page, PGACTIVATE);
1473ad6b6704SMinchan Kim 		}
14741da177e4SLinus Torvalds keep_locked:
14751da177e4SLinus Torvalds 		unlock_page(page);
14761da177e4SLinus Torvalds keep:
14771da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1478309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
14791da177e4SLinus Torvalds 	}
1480abe4c3b5SMel Gorman 
148198879b3bSYang Shi 	pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
148298879b3bSYang Shi 
1483747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
148472b252aeSMel Gorman 	try_to_unmap_flush();
14852d4894b5SMel Gorman 	free_unref_page_list(&free_pages);
1486abe4c3b5SMel Gorman 
14871da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1488886cf190SKirill Tkhai 	count_vm_events(PGACTIVATE, pgactivate);
14890a31bc97SJohannes Weiner 
149005ff5137SAndrew Morton 	return nr_reclaimed;
14911da177e4SLinus Torvalds }
14921da177e4SLinus Torvalds 
1493730ec8c0SManinder Singh unsigned int reclaim_clean_pages_from_list(struct zone *zone,
149402c6de8dSMinchan Kim 					    struct list_head *page_list)
149502c6de8dSMinchan Kim {
149602c6de8dSMinchan Kim 	struct scan_control sc = {
149702c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
149802c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
149902c6de8dSMinchan Kim 		.may_unmap = 1,
150002c6de8dSMinchan Kim 	};
15011f318a9bSJaewon Kim 	struct reclaim_stat stat;
1502730ec8c0SManinder Singh 	unsigned int nr_reclaimed;
150302c6de8dSMinchan Kim 	struct page *page, *next;
150402c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
150502c6de8dSMinchan Kim 
150602c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
15079de4f22aSHuang Ying 		if (page_is_file_lru(page) && !PageDirty(page) &&
1508a58f2cefSMinchan Kim 		    !__PageMovable(page) && !PageUnevictable(page)) {
150902c6de8dSMinchan Kim 			ClearPageActive(page);
151002c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
151102c6de8dSMinchan Kim 		}
151202c6de8dSMinchan Kim 	}
151302c6de8dSMinchan Kim 
15141f318a9bSJaewon Kim 	nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1515013339dfSShakeel Butt 					&stat, true);
151602c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
15172da9f630SNicholas Piggin 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
15182da9f630SNicholas Piggin 			    -(long)nr_reclaimed);
15191f318a9bSJaewon Kim 	/*
15201f318a9bSJaewon Kim 	 * Since lazyfree pages are isolated from file LRU from the beginning,
15211f318a9bSJaewon Kim 	 * they will rotate back to anonymous LRU in the end if it failed to
15221f318a9bSJaewon Kim 	 * discard so isolated count will be mismatched.
15231f318a9bSJaewon Kim 	 * Compensate the isolated count for both LRU lists.
15241f318a9bSJaewon Kim 	 */
15251f318a9bSJaewon Kim 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
15261f318a9bSJaewon Kim 			    stat.nr_lazyfree_fail);
15271f318a9bSJaewon Kim 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
15282da9f630SNicholas Piggin 			    -(long)stat.nr_lazyfree_fail);
15291f318a9bSJaewon Kim 	return nr_reclaimed;
153002c6de8dSMinchan Kim }
153102c6de8dSMinchan Kim 
15325ad333ebSAndy Whitcroft /*
15335ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
15345ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
15355ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
15365ad333ebSAndy Whitcroft  *
15375ad333ebSAndy Whitcroft  * page:	page to consider
15385ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
15395ad333ebSAndy Whitcroft  *
15405ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
15415ad333ebSAndy Whitcroft  */
1542f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
15435ad333ebSAndy Whitcroft {
15445ad333ebSAndy Whitcroft 	int ret = -EINVAL;
15455ad333ebSAndy Whitcroft 
15465ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
15475ad333ebSAndy Whitcroft 	if (!PageLRU(page))
15485ad333ebSAndy Whitcroft 		return ret;
15495ad333ebSAndy Whitcroft 
1550e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1551e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1552894bc310SLee Schermerhorn 		return ret;
1553894bc310SLee Schermerhorn 
15545ad333ebSAndy Whitcroft 	ret = -EBUSY;
155508e552c6SKAMEZAWA Hiroyuki 
1556c8244935SMel Gorman 	/*
1557c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1558c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1559c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1560c8244935SMel Gorman 	 *
1561c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1562c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1563c8244935SMel Gorman 	 */
15641276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1565c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1566c8244935SMel Gorman 		if (PageWriteback(page))
156739deaf85SMinchan Kim 			return ret;
156839deaf85SMinchan Kim 
1569c8244935SMel Gorman 		if (PageDirty(page)) {
1570c8244935SMel Gorman 			struct address_space *mapping;
157169d763fcSMel Gorman 			bool migrate_dirty;
1572c8244935SMel Gorman 
1573c8244935SMel Gorman 			/*
1574c8244935SMel Gorman 			 * Only pages without mappings or that have a
1575c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
157669d763fcSMel Gorman 			 * without blocking. However, we can be racing with
157769d763fcSMel Gorman 			 * truncation so it's necessary to lock the page
157869d763fcSMel Gorman 			 * to stabilise the mapping as truncation holds
157969d763fcSMel Gorman 			 * the page lock until after the page is removed
158069d763fcSMel Gorman 			 * from the page cache.
1581c8244935SMel Gorman 			 */
158269d763fcSMel Gorman 			if (!trylock_page(page))
158369d763fcSMel Gorman 				return ret;
158469d763fcSMel Gorman 
1585c8244935SMel Gorman 			mapping = page_mapping(page);
1586145e1a71SHugh Dickins 			migrate_dirty = !mapping || mapping->a_ops->migratepage;
158769d763fcSMel Gorman 			unlock_page(page);
158869d763fcSMel Gorman 			if (!migrate_dirty)
1589c8244935SMel Gorman 				return ret;
1590c8244935SMel Gorman 		}
1591c8244935SMel Gorman 	}
1592c8244935SMel Gorman 
1593f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1594f80c0673SMinchan Kim 		return ret;
1595f80c0673SMinchan Kim 
15965ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
15975ad333ebSAndy Whitcroft 		/*
15985ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
15995ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
16005ad333ebSAndy Whitcroft 		 * page release code relies on it.
16015ad333ebSAndy Whitcroft 		 */
16025ad333ebSAndy Whitcroft 		ClearPageLRU(page);
16035ad333ebSAndy Whitcroft 		ret = 0;
16045ad333ebSAndy Whitcroft 	}
16055ad333ebSAndy Whitcroft 
16065ad333ebSAndy Whitcroft 	return ret;
16075ad333ebSAndy Whitcroft }
16085ad333ebSAndy Whitcroft 
16097ee36a14SMel Gorman 
16107ee36a14SMel Gorman /*
16117ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
161255b65a57SEthon Paul  * be complete before mem_cgroup_update_lru_size due to a sanity check.
16137ee36a14SMel Gorman  */
16147ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1615b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
16167ee36a14SMel Gorman {
16177ee36a14SMel Gorman 	int zid;
16187ee36a14SMel Gorman 
16197ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
16207ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
16217ee36a14SMel Gorman 			continue;
16227ee36a14SMel Gorman 
1623a892cb6bSWei Yang 		update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
16247ee36a14SMel Gorman 	}
16257ee36a14SMel Gorman 
16267ee36a14SMel Gorman }
16277ee36a14SMel Gorman 
1628f4b7e272SAndrey Ryabinin /**
1629f4b7e272SAndrey Ryabinin  * pgdat->lru_lock is heavily contended.  Some of the functions that
16301da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
16311da177e4SLinus Torvalds  * and working on them outside the LRU lock.
16321da177e4SLinus Torvalds  *
16331da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
16341da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
16351da177e4SLinus Torvalds  *
16361da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
16371da177e4SLinus Torvalds  *
1638791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
16395dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
16401da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1641f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1642fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
16433cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
16441da177e4SLinus Torvalds  *
16451da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
16461da177e4SLinus Torvalds  */
164769e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
16485dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1649fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
1650a9e7c39fSKirill Tkhai 		enum lru_list lru)
16511da177e4SLinus Torvalds {
165275b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
165369e05944SAndrew Morton 	unsigned long nr_taken = 0;
1654599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
16557cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
16563db65812SJohannes Weiner 	unsigned long skipped = 0;
1657791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
1658b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
1659a9e7c39fSKirill Tkhai 	isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
16601da177e4SLinus Torvalds 
166198879b3bSYang Shi 	total_scan = 0;
1662791b48b6SMinchan Kim 	scan = 0;
166398879b3bSYang Shi 	while (scan < nr_to_scan && !list_empty(src)) {
16645ad333ebSAndy Whitcroft 		struct page *page;
16655ad333ebSAndy Whitcroft 
16661da177e4SLinus Torvalds 		page = lru_to_page(src);
16671da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
16681da177e4SLinus Torvalds 
1669309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
16708d438f96SNick Piggin 
1671d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
167298879b3bSYang Shi 		total_scan += nr_pages;
167398879b3bSYang Shi 
1674b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1675b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
167698879b3bSYang Shi 			nr_skipped[page_zonenum(page)] += nr_pages;
1677b2e18757SMel Gorman 			continue;
1678b2e18757SMel Gorman 		}
1679b2e18757SMel Gorman 
1680791b48b6SMinchan Kim 		/*
1681791b48b6SMinchan Kim 		 * Do not count skipped pages because that makes the function
1682791b48b6SMinchan Kim 		 * return with no isolated pages if the LRU mostly contains
1683791b48b6SMinchan Kim 		 * ineligible pages.  This causes the VM to not reclaim any
1684791b48b6SMinchan Kim 		 * pages, triggering a premature OOM.
168598879b3bSYang Shi 		 *
168698879b3bSYang Shi 		 * Account all tail pages of THP.  This would not cause
168798879b3bSYang Shi 		 * premature OOM since __isolate_lru_page() returns -EBUSY
168898879b3bSYang Shi 		 * only when the page is being freed somewhere else.
1689791b48b6SMinchan Kim 		 */
169098879b3bSYang Shi 		scan += nr_pages;
1691f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
16925ad333ebSAndy Whitcroft 		case 0:
1693599d0c95SMel Gorman 			nr_taken += nr_pages;
1694599d0c95SMel Gorman 			nr_zone_taken[page_zonenum(page)] += nr_pages;
16955ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
16965ad333ebSAndy Whitcroft 			break;
16977c8ee9a8SNick Piggin 
16985ad333ebSAndy Whitcroft 		case -EBUSY:
16995ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
17005ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
17015ad333ebSAndy Whitcroft 			continue;
17025ad333ebSAndy Whitcroft 
17035ad333ebSAndy Whitcroft 		default:
17045ad333ebSAndy Whitcroft 			BUG();
17055ad333ebSAndy Whitcroft 		}
17065ad333ebSAndy Whitcroft 	}
17071da177e4SLinus Torvalds 
1708b2e18757SMel Gorman 	/*
1709b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1710b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1711b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1712b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1713b2e18757SMel Gorman 	 * system at risk of premature OOM.
1714b2e18757SMel Gorman 	 */
17157cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
17167cc30fcfSMel Gorman 		int zid;
17177cc30fcfSMel Gorman 
17183db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
17197cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
17207cc30fcfSMel Gorman 			if (!nr_skipped[zid])
17217cc30fcfSMel Gorman 				continue;
17227cc30fcfSMel Gorman 
17237cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
17241265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
17257cc30fcfSMel Gorman 		}
17267cc30fcfSMel Gorman 	}
1727791b48b6SMinchan Kim 	*nr_scanned = total_scan;
17281265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1729791b48b6SMinchan Kim 				    total_scan, skipped, nr_taken, mode, lru);
1730b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
17311da177e4SLinus Torvalds 	return nr_taken;
17321da177e4SLinus Torvalds }
17331da177e4SLinus Torvalds 
173462695a84SNick Piggin /**
173562695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
173662695a84SNick Piggin  * @page: page to isolate from its LRU list
173762695a84SNick Piggin  *
173862695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
173962695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
174062695a84SNick Piggin  *
174162695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
174262695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
174362695a84SNick Piggin  *
174462695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1745894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1746894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1747894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
174862695a84SNick Piggin  *
174962695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
175062695a84SNick Piggin  * found will be decremented.
175162695a84SNick Piggin  *
175262695a84SNick Piggin  * Restrictions:
1753a5d09bedSMike Rapoport  *
175462695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
175501c4776bSHui Su  *     fundamental difference from isolate_lru_pages (which is called
175662695a84SNick Piggin  *     without a stable reference).
175762695a84SNick Piggin  * (2) the lru_lock must not be held.
175862695a84SNick Piggin  * (3) interrupts must be enabled.
175962695a84SNick Piggin  */
176062695a84SNick Piggin int isolate_lru_page(struct page *page)
176162695a84SNick Piggin {
176262695a84SNick Piggin 	int ret = -EBUSY;
176362695a84SNick Piggin 
1764309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1765cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
17660c917313SKonstantin Khlebnikov 
176762695a84SNick Piggin 	if (PageLRU(page)) {
1768f4b7e272SAndrey Ryabinin 		pg_data_t *pgdat = page_pgdat(page);
1769fa9add64SHugh Dickins 		struct lruvec *lruvec;
177062695a84SNick Piggin 
1771f4b7e272SAndrey Ryabinin 		spin_lock_irq(&pgdat->lru_lock);
1772f4b7e272SAndrey Ryabinin 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
17730c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1774894bc310SLee Schermerhorn 			int lru = page_lru(page);
17750c917313SKonstantin Khlebnikov 			get_page(page);
177662695a84SNick Piggin 			ClearPageLRU(page);
1777fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1778fa9add64SHugh Dickins 			ret = 0;
177962695a84SNick Piggin 		}
1780f4b7e272SAndrey Ryabinin 		spin_unlock_irq(&pgdat->lru_lock);
178162695a84SNick Piggin 	}
178262695a84SNick Piggin 	return ret;
178362695a84SNick Piggin }
178462695a84SNick Piggin 
17855ad333ebSAndy Whitcroft /*
1786d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1787178821b8SXianting Tian  * then get rescheduled. When there are massive number of tasks doing page
1788d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1789d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1790d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
179135cd7815SRik van Riel  */
1792599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
179335cd7815SRik van Riel 		struct scan_control *sc)
179435cd7815SRik van Riel {
179535cd7815SRik van Riel 	unsigned long inactive, isolated;
179635cd7815SRik van Riel 
179735cd7815SRik van Riel 	if (current_is_kswapd())
179835cd7815SRik van Riel 		return 0;
179935cd7815SRik van Riel 
1800b5ead35eSJohannes Weiner 	if (!writeback_throttling_sane(sc))
180135cd7815SRik van Riel 		return 0;
180235cd7815SRik van Riel 
180335cd7815SRik van Riel 	if (file) {
1804599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1805599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
180635cd7815SRik van Riel 	} else {
1807599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1808599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
180935cd7815SRik van Riel 	}
181035cd7815SRik van Riel 
18113cf23841SFengguang Wu 	/*
18123cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
18133cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
18143cf23841SFengguang Wu 	 * deadlock.
18153cf23841SFengguang Wu 	 */
1816d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
18173cf23841SFengguang Wu 		inactive >>= 3;
18183cf23841SFengguang Wu 
181935cd7815SRik van Riel 	return isolated > inactive;
182035cd7815SRik van Riel }
182135cd7815SRik van Riel 
1822a222f341SKirill Tkhai /*
1823a222f341SKirill Tkhai  * This moves pages from @list to corresponding LRU list.
1824a222f341SKirill Tkhai  *
1825a222f341SKirill Tkhai  * We move them the other way if the page is referenced by one or more
1826a222f341SKirill Tkhai  * processes, from rmap.
1827a222f341SKirill Tkhai  *
1828a222f341SKirill Tkhai  * If the pages are mostly unmapped, the processing is fast and it is
1829a222f341SKirill Tkhai  * appropriate to hold zone_lru_lock across the whole operation.  But if
1830a222f341SKirill Tkhai  * the pages are mapped, the processing is slow (page_referenced()) so we
1831a222f341SKirill Tkhai  * should drop zone_lru_lock around each page.  It's impossible to balance
1832a222f341SKirill Tkhai  * this, so instead we remove the pages from the LRU while processing them.
1833a222f341SKirill Tkhai  * It is safe to rely on PG_active against the non-LRU pages in here because
1834a222f341SKirill Tkhai  * nobody will play with that bit on a non-LRU page.
1835a222f341SKirill Tkhai  *
1836a222f341SKirill Tkhai  * The downside is that we have to touch page->_refcount against each page.
1837a222f341SKirill Tkhai  * But we had to alter page->flags anyway.
1838a222f341SKirill Tkhai  *
1839a222f341SKirill Tkhai  * Returns the number of pages moved to the given lruvec.
1840a222f341SKirill Tkhai  */
1841a222f341SKirill Tkhai 
1842a222f341SKirill Tkhai static unsigned noinline_for_stack move_pages_to_lru(struct lruvec *lruvec,
1843a222f341SKirill Tkhai 						     struct list_head *list)
184466635629SMel Gorman {
1845599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
1846a222f341SKirill Tkhai 	int nr_pages, nr_moved = 0;
18473f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
1848a222f341SKirill Tkhai 	struct page *page;
1849a222f341SKirill Tkhai 	enum lru_list lru;
185066635629SMel Gorman 
1851a222f341SKirill Tkhai 	while (!list_empty(list)) {
1852a222f341SKirill Tkhai 		page = lru_to_page(list);
1853309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
1854a222f341SKirill Tkhai 		list_del(&page->lru);
18553d06afabSAlex Shi 		if (unlikely(!page_evictable(page))) {
1856599d0c95SMel Gorman 			spin_unlock_irq(&pgdat->lru_lock);
185766635629SMel Gorman 			putback_lru_page(page);
1858599d0c95SMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
185966635629SMel Gorman 			continue;
186066635629SMel Gorman 		}
1861fa9add64SHugh Dickins 
18623d06afabSAlex Shi 		/*
18633d06afabSAlex Shi 		 * The SetPageLRU needs to be kept here for list integrity.
18643d06afabSAlex Shi 		 * Otherwise:
18653d06afabSAlex Shi 		 *   #0 move_pages_to_lru             #1 release_pages
18663d06afabSAlex Shi 		 *   if !put_page_testzero
18673d06afabSAlex Shi 		 *				      if (put_page_testzero())
18683d06afabSAlex Shi 		 *				        !PageLRU //skip lru_lock
18693d06afabSAlex Shi 		 *     SetPageLRU()
18703d06afabSAlex Shi 		 *     list_add(&page->lru,)
18713d06afabSAlex Shi 		 *                                        list_add(&page->lru,)
18723d06afabSAlex Shi 		 */
18737a608572SLinus Torvalds 		SetPageLRU(page);
1874a222f341SKirill Tkhai 
18753d06afabSAlex Shi 		if (unlikely(put_page_testzero(page))) {
18762bcf8879SHugh Dickins 			__ClearPageLRU(page);
18772bcf8879SHugh Dickins 			__ClearPageActive(page);
18782bcf8879SHugh Dickins 
18792bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1880599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1881ff45fc3cSMatthew Wilcox (Oracle) 				destroy_compound_page(page);
1882599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
18832bcf8879SHugh Dickins 			} else
18842bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
18853d06afabSAlex Shi 
18863d06afabSAlex Shi 			continue;
18873d06afabSAlex Shi 		}
18883d06afabSAlex Shi 
1889*afca9157SAlex Shi 		/*
1890*afca9157SAlex Shi 		 * All pages were isolated from the same lruvec (and isolation
1891*afca9157SAlex Shi 		 * inhibits memcg migration).
1892*afca9157SAlex Shi 		 */
1893*afca9157SAlex Shi 		VM_BUG_ON_PAGE(mem_cgroup_page_lruvec(page, page_pgdat(page))
1894*afca9157SAlex Shi 							!= lruvec, page);
18953d06afabSAlex Shi 		lru = page_lru(page);
18963d06afabSAlex Shi 		nr_pages = thp_nr_pages(page);
18973d06afabSAlex Shi 
18983d06afabSAlex Shi 		update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
18993d06afabSAlex Shi 		list_add(&page->lru, &lruvec->lists[lru]);
1900a222f341SKirill Tkhai 		nr_moved += nr_pages;
190131d8fcacSJohannes Weiner 		if (PageActive(page))
190231d8fcacSJohannes Weiner 			workingset_age_nonresident(lruvec, nr_pages);
190366635629SMel Gorman 	}
190466635629SMel Gorman 
19053f79768fSHugh Dickins 	/*
19063f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
19073f79768fSHugh Dickins 	 */
1908a222f341SKirill Tkhai 	list_splice(&pages_to_free, list);
1909a222f341SKirill Tkhai 
1910a222f341SKirill Tkhai 	return nr_moved;
191166635629SMel Gorman }
191266635629SMel Gorman 
191366635629SMel Gorman /*
1914399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1915a37b0715SNeilBrown  * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
1916399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1917399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1918399ba0b9SNeilBrown  */
1919399ba0b9SNeilBrown static int current_may_throttle(void)
1920399ba0b9SNeilBrown {
1921a37b0715SNeilBrown 	return !(current->flags & PF_LOCAL_THROTTLE) ||
1922399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1923399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1924399ba0b9SNeilBrown }
1925399ba0b9SNeilBrown 
1926399ba0b9SNeilBrown /*
1927b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
19281742f19fSAndrew Morton  * of reclaimed pages
19291da177e4SLinus Torvalds  */
193066635629SMel Gorman static noinline_for_stack unsigned long
19311a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
19329e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
19331da177e4SLinus Torvalds {
19341da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1935e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
1936730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
1937e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
1938060f005fSKirill Tkhai 	struct reclaim_stat stat;
1939497a6c1bSJohannes Weiner 	bool file = is_file_lru(lru);
1940f46b7912SKirill Tkhai 	enum vm_event_item item;
1941599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
1942db73ee0dSMichal Hocko 	bool stalled = false;
194378dc583dSKOSAKI Motohiro 
1944599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
1945db73ee0dSMichal Hocko 		if (stalled)
1946db73ee0dSMichal Hocko 			return 0;
1947db73ee0dSMichal Hocko 
1948db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
1949db73ee0dSMichal Hocko 		msleep(100);
1950db73ee0dSMichal Hocko 		stalled = true;
195135cd7815SRik van Riel 
195235cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
195335cd7815SRik van Riel 		if (fatal_signal_pending(current))
195435cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
195535cd7815SRik van Riel 	}
195635cd7815SRik van Riel 
19571da177e4SLinus Torvalds 	lru_add_drain();
1958f80c0673SMinchan Kim 
1959599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19601da177e4SLinus Torvalds 
19615dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
1962a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
196395d918fcSKonstantin Khlebnikov 
1964599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
1965f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
1966b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
1967f46b7912SKirill Tkhai 		__count_vm_events(item, nr_scanned);
1968f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
1969497a6c1bSJohannes Weiner 	__count_vm_events(PGSCAN_ANON + file, nr_scanned);
1970497a6c1bSJohannes Weiner 
1971599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
1972d563c050SHillf Danton 
1973d563c050SHillf Danton 	if (nr_taken == 0)
197466635629SMel Gorman 		return 0;
1975b35ea17bSKOSAKI Motohiro 
1976013339dfSShakeel Butt 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
1977c661b078SAndy Whitcroft 
1978599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
1979497a6c1bSJohannes Weiner 	move_pages_to_lru(lruvec, &page_list);
1980497a6c1bSJohannes Weiner 
1981497a6c1bSJohannes Weiner 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
1982f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
1983b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
1984f46b7912SKirill Tkhai 		__count_vm_events(item, nr_reclaimed);
1985f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
1986497a6c1bSJohannes Weiner 	__count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
1987599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19883f79768fSHugh Dickins 
198975cc3c91SAlex Shi 	lru_note_cost(lruvec, file, stat.nr_pageout);
1990747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
19912d4894b5SMel Gorman 	free_unref_page_list(&page_list);
1992e11da5b4SMel Gorman 
199392df3a72SMel Gorman 	/*
19941c610d5fSAndrey Ryabinin 	 * If dirty pages are scanned that are not queued for IO, it
19951c610d5fSAndrey Ryabinin 	 * implies that flushers are not doing their job. This can
19961c610d5fSAndrey Ryabinin 	 * happen when memory pressure pushes dirty pages to the end of
19971c610d5fSAndrey Ryabinin 	 * the LRU before the dirty limits are breached and the dirty
19981c610d5fSAndrey Ryabinin 	 * data has expired. It can also happen when the proportion of
19991c610d5fSAndrey Ryabinin 	 * dirty pages grows not through writes but through memory
20001c610d5fSAndrey Ryabinin 	 * pressure reclaiming all the clean cache. And in some cases,
20011c610d5fSAndrey Ryabinin 	 * the flushers simply cannot keep up with the allocation
20021c610d5fSAndrey Ryabinin 	 * rate. Nudge the flusher threads in case they are asleep.
20031c610d5fSAndrey Ryabinin 	 */
20041c610d5fSAndrey Ryabinin 	if (stat.nr_unqueued_dirty == nr_taken)
20051c610d5fSAndrey Ryabinin 		wakeup_flusher_threads(WB_REASON_VMSCAN);
20061c610d5fSAndrey Ryabinin 
2007d108c772SAndrey Ryabinin 	sc->nr.dirty += stat.nr_dirty;
2008d108c772SAndrey Ryabinin 	sc->nr.congested += stat.nr_congested;
2009d108c772SAndrey Ryabinin 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2010d108c772SAndrey Ryabinin 	sc->nr.writeback += stat.nr_writeback;
2011d108c772SAndrey Ryabinin 	sc->nr.immediate += stat.nr_immediate;
2012d108c772SAndrey Ryabinin 	sc->nr.taken += nr_taken;
2013d108c772SAndrey Ryabinin 	if (file)
2014d108c772SAndrey Ryabinin 		sc->nr.file_taken += nr_taken;
20158e950282SMel Gorman 
2016599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2017d51d1e64SSteven Rostedt 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
201805ff5137SAndrew Morton 	return nr_reclaimed;
20191da177e4SLinus Torvalds }
20201da177e4SLinus Torvalds 
2021f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
20221a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
2023f16015fbSJohannes Weiner 			       struct scan_control *sc,
20249e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
20251cfb419bSKAMEZAWA Hiroyuki {
202644c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
2027f626012dSHugh Dickins 	unsigned long nr_scanned;
20286fe6b7e3SWu Fengguang 	unsigned long vm_flags;
20291cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
20308cab4754SWu Fengguang 	LIST_HEAD(l_active);
2031b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
20321cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
20339d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
20349d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
20353cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
2036599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
20371cfb419bSKAMEZAWA Hiroyuki 
20381da177e4SLinus Torvalds 	lru_add_drain();
2039f80c0673SMinchan Kim 
2040599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
2041925b7673SJohannes Weiner 
20425dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2043a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
204489b5fae5SJohannes Weiner 
2045599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
20461cfb419bSKAMEZAWA Hiroyuki 
2047912c0572SShakeel Butt 	if (!cgroup_reclaim(sc))
2048599d0c95SMel Gorman 		__count_vm_events(PGREFILL, nr_scanned);
20492fa2690cSYafang Shao 	__count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
20509d5e6a9fSHugh Dickins 
2051599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
20521da177e4SLinus Torvalds 
20531da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
20541da177e4SLinus Torvalds 		cond_resched();
20551da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
20561da177e4SLinus Torvalds 		list_del(&page->lru);
20577e9cd484SRik van Riel 
205839b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
2059894bc310SLee Schermerhorn 			putback_lru_page(page);
2060894bc310SLee Schermerhorn 			continue;
2061894bc310SLee Schermerhorn 		}
2062894bc310SLee Schermerhorn 
2063cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
2064cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
2065cc715d99SMel Gorman 				if (page_has_private(page))
2066cc715d99SMel Gorman 					try_to_release_page(page, 0);
2067cc715d99SMel Gorman 				unlock_page(page);
2068cc715d99SMel Gorman 			}
2069cc715d99SMel Gorman 		}
2070cc715d99SMel Gorman 
2071c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
2072c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
20738cab4754SWu Fengguang 			/*
20748cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
20758cab4754SWu Fengguang 			 * give them one more trip around the active list. So
20768cab4754SWu Fengguang 			 * that executable code get better chances to stay in
20778cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
20788cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
20798cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
20808cab4754SWu Fengguang 			 * so we ignore them here.
20818cab4754SWu Fengguang 			 */
20829de4f22aSHuang Ying 			if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
20836c357848SMatthew Wilcox (Oracle) 				nr_rotated += thp_nr_pages(page);
20848cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
20858cab4754SWu Fengguang 				continue;
20868cab4754SWu Fengguang 			}
20878cab4754SWu Fengguang 		}
20887e9cd484SRik van Riel 
20895205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
20901899ad18SJohannes Weiner 		SetPageWorkingset(page);
20911da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
20921da177e4SLinus Torvalds 	}
20931da177e4SLinus Torvalds 
2094b555749aSAndrew Morton 	/*
20958cab4754SWu Fengguang 	 * Move pages back to the lru list.
2096b555749aSAndrew Morton 	 */
2097599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
2098556adecbSRik van Riel 
2099a222f341SKirill Tkhai 	nr_activate = move_pages_to_lru(lruvec, &l_active);
2100a222f341SKirill Tkhai 	nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2101f372d89eSKirill Tkhai 	/* Keep all free pages in l_active list */
2102f372d89eSKirill Tkhai 	list_splice(&l_inactive, &l_active);
21039851ac13SKirill Tkhai 
21049851ac13SKirill Tkhai 	__count_vm_events(PGDEACTIVATE, nr_deactivate);
21059851ac13SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
21069851ac13SKirill Tkhai 
2107599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2108599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
21092bcf8879SHugh Dickins 
2110f372d89eSKirill Tkhai 	mem_cgroup_uncharge_list(&l_active);
2111f372d89eSKirill Tkhai 	free_unref_page_list(&l_active);
21129d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
21139d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
21141da177e4SLinus Torvalds }
21151da177e4SLinus Torvalds 
21161a4e58ccSMinchan Kim unsigned long reclaim_pages(struct list_head *page_list)
21171a4e58ccSMinchan Kim {
2118f661d007SYang Shi 	int nid = NUMA_NO_NODE;
2119730ec8c0SManinder Singh 	unsigned int nr_reclaimed = 0;
21201a4e58ccSMinchan Kim 	LIST_HEAD(node_page_list);
21211a4e58ccSMinchan Kim 	struct reclaim_stat dummy_stat;
21221a4e58ccSMinchan Kim 	struct page *page;
21231a4e58ccSMinchan Kim 	struct scan_control sc = {
21241a4e58ccSMinchan Kim 		.gfp_mask = GFP_KERNEL,
21251a4e58ccSMinchan Kim 		.priority = DEF_PRIORITY,
21261a4e58ccSMinchan Kim 		.may_writepage = 1,
21271a4e58ccSMinchan Kim 		.may_unmap = 1,
21281a4e58ccSMinchan Kim 		.may_swap = 1,
21291a4e58ccSMinchan Kim 	};
21301a4e58ccSMinchan Kim 
21311a4e58ccSMinchan Kim 	while (!list_empty(page_list)) {
21321a4e58ccSMinchan Kim 		page = lru_to_page(page_list);
2133f661d007SYang Shi 		if (nid == NUMA_NO_NODE) {
21341a4e58ccSMinchan Kim 			nid = page_to_nid(page);
21351a4e58ccSMinchan Kim 			INIT_LIST_HEAD(&node_page_list);
21361a4e58ccSMinchan Kim 		}
21371a4e58ccSMinchan Kim 
21381a4e58ccSMinchan Kim 		if (nid == page_to_nid(page)) {
21391a4e58ccSMinchan Kim 			ClearPageActive(page);
21401a4e58ccSMinchan Kim 			list_move(&page->lru, &node_page_list);
21411a4e58ccSMinchan Kim 			continue;
21421a4e58ccSMinchan Kim 		}
21431a4e58ccSMinchan Kim 
21441a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
21451a4e58ccSMinchan Kim 						NODE_DATA(nid),
2146013339dfSShakeel Butt 						&sc, &dummy_stat, false);
21471a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
21481a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
21491a4e58ccSMinchan Kim 			list_del(&page->lru);
21501a4e58ccSMinchan Kim 			putback_lru_page(page);
21511a4e58ccSMinchan Kim 		}
21521a4e58ccSMinchan Kim 
2153f661d007SYang Shi 		nid = NUMA_NO_NODE;
21541a4e58ccSMinchan Kim 	}
21551a4e58ccSMinchan Kim 
21561a4e58ccSMinchan Kim 	if (!list_empty(&node_page_list)) {
21571a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
21581a4e58ccSMinchan Kim 						NODE_DATA(nid),
2159013339dfSShakeel Butt 						&sc, &dummy_stat, false);
21601a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
21611a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
21621a4e58ccSMinchan Kim 			list_del(&page->lru);
21631a4e58ccSMinchan Kim 			putback_lru_page(page);
21641a4e58ccSMinchan Kim 		}
21651a4e58ccSMinchan Kim 	}
21661a4e58ccSMinchan Kim 
21671a4e58ccSMinchan Kim 	return nr_reclaimed;
21681a4e58ccSMinchan Kim }
21691a4e58ccSMinchan Kim 
2170b91ac374SJohannes Weiner static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2171b91ac374SJohannes Weiner 				 struct lruvec *lruvec, struct scan_control *sc)
2172b91ac374SJohannes Weiner {
2173b91ac374SJohannes Weiner 	if (is_active_lru(lru)) {
2174b91ac374SJohannes Weiner 		if (sc->may_deactivate & (1 << is_file_lru(lru)))
2175b91ac374SJohannes Weiner 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2176b91ac374SJohannes Weiner 		else
2177b91ac374SJohannes Weiner 			sc->skipped_deactivate = 1;
2178b91ac374SJohannes Weiner 		return 0;
2179b91ac374SJohannes Weiner 	}
2180b91ac374SJohannes Weiner 
2181b91ac374SJohannes Weiner 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2182b91ac374SJohannes Weiner }
2183b91ac374SJohannes Weiner 
218459dc76b0SRik van Riel /*
218559dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
218659dc76b0SRik van Riel  * to do too much work.
218714797e23SKOSAKI Motohiro  *
218859dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
218959dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
219059dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
219159dc76b0SRik van Riel  *
219259dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
219359dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
219459dc76b0SRik van Riel  *
21952a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
21962a2e4885SJohannes Weiner  *
219759dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
21983a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
219959dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
220059dc76b0SRik van Riel  *
220159dc76b0SRik van Riel  * total     target    max
220259dc76b0SRik van Riel  * memory    ratio     inactive
220359dc76b0SRik van Riel  * -------------------------------------
220459dc76b0SRik van Riel  *   10MB       1         5MB
220559dc76b0SRik van Riel  *  100MB       1        50MB
220659dc76b0SRik van Riel  *    1GB       3       250MB
220759dc76b0SRik van Riel  *   10GB      10       0.9GB
220859dc76b0SRik van Riel  *  100GB      31         3GB
220959dc76b0SRik van Riel  *    1TB     101        10GB
221059dc76b0SRik van Riel  *   10TB     320        32GB
221114797e23SKOSAKI Motohiro  */
2212b91ac374SJohannes Weiner static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
221314797e23SKOSAKI Motohiro {
2214b91ac374SJohannes Weiner 	enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
22152a2e4885SJohannes Weiner 	unsigned long inactive, active;
22162a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
221759dc76b0SRik van Riel 	unsigned long gb;
221859dc76b0SRik van Riel 
2219b91ac374SJohannes Weiner 	inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2220b91ac374SJohannes Weiner 	active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2221f8d1a311SMel Gorman 
222259dc76b0SRik van Riel 	gb = (inactive + active) >> (30 - PAGE_SHIFT);
22234002570cSJoonsoo Kim 	if (gb)
222459dc76b0SRik van Riel 		inactive_ratio = int_sqrt(10 * gb);
2225b39415b2SRik van Riel 	else
222659dc76b0SRik van Riel 		inactive_ratio = 1;
2227fd538803SMichal Hocko 
222859dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2229b39415b2SRik van Riel }
2230b39415b2SRik van Riel 
22319a265114SJohannes Weiner enum scan_balance {
22329a265114SJohannes Weiner 	SCAN_EQUAL,
22339a265114SJohannes Weiner 	SCAN_FRACT,
22349a265114SJohannes Weiner 	SCAN_ANON,
22359a265114SJohannes Weiner 	SCAN_FILE,
22369a265114SJohannes Weiner };
22379a265114SJohannes Weiner 
22381da177e4SLinus Torvalds /*
22394f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
22404f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
22414f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
22424f98a2feSRik van Riel  * onto the active list instead of evict.
22434f98a2feSRik van Riel  *
2244be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2245be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
22464f98a2feSRik van Riel  */
2247afaf07a6SJohannes Weiner static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2248afaf07a6SJohannes Weiner 			   unsigned long *nr)
22494f98a2feSRik van Riel {
2250afaf07a6SJohannes Weiner 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2251d483a5ddSJohannes Weiner 	unsigned long anon_cost, file_cost, total_cost;
225233377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
2253ed017373SYu Zhao 	u64 fraction[ANON_AND_FILE];
22549a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
22559a265114SJohannes Weiner 	enum scan_balance scan_balance;
22569a265114SJohannes Weiner 	unsigned long ap, fp;
22579a265114SJohannes Weiner 	enum lru_list lru;
225876a33fc3SShaohua Li 
225976a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2260d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
22619a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
226276a33fc3SShaohua Li 		goto out;
226376a33fc3SShaohua Li 	}
22644f98a2feSRik van Riel 
226510316b31SJohannes Weiner 	/*
226610316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
226710316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
226810316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
226910316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
227010316b31SJohannes Weiner 	 * too expensive.
227110316b31SJohannes Weiner 	 */
2272b5ead35eSJohannes Weiner 	if (cgroup_reclaim(sc) && !swappiness) {
22739a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
227410316b31SJohannes Weiner 		goto out;
227510316b31SJohannes Weiner 	}
227610316b31SJohannes Weiner 
227710316b31SJohannes Weiner 	/*
227810316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
227910316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
228010316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
228110316b31SJohannes Weiner 	 */
228202695175SJohannes Weiner 	if (!sc->priority && swappiness) {
22839a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
228410316b31SJohannes Weiner 		goto out;
228510316b31SJohannes Weiner 	}
228610316b31SJohannes Weiner 
228711d16c25SJohannes Weiner 	/*
228853138ceaSJohannes Weiner 	 * If the system is almost out of file pages, force-scan anon.
228962376251SJohannes Weiner 	 */
2290b91ac374SJohannes Weiner 	if (sc->file_is_tiny) {
229162376251SJohannes Weiner 		scan_balance = SCAN_ANON;
229262376251SJohannes Weiner 		goto out;
229362376251SJohannes Weiner 	}
229462376251SJohannes Weiner 
229562376251SJohannes Weiner 	/*
2296b91ac374SJohannes Weiner 	 * If there is enough inactive page cache, we do not reclaim
2297b91ac374SJohannes Weiner 	 * anything from the anonymous working right now.
2298e9868505SRik van Riel 	 */
2299b91ac374SJohannes Weiner 	if (sc->cache_trim_mode) {
23009a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2301e9868505SRik van Riel 		goto out;
23024f98a2feSRik van Riel 	}
23034f98a2feSRik van Riel 
23049a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
23054f98a2feSRik van Riel 	/*
2306314b57fbSJohannes Weiner 	 * Calculate the pressure balance between anon and file pages.
2307314b57fbSJohannes Weiner 	 *
2308314b57fbSJohannes Weiner 	 * The amount of pressure we put on each LRU is inversely
2309314b57fbSJohannes Weiner 	 * proportional to the cost of reclaiming each list, as
2310314b57fbSJohannes Weiner 	 * determined by the share of pages that are refaulting, times
2311314b57fbSJohannes Weiner 	 * the relative IO cost of bringing back a swapped out
2312314b57fbSJohannes Weiner 	 * anonymous page vs reloading a filesystem page (swappiness).
2313314b57fbSJohannes Weiner 	 *
2314d483a5ddSJohannes Weiner 	 * Although we limit that influence to ensure no list gets
2315d483a5ddSJohannes Weiner 	 * left behind completely: at least a third of the pressure is
2316d483a5ddSJohannes Weiner 	 * applied, before swappiness.
2317d483a5ddSJohannes Weiner 	 *
2318314b57fbSJohannes Weiner 	 * With swappiness at 100, anon and file have equal IO cost.
231958c37f6eSKOSAKI Motohiro 	 */
2320d483a5ddSJohannes Weiner 	total_cost = sc->anon_cost + sc->file_cost;
2321d483a5ddSJohannes Weiner 	anon_cost = total_cost + sc->anon_cost;
2322d483a5ddSJohannes Weiner 	file_cost = total_cost + sc->file_cost;
2323d483a5ddSJohannes Weiner 	total_cost = anon_cost + file_cost;
232458c37f6eSKOSAKI Motohiro 
2325d483a5ddSJohannes Weiner 	ap = swappiness * (total_cost + 1);
2326d483a5ddSJohannes Weiner 	ap /= anon_cost + 1;
23274f98a2feSRik van Riel 
2328d483a5ddSJohannes Weiner 	fp = (200 - swappiness) * (total_cost + 1);
2329d483a5ddSJohannes Weiner 	fp /= file_cost + 1;
23304f98a2feSRik van Riel 
233176a33fc3SShaohua Li 	fraction[0] = ap;
233276a33fc3SShaohua Li 	fraction[1] = fp;
2333a4fe1631SJohannes Weiner 	denominator = ap + fp;
233476a33fc3SShaohua Li out:
23354111304dSHugh Dickins 	for_each_evictable_lru(lru) {
23364111304dSHugh Dickins 		int file = is_file_lru(lru);
23379783aa99SChris Down 		unsigned long lruvec_size;
233876a33fc3SShaohua Li 		unsigned long scan;
23391bc63fb1SChris Down 		unsigned long protection;
234076a33fc3SShaohua Li 
23419783aa99SChris Down 		lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
234222f7496fSYafang Shao 		protection = mem_cgroup_protection(sc->target_mem_cgroup,
234322f7496fSYafang Shao 						   memcg,
23441bc63fb1SChris Down 						   sc->memcg_low_reclaim);
23459783aa99SChris Down 
23461bc63fb1SChris Down 		if (protection) {
23479783aa99SChris Down 			/*
23489783aa99SChris Down 			 * Scale a cgroup's reclaim pressure by proportioning
23499783aa99SChris Down 			 * its current usage to its memory.low or memory.min
23509783aa99SChris Down 			 * setting.
23519783aa99SChris Down 			 *
23529783aa99SChris Down 			 * This is important, as otherwise scanning aggression
23539783aa99SChris Down 			 * becomes extremely binary -- from nothing as we
23549783aa99SChris Down 			 * approach the memory protection threshold, to totally
23559783aa99SChris Down 			 * nominal as we exceed it.  This results in requiring
23569783aa99SChris Down 			 * setting extremely liberal protection thresholds. It
23579783aa99SChris Down 			 * also means we simply get no protection at all if we
23589783aa99SChris Down 			 * set it too low, which is not ideal.
23591bc63fb1SChris Down 			 *
23601bc63fb1SChris Down 			 * If there is any protection in place, we reduce scan
23611bc63fb1SChris Down 			 * pressure by how much of the total memory used is
23621bc63fb1SChris Down 			 * within protection thresholds.
23639783aa99SChris Down 			 *
23649de7ca46SChris Down 			 * There is one special case: in the first reclaim pass,
23659de7ca46SChris Down 			 * we skip over all groups that are within their low
23669de7ca46SChris Down 			 * protection. If that fails to reclaim enough pages to
23679de7ca46SChris Down 			 * satisfy the reclaim goal, we come back and override
23689de7ca46SChris Down 			 * the best-effort low protection. However, we still
23699de7ca46SChris Down 			 * ideally want to honor how well-behaved groups are in
23709de7ca46SChris Down 			 * that case instead of simply punishing them all
23719de7ca46SChris Down 			 * equally. As such, we reclaim them based on how much
23721bc63fb1SChris Down 			 * memory they are using, reducing the scan pressure
23731bc63fb1SChris Down 			 * again by how much of the total memory used is under
23741bc63fb1SChris Down 			 * hard protection.
23759783aa99SChris Down 			 */
23761bc63fb1SChris Down 			unsigned long cgroup_size = mem_cgroup_size(memcg);
23771bc63fb1SChris Down 
23781bc63fb1SChris Down 			/* Avoid TOCTOU with earlier protection check */
23791bc63fb1SChris Down 			cgroup_size = max(cgroup_size, protection);
23801bc63fb1SChris Down 
23811bc63fb1SChris Down 			scan = lruvec_size - lruvec_size * protection /
23821bc63fb1SChris Down 				cgroup_size;
23839783aa99SChris Down 
23849783aa99SChris Down 			/*
23851bc63fb1SChris Down 			 * Minimally target SWAP_CLUSTER_MAX pages to keep
238655b65a57SEthon Paul 			 * reclaim moving forwards, avoiding decrementing
23879de7ca46SChris Down 			 * sc->priority further than desirable.
23889783aa99SChris Down 			 */
23891bc63fb1SChris Down 			scan = max(scan, SWAP_CLUSTER_MAX);
23909783aa99SChris Down 		} else {
23919783aa99SChris Down 			scan = lruvec_size;
23929783aa99SChris Down 		}
23939783aa99SChris Down 
23949783aa99SChris Down 		scan >>= sc->priority;
23959783aa99SChris Down 
2396688035f7SJohannes Weiner 		/*
2397688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2398688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2399688035f7SJohannes Weiner 		 */
2400688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
24019783aa99SChris Down 			scan = min(lruvec_size, SWAP_CLUSTER_MAX);
24029a265114SJohannes Weiner 
24039a265114SJohannes Weiner 		switch (scan_balance) {
24049a265114SJohannes Weiner 		case SCAN_EQUAL:
24059a265114SJohannes Weiner 			/* Scan lists relative to size */
24069a265114SJohannes Weiner 			break;
24079a265114SJohannes Weiner 		case SCAN_FRACT:
24089a265114SJohannes Weiner 			/*
24099a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
24109a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
241176073c64SGavin Shan 			 * Make sure we don't miss the last page on
241276073c64SGavin Shan 			 * the offlined memory cgroups because of a
241376073c64SGavin Shan 			 * round-off error.
24149a265114SJohannes Weiner 			 */
241576073c64SGavin Shan 			scan = mem_cgroup_online(memcg) ?
241676073c64SGavin Shan 			       div64_u64(scan * fraction[file], denominator) :
241776073c64SGavin Shan 			       DIV64_U64_ROUND_UP(scan * fraction[file],
24186f04f48dSSuleiman Souhlal 						  denominator);
24199a265114SJohannes Weiner 			break;
24209a265114SJohannes Weiner 		case SCAN_FILE:
24219a265114SJohannes Weiner 		case SCAN_ANON:
24229a265114SJohannes Weiner 			/* Scan one type exclusively */
2423e072bff6SMateusz Nosek 			if ((scan_balance == SCAN_FILE) != file)
24249a265114SJohannes Weiner 				scan = 0;
24259a265114SJohannes Weiner 			break;
24269a265114SJohannes Weiner 		default:
24279a265114SJohannes Weiner 			/* Look ma, no brain */
24289a265114SJohannes Weiner 			BUG();
24299a265114SJohannes Weiner 		}
24306b4f7799SJohannes Weiner 
24314111304dSHugh Dickins 		nr[lru] = scan;
243276a33fc3SShaohua Li 	}
24336e08a369SWu Fengguang }
24344f98a2feSRik van Riel 
2435afaf07a6SJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
24369b4f98cdSJohannes Weiner {
24379b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2438e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
24399b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
24409b4f98cdSJohannes Weiner 	enum lru_list lru;
24419b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
24429b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
24439b4f98cdSJohannes Weiner 	struct blk_plug plug;
24441a501907SMel Gorman 	bool scan_adjusted;
24459b4f98cdSJohannes Weiner 
2446afaf07a6SJohannes Weiner 	get_scan_count(lruvec, sc, nr);
24479b4f98cdSJohannes Weiner 
2448e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2449e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2450e82e0561SMel Gorman 
24511a501907SMel Gorman 	/*
24521a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
24531a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
24541a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
24551a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
24561a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
24571a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
24581a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
24591a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
24601a501907SMel Gorman 	 * dropped to zero at the first pass.
24611a501907SMel Gorman 	 */
2462b5ead35eSJohannes Weiner 	scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
24631a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
24641a501907SMel Gorman 
24659b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
24669b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
24679b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2468e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2469e82e0561SMel Gorman 		unsigned long nr_scanned;
2470e82e0561SMel Gorman 
24719b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
24729b4f98cdSJohannes Weiner 			if (nr[lru]) {
24739b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
24749b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
24759b4f98cdSJohannes Weiner 
24769b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
24773b991208SJohannes Weiner 							    lruvec, sc);
24789b4f98cdSJohannes Weiner 			}
24799b4f98cdSJohannes Weiner 		}
2480e82e0561SMel Gorman 
2481bd041733SMichal Hocko 		cond_resched();
2482bd041733SMichal Hocko 
2483e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2484e82e0561SMel Gorman 			continue;
2485e82e0561SMel Gorman 
24869b4f98cdSJohannes Weiner 		/*
2487e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
24881a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2489e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2490e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2491e82e0561SMel Gorman 		 * proportional to the original scan target.
2492e82e0561SMel Gorman 		 */
2493e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2494e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2495e82e0561SMel Gorman 
24961a501907SMel Gorman 		/*
24971a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
24981a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
24991a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
25001a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
25011a501907SMel Gorman 		 */
25021a501907SMel Gorman 		if (!nr_file || !nr_anon)
25031a501907SMel Gorman 			break;
25041a501907SMel Gorman 
2505e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2506e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2507e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2508e82e0561SMel Gorman 			lru = LRU_BASE;
2509e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2510e82e0561SMel Gorman 		} else {
2511e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2512e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2513e82e0561SMel Gorman 			lru = LRU_FILE;
2514e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2515e82e0561SMel Gorman 		}
2516e82e0561SMel Gorman 
2517e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2518e82e0561SMel Gorman 		nr[lru] = 0;
2519e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2520e82e0561SMel Gorman 
2521e82e0561SMel Gorman 		/*
2522e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2523e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2524e82e0561SMel Gorman 		 */
2525e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2526e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2527e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2528e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2529e82e0561SMel Gorman 
2530e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2531e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2532e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2533e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2534e82e0561SMel Gorman 
2535e82e0561SMel Gorman 		scan_adjusted = true;
25369b4f98cdSJohannes Weiner 	}
25379b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
25389b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
25399b4f98cdSJohannes Weiner 
25409b4f98cdSJohannes Weiner 	/*
25419b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
25429b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
25439b4f98cdSJohannes Weiner 	 */
2544b91ac374SJohannes Weiner 	if (total_swap_pages && inactive_is_low(lruvec, LRU_INACTIVE_ANON))
25459b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
25469b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
25479b4f98cdSJohannes Weiner }
25489b4f98cdSJohannes Weiner 
254923b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
25509e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
255123b9da55SMel Gorman {
2552d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
255323b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
25549e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
255523b9da55SMel Gorman 		return true;
255623b9da55SMel Gorman 
255723b9da55SMel Gorman 	return false;
255823b9da55SMel Gorman }
255923b9da55SMel Gorman 
25604f98a2feSRik van Riel /*
256123b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
256223b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
256323b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
2564df3a45f9SQiwu Chen  * calls try_to_compact_pages() that it will have enough free pages to succeed.
256523b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
25663e7d3449SMel Gorman  */
2567a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
25683e7d3449SMel Gorman 					unsigned long nr_reclaimed,
25693e7d3449SMel Gorman 					struct scan_control *sc)
25703e7d3449SMel Gorman {
25713e7d3449SMel Gorman 	unsigned long pages_for_compaction;
25723e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2573a9dd0a83SMel Gorman 	int z;
25743e7d3449SMel Gorman 
25753e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
25769e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
25773e7d3449SMel Gorman 		return false;
25783e7d3449SMel Gorman 
25793e7d3449SMel Gorman 	/*
25805ee04716SVlastimil Babka 	 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
25815ee04716SVlastimil Babka 	 * number of pages that were scanned. This will return to the caller
25825ee04716SVlastimil Babka 	 * with the risk reclaim/compaction and the resulting allocation attempt
25835ee04716SVlastimil Babka 	 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
25845ee04716SVlastimil Babka 	 * allocations through requiring that the full LRU list has been scanned
25855ee04716SVlastimil Babka 	 * first, by assuming that zero delta of sc->nr_scanned means full LRU
25865ee04716SVlastimil Babka 	 * scan, but that approximation was wrong, and there were corner cases
25875ee04716SVlastimil Babka 	 * where always a non-zero amount of pages were scanned.
25882876592fSMel Gorman 	 */
25892876592fSMel Gorman 	if (!nr_reclaimed)
25902876592fSMel Gorman 		return false;
25913e7d3449SMel Gorman 
25923e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2593a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2594a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
25956aa303deSMel Gorman 		if (!managed_zone(zone))
2596a9dd0a83SMel Gorman 			continue;
2597a9dd0a83SMel Gorman 
2598a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2599cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
26003e7d3449SMel Gorman 		case COMPACT_CONTINUE:
26013e7d3449SMel Gorman 			return false;
26023e7d3449SMel Gorman 		default:
2603a9dd0a83SMel Gorman 			/* check next zone */
2604a9dd0a83SMel Gorman 			;
26053e7d3449SMel Gorman 		}
26063e7d3449SMel Gorman 	}
26071c6c1597SHillf Danton 
26081c6c1597SHillf Danton 	/*
26091c6c1597SHillf Danton 	 * If we have not reclaimed enough pages for compaction and the
26101c6c1597SHillf Danton 	 * inactive lists are large enough, continue reclaiming
26111c6c1597SHillf Danton 	 */
26121c6c1597SHillf Danton 	pages_for_compaction = compact_gap(sc->order);
26131c6c1597SHillf Danton 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
26141c6c1597SHillf Danton 	if (get_nr_swap_pages() > 0)
26151c6c1597SHillf Danton 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
26161c6c1597SHillf Danton 
26175ee04716SVlastimil Babka 	return inactive_lru_pages > pages_for_compaction;
2618a9dd0a83SMel Gorman }
26193e7d3449SMel Gorman 
26200f6a5cffSJohannes Weiner static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
2621f16015fbSJohannes Weiner {
26220f6a5cffSJohannes Weiner 	struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
2623694fbc0fSAndrew Morton 	struct mem_cgroup *memcg;
2624d108c772SAndrey Ryabinin 
26250f6a5cffSJohannes Weiner 	memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
2626694fbc0fSAndrew Morton 	do {
2627afaf07a6SJohannes Weiner 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
26288e8ae645SJohannes Weiner 		unsigned long reclaimed;
2629cb731d6cSVladimir Davydov 		unsigned long scanned;
26309b4f98cdSJohannes Weiner 
2631e3336cabSXunlei Pang 		/*
2632e3336cabSXunlei Pang 		 * This loop can become CPU-bound when target memcgs
2633e3336cabSXunlei Pang 		 * aren't eligible for reclaim - either because they
2634e3336cabSXunlei Pang 		 * don't have any reclaimable pages, or because their
2635e3336cabSXunlei Pang 		 * memory is explicitly protected. Avoid soft lockups.
2636e3336cabSXunlei Pang 		 */
2637e3336cabSXunlei Pang 		cond_resched();
2638e3336cabSXunlei Pang 
263945c7f7e1SChris Down 		mem_cgroup_calculate_protection(target_memcg, memcg);
264045c7f7e1SChris Down 
264145c7f7e1SChris Down 		if (mem_cgroup_below_min(memcg)) {
2642bf8d5d52SRoman Gushchin 			/*
2643bf8d5d52SRoman Gushchin 			 * Hard protection.
2644bf8d5d52SRoman Gushchin 			 * If there is no reclaimable memory, OOM.
2645bf8d5d52SRoman Gushchin 			 */
2646bf8d5d52SRoman Gushchin 			continue;
264745c7f7e1SChris Down 		} else if (mem_cgroup_below_low(memcg)) {
2648bf8d5d52SRoman Gushchin 			/*
2649bf8d5d52SRoman Gushchin 			 * Soft protection.
2650bf8d5d52SRoman Gushchin 			 * Respect the protection only as long as
2651bf8d5d52SRoman Gushchin 			 * there is an unprotected supply
2652bf8d5d52SRoman Gushchin 			 * of reclaimable memory from other cgroups.
2653bf8d5d52SRoman Gushchin 			 */
2654d6622f63SYisheng Xie 			if (!sc->memcg_low_reclaim) {
2655d6622f63SYisheng Xie 				sc->memcg_low_skipped = 1;
2656241994edSJohannes Weiner 				continue;
2657d6622f63SYisheng Xie 			}
2658e27be240SJohannes Weiner 			memcg_memory_event(memcg, MEMCG_LOW);
2659241994edSJohannes Weiner 		}
2660241994edSJohannes Weiner 
26618e8ae645SJohannes Weiner 		reclaimed = sc->nr_reclaimed;
2662cb731d6cSVladimir Davydov 		scanned = sc->nr_scanned;
2663afaf07a6SJohannes Weiner 
2664afaf07a6SJohannes Weiner 		shrink_lruvec(lruvec, sc);
2665f9be23d6SKonstantin Khlebnikov 
266628360f39SMel Gorman 		shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
266728360f39SMel Gorman 			    sc->priority);
2668cb731d6cSVladimir Davydov 
26698e8ae645SJohannes Weiner 		/* Record the group's reclaim efficiency */
26708e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, memcg, false,
26718e8ae645SJohannes Weiner 			   sc->nr_scanned - scanned,
26728e8ae645SJohannes Weiner 			   sc->nr_reclaimed - reclaimed);
26738e8ae645SJohannes Weiner 
26740f6a5cffSJohannes Weiner 	} while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
26750f6a5cffSJohannes Weiner }
26760f6a5cffSJohannes Weiner 
26776c9e0907SLiu Song static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
26780f6a5cffSJohannes Weiner {
26790f6a5cffSJohannes Weiner 	struct reclaim_state *reclaim_state = current->reclaim_state;
26800f6a5cffSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
26811b05117dSJohannes Weiner 	struct lruvec *target_lruvec;
26820f6a5cffSJohannes Weiner 	bool reclaimable = false;
2683b91ac374SJohannes Weiner 	unsigned long file;
26840f6a5cffSJohannes Weiner 
26851b05117dSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
26861b05117dSJohannes Weiner 
26870f6a5cffSJohannes Weiner again:
26880f6a5cffSJohannes Weiner 	memset(&sc->nr, 0, sizeof(sc->nr));
26890f6a5cffSJohannes Weiner 
26900f6a5cffSJohannes Weiner 	nr_reclaimed = sc->nr_reclaimed;
26910f6a5cffSJohannes Weiner 	nr_scanned = sc->nr_scanned;
26920f6a5cffSJohannes Weiner 
269353138ceaSJohannes Weiner 	/*
26947cf111bcSJohannes Weiner 	 * Determine the scan balance between anon and file LRUs.
26957cf111bcSJohannes Weiner 	 */
26967cf111bcSJohannes Weiner 	spin_lock_irq(&pgdat->lru_lock);
26977cf111bcSJohannes Weiner 	sc->anon_cost = target_lruvec->anon_cost;
26987cf111bcSJohannes Weiner 	sc->file_cost = target_lruvec->file_cost;
26997cf111bcSJohannes Weiner 	spin_unlock_irq(&pgdat->lru_lock);
27007cf111bcSJohannes Weiner 
27017cf111bcSJohannes Weiner 	/*
2702b91ac374SJohannes Weiner 	 * Target desirable inactive:active list ratios for the anon
2703b91ac374SJohannes Weiner 	 * and file LRU lists.
2704b91ac374SJohannes Weiner 	 */
2705b91ac374SJohannes Weiner 	if (!sc->force_deactivate) {
2706b91ac374SJohannes Weiner 		unsigned long refaults;
2707b91ac374SJohannes Weiner 
2708170b04b7SJoonsoo Kim 		refaults = lruvec_page_state(target_lruvec,
2709170b04b7SJoonsoo Kim 				WORKINGSET_ACTIVATE_ANON);
2710170b04b7SJoonsoo Kim 		if (refaults != target_lruvec->refaults[0] ||
2711170b04b7SJoonsoo Kim 			inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2712b91ac374SJohannes Weiner 			sc->may_deactivate |= DEACTIVATE_ANON;
2713b91ac374SJohannes Weiner 		else
2714b91ac374SJohannes Weiner 			sc->may_deactivate &= ~DEACTIVATE_ANON;
2715b91ac374SJohannes Weiner 
2716b91ac374SJohannes Weiner 		/*
2717b91ac374SJohannes Weiner 		 * When refaults are being observed, it means a new
2718b91ac374SJohannes Weiner 		 * workingset is being established. Deactivate to get
2719b91ac374SJohannes Weiner 		 * rid of any stale active pages quickly.
2720b91ac374SJohannes Weiner 		 */
2721b91ac374SJohannes Weiner 		refaults = lruvec_page_state(target_lruvec,
2722170b04b7SJoonsoo Kim 				WORKINGSET_ACTIVATE_FILE);
2723170b04b7SJoonsoo Kim 		if (refaults != target_lruvec->refaults[1] ||
2724b91ac374SJohannes Weiner 		    inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2725b91ac374SJohannes Weiner 			sc->may_deactivate |= DEACTIVATE_FILE;
2726b91ac374SJohannes Weiner 		else
2727b91ac374SJohannes Weiner 			sc->may_deactivate &= ~DEACTIVATE_FILE;
2728b91ac374SJohannes Weiner 	} else
2729b91ac374SJohannes Weiner 		sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2730b91ac374SJohannes Weiner 
2731b91ac374SJohannes Weiner 	/*
2732b91ac374SJohannes Weiner 	 * If we have plenty of inactive file pages that aren't
2733b91ac374SJohannes Weiner 	 * thrashing, try to reclaim those first before touching
2734b91ac374SJohannes Weiner 	 * anonymous pages.
2735b91ac374SJohannes Weiner 	 */
2736b91ac374SJohannes Weiner 	file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2737b91ac374SJohannes Weiner 	if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2738b91ac374SJohannes Weiner 		sc->cache_trim_mode = 1;
2739b91ac374SJohannes Weiner 	else
2740b91ac374SJohannes Weiner 		sc->cache_trim_mode = 0;
2741b91ac374SJohannes Weiner 
2742b91ac374SJohannes Weiner 	/*
274353138ceaSJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
274453138ceaSJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
274553138ceaSJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
274653138ceaSJohannes Weiner 	 * shrinks, so does the window for rotation from references.
274753138ceaSJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
274853138ceaSJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
274953138ceaSJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
275053138ceaSJohannes Weiner 	 */
275153138ceaSJohannes Weiner 	if (!cgroup_reclaim(sc)) {
275253138ceaSJohannes Weiner 		unsigned long total_high_wmark = 0;
2753b91ac374SJohannes Weiner 		unsigned long free, anon;
2754b91ac374SJohannes Weiner 		int z;
275553138ceaSJohannes Weiner 
275653138ceaSJohannes Weiner 		free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
275753138ceaSJohannes Weiner 		file = node_page_state(pgdat, NR_ACTIVE_FILE) +
275853138ceaSJohannes Weiner 			   node_page_state(pgdat, NR_INACTIVE_FILE);
275953138ceaSJohannes Weiner 
276053138ceaSJohannes Weiner 		for (z = 0; z < MAX_NR_ZONES; z++) {
276153138ceaSJohannes Weiner 			struct zone *zone = &pgdat->node_zones[z];
276253138ceaSJohannes Weiner 			if (!managed_zone(zone))
276353138ceaSJohannes Weiner 				continue;
276453138ceaSJohannes Weiner 
276553138ceaSJohannes Weiner 			total_high_wmark += high_wmark_pages(zone);
276653138ceaSJohannes Weiner 		}
276753138ceaSJohannes Weiner 
2768b91ac374SJohannes Weiner 		/*
2769b91ac374SJohannes Weiner 		 * Consider anon: if that's low too, this isn't a
2770b91ac374SJohannes Weiner 		 * runaway file reclaim problem, but rather just
2771b91ac374SJohannes Weiner 		 * extreme pressure. Reclaim as per usual then.
2772b91ac374SJohannes Weiner 		 */
2773b91ac374SJohannes Weiner 		anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2774b91ac374SJohannes Weiner 
2775b91ac374SJohannes Weiner 		sc->file_is_tiny =
2776b91ac374SJohannes Weiner 			file + free <= total_high_wmark &&
2777b91ac374SJohannes Weiner 			!(sc->may_deactivate & DEACTIVATE_ANON) &&
2778b91ac374SJohannes Weiner 			anon >> sc->priority;
277953138ceaSJohannes Weiner 	}
278053138ceaSJohannes Weiner 
27810f6a5cffSJohannes Weiner 	shrink_node_memcgs(pgdat, sc);
278270ddf637SAnton Vorontsov 
27836b4f7799SJohannes Weiner 	if (reclaim_state) {
2784cb731d6cSVladimir Davydov 		sc->nr_reclaimed += reclaim_state->reclaimed_slab;
27856b4f7799SJohannes Weiner 		reclaim_state->reclaimed_slab = 0;
27866b4f7799SJohannes Weiner 	}
27876b4f7799SJohannes Weiner 
27888e8ae645SJohannes Weiner 	/* Record the subtree's reclaim efficiency */
27891b05117dSJohannes Weiner 	vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
279070ddf637SAnton Vorontsov 		   sc->nr_scanned - nr_scanned,
279170ddf637SAnton Vorontsov 		   sc->nr_reclaimed - nr_reclaimed);
279270ddf637SAnton Vorontsov 
27932344d7e4SJohannes Weiner 	if (sc->nr_reclaimed - nr_reclaimed)
27942344d7e4SJohannes Weiner 		reclaimable = true;
27952344d7e4SJohannes Weiner 
2796e3c1ac58SAndrey Ryabinin 	if (current_is_kswapd()) {
2797d108c772SAndrey Ryabinin 		/*
2798e3c1ac58SAndrey Ryabinin 		 * If reclaim is isolating dirty pages under writeback,
2799e3c1ac58SAndrey Ryabinin 		 * it implies that the long-lived page allocation rate
2800e3c1ac58SAndrey Ryabinin 		 * is exceeding the page laundering rate. Either the
2801e3c1ac58SAndrey Ryabinin 		 * global limits are not being effective at throttling
2802e3c1ac58SAndrey Ryabinin 		 * processes due to the page distribution throughout
2803e3c1ac58SAndrey Ryabinin 		 * zones or there is heavy usage of a slow backing
2804e3c1ac58SAndrey Ryabinin 		 * device. The only option is to throttle from reclaim
2805e3c1ac58SAndrey Ryabinin 		 * context which is not ideal as there is no guarantee
2806d108c772SAndrey Ryabinin 		 * the dirtying process is throttled in the same way
2807d108c772SAndrey Ryabinin 		 * balance_dirty_pages() manages.
2808d108c772SAndrey Ryabinin 		 *
2809e3c1ac58SAndrey Ryabinin 		 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
2810e3c1ac58SAndrey Ryabinin 		 * count the number of pages under pages flagged for
2811e3c1ac58SAndrey Ryabinin 		 * immediate reclaim and stall if any are encountered
2812e3c1ac58SAndrey Ryabinin 		 * in the nr_immediate check below.
2813d108c772SAndrey Ryabinin 		 */
2814d108c772SAndrey Ryabinin 		if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
2815d108c772SAndrey Ryabinin 			set_bit(PGDAT_WRITEBACK, &pgdat->flags);
2816d108c772SAndrey Ryabinin 
2817d108c772SAndrey Ryabinin 		/* Allow kswapd to start writing pages during reclaim.*/
2818d108c772SAndrey Ryabinin 		if (sc->nr.unqueued_dirty == sc->nr.file_taken)
2819d108c772SAndrey Ryabinin 			set_bit(PGDAT_DIRTY, &pgdat->flags);
2820d108c772SAndrey Ryabinin 
2821d108c772SAndrey Ryabinin 		/*
28221eba09c1SRandy Dunlap 		 * If kswapd scans pages marked for immediate
2823d108c772SAndrey Ryabinin 		 * reclaim and under writeback (nr_immediate), it
2824d108c772SAndrey Ryabinin 		 * implies that pages are cycling through the LRU
2825d108c772SAndrey Ryabinin 		 * faster than they are written so also forcibly stall.
2826d108c772SAndrey Ryabinin 		 */
2827d108c772SAndrey Ryabinin 		if (sc->nr.immediate)
2828d108c772SAndrey Ryabinin 			congestion_wait(BLK_RW_ASYNC, HZ/10);
2829d108c772SAndrey Ryabinin 	}
2830d108c772SAndrey Ryabinin 
2831d108c772SAndrey Ryabinin 	/*
28321b05117dSJohannes Weiner 	 * Tag a node/memcg as congested if all the dirty pages
28331b05117dSJohannes Weiner 	 * scanned were backed by a congested BDI and
28341b05117dSJohannes Weiner 	 * wait_iff_congested will stall.
28351b05117dSJohannes Weiner 	 *
2836e3c1ac58SAndrey Ryabinin 	 * Legacy memcg will stall in page writeback so avoid forcibly
2837e3c1ac58SAndrey Ryabinin 	 * stalling in wait_iff_congested().
2838e3c1ac58SAndrey Ryabinin 	 */
28391b05117dSJohannes Weiner 	if ((current_is_kswapd() ||
28401b05117dSJohannes Weiner 	     (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
2841e3c1ac58SAndrey Ryabinin 	    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
28421b05117dSJohannes Weiner 		set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
2843e3c1ac58SAndrey Ryabinin 
2844e3c1ac58SAndrey Ryabinin 	/*
2845d108c772SAndrey Ryabinin 	 * Stall direct reclaim for IO completions if underlying BDIs
2846d108c772SAndrey Ryabinin 	 * and node is congested. Allow kswapd to continue until it
2847d108c772SAndrey Ryabinin 	 * starts encountering unqueued dirty pages or cycling through
2848d108c772SAndrey Ryabinin 	 * the LRU too quickly.
2849d108c772SAndrey Ryabinin 	 */
28501b05117dSJohannes Weiner 	if (!current_is_kswapd() && current_may_throttle() &&
28511b05117dSJohannes Weiner 	    !sc->hibernation_mode &&
28521b05117dSJohannes Weiner 	    test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
2853e3c1ac58SAndrey Ryabinin 		wait_iff_congested(BLK_RW_ASYNC, HZ/10);
2854d108c772SAndrey Ryabinin 
2855d2af3397SJohannes Weiner 	if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
2856d2af3397SJohannes Weiner 				    sc))
2857d2af3397SJohannes Weiner 		goto again;
28582344d7e4SJohannes Weiner 
2859c73322d0SJohannes Weiner 	/*
2860c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
2861c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
2862c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
2863c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
2864c73322d0SJohannes Weiner 	 */
2865c73322d0SJohannes Weiner 	if (reclaimable)
2866c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
2867f16015fbSJohannes Weiner }
2868f16015fbSJohannes Weiner 
286953853e2dSVlastimil Babka /*
2870fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
2871fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
2872fdd4c614SVlastimil Babka  * should reclaim first.
287353853e2dSVlastimil Babka  */
28744f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2875fe4b1b24SMel Gorman {
287631483b6aSMel Gorman 	unsigned long watermark;
2877fdd4c614SVlastimil Babka 	enum compact_result suitable;
2878fe4b1b24SMel Gorman 
2879fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2880fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
2881fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
2882fdd4c614SVlastimil Babka 		return true;
2883fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
2884fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
2885fe4b1b24SMel Gorman 		return false;
2886fe4b1b24SMel Gorman 
2887fdd4c614SVlastimil Babka 	/*
2888fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
2889fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
2890fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
2891fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
2892fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
2893fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
2894fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
2895fdd4c614SVlastimil Babka 	 */
2896fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
2897fdd4c614SVlastimil Babka 
2898fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
2899fe4b1b24SMel Gorman }
2900fe4b1b24SMel Gorman 
29011da177e4SLinus Torvalds /*
29021da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
29031da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
29041da177e4SLinus Torvalds  * request.
29051da177e4SLinus Torvalds  *
29061da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
29071da177e4SLinus Torvalds  * scan then give up on it.
29081da177e4SLinus Torvalds  */
29090a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
29101da177e4SLinus Torvalds {
2911dd1a239fSMel Gorman 	struct zoneref *z;
291254a6eb5cSMel Gorman 	struct zone *zone;
29130608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
29140608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2915619d0d76SWeijie Yang 	gfp_t orig_mask;
291679dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
29171cfb419bSKAMEZAWA Hiroyuki 
2918cc715d99SMel Gorman 	/*
2919cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2920cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2921cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2922cc715d99SMel Gorman 	 */
2923619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2924b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
2925cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
29264f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
2927b2e18757SMel Gorman 	}
2928cc715d99SMel Gorman 
2929d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2930b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
2931b2e18757SMel Gorman 		/*
29321cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
29331cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
29341cfb419bSKAMEZAWA Hiroyuki 		 */
2935b5ead35eSJohannes Weiner 		if (!cgroup_reclaim(sc)) {
2936344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2937344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
29381da177e4SLinus Torvalds 				continue;
293965ec02cbSVladimir Davydov 
2940e0887c19SRik van Riel 			/*
2941e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2942e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2943e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2944e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2945e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2946c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2947c7cfa37bSCopot Alexandru 			 * page allocations.
2948e0887c19SRik van Riel 			 */
29490b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
29500b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
29514f588331SMel Gorman 			    compaction_ready(zone, sc)) {
29520b06496aSJohannes Weiner 				sc->compaction_ready = true;
2953e0887c19SRik van Riel 				continue;
2954e0887c19SRik van Riel 			}
29550b06496aSJohannes Weiner 
29560608f43dSAndrew Morton 			/*
295779dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
295879dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
295979dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
296079dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
296179dafcdcSMel Gorman 			 */
296279dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
296379dafcdcSMel Gorman 				continue;
296479dafcdcSMel Gorman 
296579dafcdcSMel Gorman 			/*
29660608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
29670608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
29680608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
29690608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
29700608f43dSAndrew Morton 			 */
29710608f43dSAndrew Morton 			nr_soft_scanned = 0;
2972ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
29730608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
29740608f43dSAndrew Morton 						&nr_soft_scanned);
29750608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
29760608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
2977ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2978ac34a1a3SKAMEZAWA Hiroyuki 		}
2979d149e3b2SYing Han 
298079dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
298179dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
298279dafcdcSMel Gorman 			continue;
298379dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
2984970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
29851da177e4SLinus Torvalds 	}
2986e0c23279SMel Gorman 
298765ec02cbSVladimir Davydov 	/*
2988619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2989619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
2990619d0d76SWeijie Yang 	 */
2991619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
29921da177e4SLinus Torvalds }
29931da177e4SLinus Torvalds 
2994b910718aSJohannes Weiner static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
29952a2e4885SJohannes Weiner {
2996b910718aSJohannes Weiner 	struct lruvec *target_lruvec;
29972a2e4885SJohannes Weiner 	unsigned long refaults;
29982a2e4885SJohannes Weiner 
2999b910718aSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
3000170b04b7SJoonsoo Kim 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
3001170b04b7SJoonsoo Kim 	target_lruvec->refaults[0] = refaults;
3002170b04b7SJoonsoo Kim 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
3003170b04b7SJoonsoo Kim 	target_lruvec->refaults[1] = refaults;
30042a2e4885SJohannes Weiner }
30052a2e4885SJohannes Weiner 
30061da177e4SLinus Torvalds /*
30071da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
30081da177e4SLinus Torvalds  *
30091da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
30101da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
30111da177e4SLinus Torvalds  *
30121da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
30131da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
30145b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
30155b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
30165b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
30175b0830cbSJens Axboe  * work, and the allocation attempt will fail.
3018a41f24eaSNishanth Aravamudan  *
3019a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
3020a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
30211da177e4SLinus Torvalds  */
3022dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
30233115cd91SVladimir Davydov 					  struct scan_control *sc)
30241da177e4SLinus Torvalds {
3025241994edSJohannes Weiner 	int initial_priority = sc->priority;
30262a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
30272a2e4885SJohannes Weiner 	struct zoneref *z;
30282a2e4885SJohannes Weiner 	struct zone *zone;
3029241994edSJohannes Weiner retry:
3030873b4771SKeika Kobayashi 	delayacct_freepages_start();
3031873b4771SKeika Kobayashi 
3032b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
30337cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
30341da177e4SLinus Torvalds 
30359e3b2f8cSKonstantin Khlebnikov 	do {
303670ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
303770ddf637SAnton Vorontsov 				sc->priority);
303866e1707bSBalbir Singh 		sc->nr_scanned = 0;
30390a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
3040e0c23279SMel Gorman 
3041bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
30420b06496aSJohannes Weiner 			break;
30430b06496aSJohannes Weiner 
30440b06496aSJohannes Weiner 		if (sc->compaction_ready)
30450b06496aSJohannes Weiner 			break;
30461da177e4SLinus Torvalds 
30471da177e4SLinus Torvalds 		/*
30480e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
30490e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
30500e50ce3bSMinchan Kim 		 */
30510e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
30520e50ce3bSMinchan Kim 			sc->may_writepage = 1;
30530b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
3054bb21c7ceSKOSAKI Motohiro 
30552a2e4885SJohannes Weiner 	last_pgdat = NULL;
30562a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
30572a2e4885SJohannes Weiner 					sc->nodemask) {
30582a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
30592a2e4885SJohannes Weiner 			continue;
30602a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
30611b05117dSJohannes Weiner 
30622a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
30631b05117dSJohannes Weiner 
30641b05117dSJohannes Weiner 		if (cgroup_reclaim(sc)) {
30651b05117dSJohannes Weiner 			struct lruvec *lruvec;
30661b05117dSJohannes Weiner 
30671b05117dSJohannes Weiner 			lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
30681b05117dSJohannes Weiner 						   zone->zone_pgdat);
30691b05117dSJohannes Weiner 			clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
30701b05117dSJohannes Weiner 		}
30712a2e4885SJohannes Weiner 	}
30722a2e4885SJohannes Weiner 
3073873b4771SKeika Kobayashi 	delayacct_freepages_end();
3074873b4771SKeika Kobayashi 
3075bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
3076bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
3077bb21c7ceSKOSAKI Motohiro 
30780cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
30790b06496aSJohannes Weiner 	if (sc->compaction_ready)
30807335084dSMel Gorman 		return 1;
30817335084dSMel Gorman 
3082b91ac374SJohannes Weiner 	/*
3083b91ac374SJohannes Weiner 	 * We make inactive:active ratio decisions based on the node's
3084b91ac374SJohannes Weiner 	 * composition of memory, but a restrictive reclaim_idx or a
3085b91ac374SJohannes Weiner 	 * memory.low cgroup setting can exempt large amounts of
3086b91ac374SJohannes Weiner 	 * memory from reclaim. Neither of which are very common, so
3087b91ac374SJohannes Weiner 	 * instead of doing costly eligibility calculations of the
3088b91ac374SJohannes Weiner 	 * entire cgroup subtree up front, we assume the estimates are
3089b91ac374SJohannes Weiner 	 * good, and retry with forcible deactivation if that fails.
3090b91ac374SJohannes Weiner 	 */
3091b91ac374SJohannes Weiner 	if (sc->skipped_deactivate) {
3092b91ac374SJohannes Weiner 		sc->priority = initial_priority;
3093b91ac374SJohannes Weiner 		sc->force_deactivate = 1;
3094b91ac374SJohannes Weiner 		sc->skipped_deactivate = 0;
3095b91ac374SJohannes Weiner 		goto retry;
3096b91ac374SJohannes Weiner 	}
3097b91ac374SJohannes Weiner 
3098241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
3099d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
3100241994edSJohannes Weiner 		sc->priority = initial_priority;
3101b91ac374SJohannes Weiner 		sc->force_deactivate = 0;
3102d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
3103d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
3104241994edSJohannes Weiner 		goto retry;
3105241994edSJohannes Weiner 	}
3106241994edSJohannes Weiner 
3107bb21c7ceSKOSAKI Motohiro 	return 0;
31081da177e4SLinus Torvalds }
31091da177e4SLinus Torvalds 
3110c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
31115515061dSMel Gorman {
31125515061dSMel Gorman 	struct zone *zone;
31135515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
31145515061dSMel Gorman 	unsigned long free_pages = 0;
31155515061dSMel Gorman 	int i;
31165515061dSMel Gorman 	bool wmark_ok;
31175515061dSMel Gorman 
3118c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3119c73322d0SJohannes Weiner 		return true;
3120c73322d0SJohannes Weiner 
31215515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
31225515061dSMel Gorman 		zone = &pgdat->node_zones[i];
3123d450abd8SJohannes Weiner 		if (!managed_zone(zone))
3124d450abd8SJohannes Weiner 			continue;
3125d450abd8SJohannes Weiner 
3126d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
3127675becceSMel Gorman 			continue;
3128675becceSMel Gorman 
31295515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
31305515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
31315515061dSMel Gorman 	}
31325515061dSMel Gorman 
3133675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
3134675becceSMel Gorman 	if (!pfmemalloc_reserve)
3135675becceSMel Gorman 		return true;
3136675becceSMel Gorman 
31375515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
31385515061dSMel Gorman 
31395515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
31405515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
314197a225e6SJoonsoo Kim 		if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
314297a225e6SJoonsoo Kim 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
31435644e1fbSQian Cai 
31445515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
31455515061dSMel Gorman 	}
31465515061dSMel Gorman 
31475515061dSMel Gorman 	return wmark_ok;
31485515061dSMel Gorman }
31495515061dSMel Gorman 
31505515061dSMel Gorman /*
31515515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
31525515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
31535515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
315450694c28SMel Gorman  * when the low watermark is reached.
315550694c28SMel Gorman  *
315650694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
315750694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
31585515061dSMel Gorman  */
315950694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
31605515061dSMel Gorman 					nodemask_t *nodemask)
31615515061dSMel Gorman {
3162675becceSMel Gorman 	struct zoneref *z;
31635515061dSMel Gorman 	struct zone *zone;
3164675becceSMel Gorman 	pg_data_t *pgdat = NULL;
31655515061dSMel Gorman 
31665515061dSMel Gorman 	/*
31675515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
31685515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
31695515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
31705515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
31715515061dSMel Gorman 	 * processes to block on log_wait_commit().
31725515061dSMel Gorman 	 */
31735515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
317450694c28SMel Gorman 		goto out;
317550694c28SMel Gorman 
317650694c28SMel Gorman 	/*
317750694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
317850694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
317950694c28SMel Gorman 	 */
318050694c28SMel Gorman 	if (fatal_signal_pending(current))
318150694c28SMel Gorman 		goto out;
31825515061dSMel Gorman 
3183675becceSMel Gorman 	/*
3184675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
3185675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3186675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
3187675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
3188675becceSMel Gorman 	 *
3189675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
3190675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
3191675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
3192675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
3193675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
3194675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
3195675becceSMel Gorman 	 * should make reasonable progress.
3196675becceSMel Gorman 	 */
3197675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
319817636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
3199675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
3200675becceSMel Gorman 			continue;
3201675becceSMel Gorman 
3202675becceSMel Gorman 		/* Throttle based on the first usable node */
32035515061dSMel Gorman 		pgdat = zone->zone_pgdat;
3204c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
320550694c28SMel Gorman 			goto out;
3206675becceSMel Gorman 		break;
3207675becceSMel Gorman 	}
3208675becceSMel Gorman 
3209675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
3210675becceSMel Gorman 	if (!pgdat)
3211675becceSMel Gorman 		goto out;
32125515061dSMel Gorman 
321368243e76SMel Gorman 	/* Account for the throttling */
321468243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
321568243e76SMel Gorman 
32165515061dSMel Gorman 	/*
32175515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
32185515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
32195515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
32205515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
32215515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
32225515061dSMel Gorman 	 * second before continuing.
32235515061dSMel Gorman 	 */
32245515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
32255515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3226c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
322750694c28SMel Gorman 
322850694c28SMel Gorman 		goto check_pending;
32295515061dSMel Gorman 	}
32305515061dSMel Gorman 
32315515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
32325515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3233c73322d0SJohannes Weiner 		allow_direct_reclaim(pgdat));
323450694c28SMel Gorman 
323550694c28SMel Gorman check_pending:
323650694c28SMel Gorman 	if (fatal_signal_pending(current))
323750694c28SMel Gorman 		return true;
323850694c28SMel Gorman 
323950694c28SMel Gorman out:
324050694c28SMel Gorman 	return false;
32415515061dSMel Gorman }
32425515061dSMel Gorman 
3243dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3244327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
324566e1707bSBalbir Singh {
324633906bc5SMel Gorman 	unsigned long nr_reclaimed;
324766e1707bSBalbir Singh 	struct scan_control sc = {
324822fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3249f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3250b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
3251ee814fe2SJohannes Weiner 		.order = order,
3252ee814fe2SJohannes Weiner 		.nodemask = nodemask,
3253ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
3254ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3255a6dc60f8SJohannes Weiner 		.may_unmap = 1,
32562e2e4259SKOSAKI Motohiro 		.may_swap = 1,
325766e1707bSBalbir Singh 	};
325866e1707bSBalbir Singh 
32595515061dSMel Gorman 	/*
3260bb451fdfSGreg Thelen 	 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3261bb451fdfSGreg Thelen 	 * Confirm they are large enough for max values.
3262bb451fdfSGreg Thelen 	 */
3263bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3264bb451fdfSGreg Thelen 	BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3265bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3266bb451fdfSGreg Thelen 
3267bb451fdfSGreg Thelen 	/*
326850694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
326950694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
327050694c28SMel Gorman 	 * point.
32715515061dSMel Gorman 	 */
3272f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
32735515061dSMel Gorman 		return 1;
32745515061dSMel Gorman 
32751732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
32763481c37fSYafang Shao 	trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
327733906bc5SMel Gorman 
32783115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
327933906bc5SMel Gorman 
328033906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
32811732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
328233906bc5SMel Gorman 
328333906bc5SMel Gorman 	return nr_reclaimed;
328466e1707bSBalbir Singh }
328566e1707bSBalbir Singh 
3286c255a458SAndrew Morton #ifdef CONFIG_MEMCG
328766e1707bSBalbir Singh 
3288d2e5fb92SMichal Hocko /* Only used by soft limit reclaim. Do not reuse for anything else. */
3289a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
32904e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
3291ef8f2327SMel Gorman 						pg_data_t *pgdat,
32920ae5e89cSYing Han 						unsigned long *nr_scanned)
32934e416953SBalbir Singh {
3294afaf07a6SJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
32954e416953SBalbir Singh 	struct scan_control sc = {
3296b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3297ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
32984e416953SBalbir Singh 		.may_writepage = !laptop_mode,
32994e416953SBalbir Singh 		.may_unmap = 1,
3300b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
33014e416953SBalbir Singh 		.may_swap = !noswap,
33024e416953SBalbir Singh 	};
33030ae5e89cSYing Han 
3304d2e5fb92SMichal Hocko 	WARN_ON_ONCE(!current->reclaim_state);
3305d2e5fb92SMichal Hocko 
33064e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
33074e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3308bdce6d9eSKOSAKI Motohiro 
33099e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
33103481c37fSYafang Shao 						      sc.gfp_mask);
3311bdce6d9eSKOSAKI Motohiro 
33124e416953SBalbir Singh 	/*
33134e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
33144e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3315a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
33164e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
33174e416953SBalbir Singh 	 * the priority and make it zero.
33184e416953SBalbir Singh 	 */
3319afaf07a6SJohannes Weiner 	shrink_lruvec(lruvec, &sc);
3320bdce6d9eSKOSAKI Motohiro 
3321bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3322bdce6d9eSKOSAKI Motohiro 
33230ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
33240308f7cfSYafang Shao 
33254e416953SBalbir Singh 	return sc.nr_reclaimed;
33264e416953SBalbir Singh }
33274e416953SBalbir Singh 
332872835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3329b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
33308c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3331b70a2a21SJohannes Weiner 					   bool may_swap)
333266e1707bSBalbir Singh {
3333bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3334499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
333566e1707bSBalbir Singh 	struct scan_control sc = {
3336b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
33377dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3338ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3339b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3340ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3341ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
334266e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3343a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3344b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3345a09ed5e0SYing Han 	};
3346fa40d1eeSShakeel Butt 	/*
3347fa40d1eeSShakeel Butt 	 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
3348fa40d1eeSShakeel Butt 	 * equal pressure on all the nodes. This is based on the assumption that
3349fa40d1eeSShakeel Butt 	 * the reclaim does not bail out early.
3350fa40d1eeSShakeel Butt 	 */
3351fa40d1eeSShakeel Butt 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
335266e1707bSBalbir Singh 
33531732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
33543481c37fSYafang Shao 	trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
3355499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3356eb414681SJohannes Weiner 
33573115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3358eb414681SJohannes Weiner 
3359499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3360bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
33611732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3362bdce6d9eSKOSAKI Motohiro 
3363bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
336466e1707bSBalbir Singh }
336566e1707bSBalbir Singh #endif
336666e1707bSBalbir Singh 
33671d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3368ef8f2327SMel Gorman 				struct scan_control *sc)
3369f16015fbSJohannes Weiner {
3370b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3371b91ac374SJohannes Weiner 	struct lruvec *lruvec;
3372b95a2f2dSJohannes Weiner 
3373b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3374b95a2f2dSJohannes Weiner 		return;
3375b95a2f2dSJohannes Weiner 
3376b91ac374SJohannes Weiner 	lruvec = mem_cgroup_lruvec(NULL, pgdat);
3377b91ac374SJohannes Weiner 	if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
3378b91ac374SJohannes Weiner 		return;
3379b91ac374SJohannes Weiner 
3380b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3381b95a2f2dSJohannes Weiner 	do {
3382b91ac374SJohannes Weiner 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
33831a93be0eSKonstantin Khlebnikov 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
33849e3b2f8cSKonstantin Khlebnikov 				   sc, LRU_ACTIVE_ANON);
3385b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3386b95a2f2dSJohannes Weiner 	} while (memcg);
3387f16015fbSJohannes Weiner }
3388f16015fbSJohannes Weiner 
338997a225e6SJoonsoo Kim static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
33901c30844dSMel Gorman {
33911c30844dSMel Gorman 	int i;
33921c30844dSMel Gorman 	struct zone *zone;
33931c30844dSMel Gorman 
33941c30844dSMel Gorman 	/*
33951c30844dSMel Gorman 	 * Check for watermark boosts top-down as the higher zones
33961c30844dSMel Gorman 	 * are more likely to be boosted. Both watermarks and boosts
33971eba09c1SRandy Dunlap 	 * should not be checked at the same time as reclaim would
33981c30844dSMel Gorman 	 * start prematurely when there is no boosting and a lower
33991c30844dSMel Gorman 	 * zone is balanced.
34001c30844dSMel Gorman 	 */
340197a225e6SJoonsoo Kim 	for (i = highest_zoneidx; i >= 0; i--) {
34021c30844dSMel Gorman 		zone = pgdat->node_zones + i;
34031c30844dSMel Gorman 		if (!managed_zone(zone))
34041c30844dSMel Gorman 			continue;
34051c30844dSMel Gorman 
34061c30844dSMel Gorman 		if (zone->watermark_boost)
34071c30844dSMel Gorman 			return true;
34081c30844dSMel Gorman 	}
34091c30844dSMel Gorman 
34101c30844dSMel Gorman 	return false;
34111c30844dSMel Gorman }
34121c30844dSMel Gorman 
3413e716f2ebSMel Gorman /*
3414e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
341597a225e6SJoonsoo Kim  * and highest_zoneidx
3416e716f2ebSMel Gorman  */
341797a225e6SJoonsoo Kim static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
341860cefed4SJohannes Weiner {
3419e716f2ebSMel Gorman 	int i;
3420e716f2ebSMel Gorman 	unsigned long mark = -1;
3421e716f2ebSMel Gorman 	struct zone *zone;
342260cefed4SJohannes Weiner 
34231c30844dSMel Gorman 	/*
34241c30844dSMel Gorman 	 * Check watermarks bottom-up as lower zones are more likely to
34251c30844dSMel Gorman 	 * meet watermarks.
34261c30844dSMel Gorman 	 */
342797a225e6SJoonsoo Kim 	for (i = 0; i <= highest_zoneidx; i++) {
3428e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
34296256c6b4SMel Gorman 
3430e716f2ebSMel Gorman 		if (!managed_zone(zone))
3431e716f2ebSMel Gorman 			continue;
3432e716f2ebSMel Gorman 
3433e716f2ebSMel Gorman 		mark = high_wmark_pages(zone);
343497a225e6SJoonsoo Kim 		if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
34356256c6b4SMel Gorman 			return true;
343660cefed4SJohannes Weiner 	}
343760cefed4SJohannes Weiner 
3438e716f2ebSMel Gorman 	/*
343997a225e6SJoonsoo Kim 	 * If a node has no populated zone within highest_zoneidx, it does not
3440e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3441e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3442e716f2ebSMel Gorman 	 */
3443e716f2ebSMel Gorman 	if (mark == -1)
3444e716f2ebSMel Gorman 		return true;
3445e716f2ebSMel Gorman 
3446e716f2ebSMel Gorman 	return false;
3447e716f2ebSMel Gorman }
3448e716f2ebSMel Gorman 
3449631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
3450631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
3451631b6e08SMel Gorman {
34521b05117dSJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
34531b05117dSJohannes Weiner 
34541b05117dSJohannes Weiner 	clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3455631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
3456631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3457631b6e08SMel Gorman }
3458631b6e08SMel Gorman 
34591741c877SMel Gorman /*
34605515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
34615515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
34625515061dSMel Gorman  *
34635515061dSMel Gorman  * Returns true if kswapd is ready to sleep
34645515061dSMel Gorman  */
346597a225e6SJoonsoo Kim static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
346697a225e6SJoonsoo Kim 				int highest_zoneidx)
3467f50de2d3SMel Gorman {
34685515061dSMel Gorman 	/*
34699e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3470c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
34719e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
34729e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
34739e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
34749e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
34759e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
34769e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
34779e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
34789e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
34799e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
34805515061dSMel Gorman 	 */
34819e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
34829e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3483f50de2d3SMel Gorman 
3484c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3485c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3486c73322d0SJohannes Weiner 		return true;
3487c73322d0SJohannes Weiner 
348897a225e6SJoonsoo Kim 	if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
3489631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
3490333b0a45SShantanu Goel 		return true;
34911d82de61SMel Gorman 	}
34921d82de61SMel Gorman 
3493333b0a45SShantanu Goel 	return false;
3494f50de2d3SMel Gorman }
3495f50de2d3SMel Gorman 
34961da177e4SLinus Torvalds /*
34971d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
34981d82de61SMel Gorman  * zone that is currently unbalanced.
3499b8e83b94SMel Gorman  *
3500b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3501283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3502283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
350375485363SMel Gorman  */
35041d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3505accf6242SVlastimil Babka 			       struct scan_control *sc)
350675485363SMel Gorman {
35071d82de61SMel Gorman 	struct zone *zone;
35081d82de61SMel Gorman 	int z;
350975485363SMel Gorman 
35101d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
35111d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3512970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
35131d82de61SMel Gorman 		zone = pgdat->node_zones + z;
35146aa303deSMel Gorman 		if (!managed_zone(zone))
35151d82de61SMel Gorman 			continue;
35167c954f6dSMel Gorman 
35171d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
35187c954f6dSMel Gorman 	}
35197c954f6dSMel Gorman 
35201d82de61SMel Gorman 	/*
35211d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
35221d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
35231d82de61SMel Gorman 	 */
3524970a39a3SMel Gorman 	shrink_node(pgdat, sc);
35251d82de61SMel Gorman 
35261d82de61SMel Gorman 	/*
35271d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
35281d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
35291d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
35301d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
35311d82de61SMel Gorman 	 * can direct reclaim/compact.
35321d82de61SMel Gorman 	 */
35339861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
35341d82de61SMel Gorman 		sc->order = 0;
35351d82de61SMel Gorman 
3536b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
353775485363SMel Gorman }
353875485363SMel Gorman 
353975485363SMel Gorman /*
35401d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
35411d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
35421d82de61SMel Gorman  * balanced.
35431da177e4SLinus Torvalds  *
35441d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
35451da177e4SLinus Torvalds  *
35461da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
354741858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
35488bb4e7a2SWei Yang  * found to have free_pages <= high_wmark_pages(zone), any page in that zone
35491d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
35501d82de61SMel Gorman  * balanced.
35511da177e4SLinus Torvalds  */
355297a225e6SJoonsoo Kim static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
35531da177e4SLinus Torvalds {
35541da177e4SLinus Torvalds 	int i;
35550608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
35560608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3557eb414681SJohannes Weiner 	unsigned long pflags;
35581c30844dSMel Gorman 	unsigned long nr_boost_reclaim;
35591c30844dSMel Gorman 	unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
35601c30844dSMel Gorman 	bool boosted;
35611d82de61SMel Gorman 	struct zone *zone;
3562179e9639SAndrew Morton 	struct scan_control sc = {
3563179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3564ee814fe2SJohannes Weiner 		.order = order,
3565a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3566179e9639SAndrew Morton 	};
356793781325SOmar Sandoval 
35681732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
3569eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
357093781325SOmar Sandoval 	__fs_reclaim_acquire();
357193781325SOmar Sandoval 
3572f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
35731da177e4SLinus Torvalds 
35741c30844dSMel Gorman 	/*
35751c30844dSMel Gorman 	 * Account for the reclaim boost. Note that the zone boost is left in
35761c30844dSMel Gorman 	 * place so that parallel allocations that are near the watermark will
35771c30844dSMel Gorman 	 * stall or direct reclaim until kswapd is finished.
35781c30844dSMel Gorman 	 */
35791c30844dSMel Gorman 	nr_boost_reclaim = 0;
358097a225e6SJoonsoo Kim 	for (i = 0; i <= highest_zoneidx; i++) {
35811c30844dSMel Gorman 		zone = pgdat->node_zones + i;
35821c30844dSMel Gorman 		if (!managed_zone(zone))
35831c30844dSMel Gorman 			continue;
35841c30844dSMel Gorman 
35851c30844dSMel Gorman 		nr_boost_reclaim += zone->watermark_boost;
35861c30844dSMel Gorman 		zone_boosts[i] = zone->watermark_boost;
35871c30844dSMel Gorman 	}
35881c30844dSMel Gorman 	boosted = nr_boost_reclaim;
35891c30844dSMel Gorman 
35901c30844dSMel Gorman restart:
35911c30844dSMel Gorman 	sc.priority = DEF_PRIORITY;
35929e3b2f8cSKonstantin Khlebnikov 	do {
3593c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
3594b8e83b94SMel Gorman 		bool raise_priority = true;
35951c30844dSMel Gorman 		bool balanced;
359693781325SOmar Sandoval 		bool ret;
3597b8e83b94SMel Gorman 
359897a225e6SJoonsoo Kim 		sc.reclaim_idx = highest_zoneidx;
35991da177e4SLinus Torvalds 
360086c79f6bSMel Gorman 		/*
360184c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
360284c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
360384c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
360484c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
360584c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
360684c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
360784c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
360884c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
360986c79f6bSMel Gorman 		 */
361086c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
361186c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
361286c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
36136aa303deSMel Gorman 				if (!managed_zone(zone))
361486c79f6bSMel Gorman 					continue;
361586c79f6bSMel Gorman 
3616970a39a3SMel Gorman 				sc.reclaim_idx = i;
361786c79f6bSMel Gorman 				break;
361886c79f6bSMel Gorman 			}
361986c79f6bSMel Gorman 		}
362086c79f6bSMel Gorman 
362186c79f6bSMel Gorman 		/*
36221c30844dSMel Gorman 		 * If the pgdat is imbalanced then ignore boosting and preserve
36231c30844dSMel Gorman 		 * the watermarks for a later time and restart. Note that the
36241c30844dSMel Gorman 		 * zone watermarks will be still reset at the end of balancing
36251c30844dSMel Gorman 		 * on the grounds that the normal reclaim should be enough to
36261c30844dSMel Gorman 		 * re-evaluate if boosting is required when kswapd next wakes.
362786c79f6bSMel Gorman 		 */
362897a225e6SJoonsoo Kim 		balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
36291c30844dSMel Gorman 		if (!balanced && nr_boost_reclaim) {
36301c30844dSMel Gorman 			nr_boost_reclaim = 0;
36311c30844dSMel Gorman 			goto restart;
36321c30844dSMel Gorman 		}
36331c30844dSMel Gorman 
36341c30844dSMel Gorman 		/*
36351c30844dSMel Gorman 		 * If boosting is not active then only reclaim if there are no
36361c30844dSMel Gorman 		 * eligible zones. Note that sc.reclaim_idx is not used as
36371c30844dSMel Gorman 		 * buffer_heads_over_limit may have adjusted it.
36381c30844dSMel Gorman 		 */
36391c30844dSMel Gorman 		if (!nr_boost_reclaim && balanced)
36401da177e4SLinus Torvalds 			goto out;
3641e1dbeda6SAndrew Morton 
36421c30844dSMel Gorman 		/* Limit the priority of boosting to avoid reclaim writeback */
36431c30844dSMel Gorman 		if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
36441c30844dSMel Gorman 			raise_priority = false;
36451c30844dSMel Gorman 
36461c30844dSMel Gorman 		/*
36471c30844dSMel Gorman 		 * Do not writeback or swap pages for boosted reclaim. The
36481c30844dSMel Gorman 		 * intent is to relieve pressure not issue sub-optimal IO
36491c30844dSMel Gorman 		 * from reclaim context. If no pages are reclaimed, the
36501c30844dSMel Gorman 		 * reclaim will be aborted.
36511c30844dSMel Gorman 		 */
36521c30844dSMel Gorman 		sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
36531c30844dSMel Gorman 		sc.may_swap = !nr_boost_reclaim;
36541c30844dSMel Gorman 
36551da177e4SLinus Torvalds 		/*
36561d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
36571d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
36581d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
36591d82de61SMel Gorman 		 * about consistent aging.
36601d82de61SMel Gorman 		 */
3661ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
36621d82de61SMel Gorman 
36631d82de61SMel Gorman 		/*
3664b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3665b7ea3c41SMel Gorman 		 * even in laptop mode.
3666b7ea3c41SMel Gorman 		 */
3667047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
3668b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3669b7ea3c41SMel Gorman 
36701d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
36711da177e4SLinus Torvalds 		sc.nr_scanned = 0;
36720608f43dSAndrew Morton 		nr_soft_scanned = 0;
3673ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
36741d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
36750608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
36760608f43dSAndrew Morton 
367732a4330dSRik van Riel 		/*
36781d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
36791d82de61SMel Gorman 		 * enough pages are already being scanned that that high
36801d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
368132a4330dSRik van Riel 		 */
3682970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3683b8e83b94SMel Gorman 			raise_priority = false;
3684d7868daeSMel Gorman 
36855515061dSMel Gorman 		/*
36865515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
36875515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
36885515061dSMel Gorman 		 * able to safely make forward progress. Wake them
36895515061dSMel Gorman 		 */
36905515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3691c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
3692cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
36935515061dSMel Gorman 
3694b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
369593781325SOmar Sandoval 		__fs_reclaim_release();
369693781325SOmar Sandoval 		ret = try_to_freeze();
369793781325SOmar Sandoval 		__fs_reclaim_acquire();
369893781325SOmar Sandoval 		if (ret || kthread_should_stop())
3699b8e83b94SMel Gorman 			break;
3700b8e83b94SMel Gorman 
3701b8e83b94SMel Gorman 		/*
3702b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3703b8e83b94SMel Gorman 		 * progress in reclaiming pages
3704b8e83b94SMel Gorman 		 */
3705c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
37061c30844dSMel Gorman 		nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
37071c30844dSMel Gorman 
37081c30844dSMel Gorman 		/*
37091c30844dSMel Gorman 		 * If reclaim made no progress for a boost, stop reclaim as
37101c30844dSMel Gorman 		 * IO cannot be queued and it could be an infinite loop in
37111c30844dSMel Gorman 		 * extreme circumstances.
37121c30844dSMel Gorman 		 */
37131c30844dSMel Gorman 		if (nr_boost_reclaim && !nr_reclaimed)
37141c30844dSMel Gorman 			break;
37151c30844dSMel Gorman 
3716c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
3717b8e83b94SMel Gorman 			sc.priority--;
37181d82de61SMel Gorman 	} while (sc.priority >= 1);
37191da177e4SLinus Torvalds 
3720c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
3721c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
3722c73322d0SJohannes Weiner 
3723b8e83b94SMel Gorman out:
37241c30844dSMel Gorman 	/* If reclaim was boosted, account for the reclaim done in this pass */
37251c30844dSMel Gorman 	if (boosted) {
37261c30844dSMel Gorman 		unsigned long flags;
37271c30844dSMel Gorman 
372897a225e6SJoonsoo Kim 		for (i = 0; i <= highest_zoneidx; i++) {
37291c30844dSMel Gorman 			if (!zone_boosts[i])
37301c30844dSMel Gorman 				continue;
37311c30844dSMel Gorman 
37321c30844dSMel Gorman 			/* Increments are under the zone lock */
37331c30844dSMel Gorman 			zone = pgdat->node_zones + i;
37341c30844dSMel Gorman 			spin_lock_irqsave(&zone->lock, flags);
37351c30844dSMel Gorman 			zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
37361c30844dSMel Gorman 			spin_unlock_irqrestore(&zone->lock, flags);
37371c30844dSMel Gorman 		}
37381c30844dSMel Gorman 
37391c30844dSMel Gorman 		/*
37401c30844dSMel Gorman 		 * As there is now likely space, wakeup kcompact to defragment
37411c30844dSMel Gorman 		 * pageblocks.
37421c30844dSMel Gorman 		 */
374397a225e6SJoonsoo Kim 		wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
37441c30844dSMel Gorman 	}
37451c30844dSMel Gorman 
37462a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
374793781325SOmar Sandoval 	__fs_reclaim_release();
3748eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
37491732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3750e5ca8071SYafang Shao 
37510abdee2bSMel Gorman 	/*
37521d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
37531d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
37541d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
37551d82de61SMel Gorman 	 * remain at the higher level.
37560abdee2bSMel Gorman 	 */
37571d82de61SMel Gorman 	return sc.order;
37581da177e4SLinus Torvalds }
37591da177e4SLinus Torvalds 
3760e716f2ebSMel Gorman /*
376197a225e6SJoonsoo Kim  * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
376297a225e6SJoonsoo Kim  * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
376397a225e6SJoonsoo Kim  * not a valid index then either kswapd runs for first time or kswapd couldn't
376497a225e6SJoonsoo Kim  * sleep after previous reclaim attempt (node is still unbalanced). In that
376597a225e6SJoonsoo Kim  * case return the zone index of the previous kswapd reclaim cycle.
3766e716f2ebSMel Gorman  */
376797a225e6SJoonsoo Kim static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
376897a225e6SJoonsoo Kim 					   enum zone_type prev_highest_zoneidx)
3769e716f2ebSMel Gorman {
377097a225e6SJoonsoo Kim 	enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
37715644e1fbSQian Cai 
377297a225e6SJoonsoo Kim 	return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
3773e716f2ebSMel Gorman }
3774e716f2ebSMel Gorman 
377538087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
377697a225e6SJoonsoo Kim 				unsigned int highest_zoneidx)
3777f0bc0a60SKOSAKI Motohiro {
3778f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3779f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3780f0bc0a60SKOSAKI Motohiro 
3781f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3782f0bc0a60SKOSAKI Motohiro 		return;
3783f0bc0a60SKOSAKI Motohiro 
3784f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3785f0bc0a60SKOSAKI Motohiro 
3786333b0a45SShantanu Goel 	/*
3787333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
3788333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
3789333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
3790333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
3791333b0a45SShantanu Goel 	 * succeed.
3792333b0a45SShantanu Goel 	 */
379397a225e6SJoonsoo Kim 	if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
3794fd901c95SVlastimil Babka 		/*
3795fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3796fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3797fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3798fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3799fd901c95SVlastimil Babka 		 */
3800fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3801fd901c95SVlastimil Babka 
3802fd901c95SVlastimil Babka 		/*
3803fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3804fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3805fd901c95SVlastimil Babka 		 */
380697a225e6SJoonsoo Kim 		wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
3807fd901c95SVlastimil Babka 
3808f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
380938087d9bSMel Gorman 
381038087d9bSMel Gorman 		/*
381197a225e6SJoonsoo Kim 		 * If woken prematurely then reset kswapd_highest_zoneidx and
381238087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
381338087d9bSMel Gorman 		 * the previous request that slept prematurely.
381438087d9bSMel Gorman 		 */
381538087d9bSMel Gorman 		if (remaining) {
381697a225e6SJoonsoo Kim 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
381797a225e6SJoonsoo Kim 					kswapd_highest_zoneidx(pgdat,
381897a225e6SJoonsoo Kim 							highest_zoneidx));
38195644e1fbSQian Cai 
38205644e1fbSQian Cai 			if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
38215644e1fbSQian Cai 				WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
382238087d9bSMel Gorman 		}
382338087d9bSMel Gorman 
3824f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3825f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3826f0bc0a60SKOSAKI Motohiro 	}
3827f0bc0a60SKOSAKI Motohiro 
3828f0bc0a60SKOSAKI Motohiro 	/*
3829f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3830f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3831f0bc0a60SKOSAKI Motohiro 	 */
3832d9f21d42SMel Gorman 	if (!remaining &&
383397a225e6SJoonsoo Kim 	    prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
3834f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3835f0bc0a60SKOSAKI Motohiro 
3836f0bc0a60SKOSAKI Motohiro 		/*
3837f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3838f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3839f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3840f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3841f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3842f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3843f0bc0a60SKOSAKI Motohiro 		 */
3844f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
38451c7e7f6cSAaditya Kumar 
38461c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3847f0bc0a60SKOSAKI Motohiro 			schedule();
38481c7e7f6cSAaditya Kumar 
3849f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3850f0bc0a60SKOSAKI Motohiro 	} else {
3851f0bc0a60SKOSAKI Motohiro 		if (remaining)
3852f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3853f0bc0a60SKOSAKI Motohiro 		else
3854f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3855f0bc0a60SKOSAKI Motohiro 	}
3856f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3857f0bc0a60SKOSAKI Motohiro }
3858f0bc0a60SKOSAKI Motohiro 
38591da177e4SLinus Torvalds /*
38601da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
38611da177e4SLinus Torvalds  * from the init process.
38621da177e4SLinus Torvalds  *
38631da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
38641da177e4SLinus Torvalds  * free memory available even if there is no other activity
38651da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
38661da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
38671da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
38681da177e4SLinus Torvalds  *
38691da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
38701da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
38711da177e4SLinus Torvalds  */
38721da177e4SLinus Torvalds static int kswapd(void *p)
38731da177e4SLinus Torvalds {
3874e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
387597a225e6SJoonsoo Kim 	unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
38761da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
38771da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3878a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
38791da177e4SLinus Torvalds 
3880174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3881c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
38821da177e4SLinus Torvalds 
38831da177e4SLinus Torvalds 	/*
38841da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
38851da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
38861da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
38871da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
38881da177e4SLinus Torvalds 	 *
38891da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
38901da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
38911da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
38921da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
38931da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
38941da177e4SLinus Torvalds 	 */
3895930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
389683144186SRafael J. Wysocki 	set_freezable();
38971da177e4SLinus Torvalds 
38985644e1fbSQian Cai 	WRITE_ONCE(pgdat->kswapd_order, 0);
389997a225e6SJoonsoo Kim 	WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
39001da177e4SLinus Torvalds 	for ( ; ; ) {
39016f6313d4SJeff Liu 		bool ret;
39023e1d1d28SChristoph Lameter 
39035644e1fbSQian Cai 		alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
390497a225e6SJoonsoo Kim 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
390597a225e6SJoonsoo Kim 							highest_zoneidx);
3906e716f2ebSMel Gorman 
390738087d9bSMel Gorman kswapd_try_sleep:
390838087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
390997a225e6SJoonsoo Kim 					highest_zoneidx);
3910215ddd66SMel Gorman 
391197a225e6SJoonsoo Kim 		/* Read the new order and highest_zoneidx */
39122b47a24cSLukas Bulwahn 		alloc_order = READ_ONCE(pgdat->kswapd_order);
391397a225e6SJoonsoo Kim 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
391497a225e6SJoonsoo Kim 							highest_zoneidx);
39155644e1fbSQian Cai 		WRITE_ONCE(pgdat->kswapd_order, 0);
391697a225e6SJoonsoo Kim 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
39171da177e4SLinus Torvalds 
39188fe23e05SDavid Rientjes 		ret = try_to_freeze();
39198fe23e05SDavid Rientjes 		if (kthread_should_stop())
39208fe23e05SDavid Rientjes 			break;
39218fe23e05SDavid Rientjes 
39228fe23e05SDavid Rientjes 		/*
39238fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
39248fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3925b1296cc4SRafael J. Wysocki 		 */
392638087d9bSMel Gorman 		if (ret)
392738087d9bSMel Gorman 			continue;
39281d82de61SMel Gorman 
392938087d9bSMel Gorman 		/*
393038087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
393138087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
393238087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
393338087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
393438087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
393538087d9bSMel Gorman 		 * request (alloc_order).
393638087d9bSMel Gorman 		 */
393797a225e6SJoonsoo Kim 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
3938e5146b12SMel Gorman 						alloc_order);
393997a225e6SJoonsoo Kim 		reclaim_order = balance_pgdat(pgdat, alloc_order,
394097a225e6SJoonsoo Kim 						highest_zoneidx);
394138087d9bSMel Gorman 		if (reclaim_order < alloc_order)
394238087d9bSMel Gorman 			goto kswapd_try_sleep;
394333906bc5SMel Gorman 	}
3944b0a8cc58STakamori Yamaguchi 
394571abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
394671abdc15SJohannes Weiner 
39471da177e4SLinus Torvalds 	return 0;
39481da177e4SLinus Torvalds }
39491da177e4SLinus Torvalds 
39501da177e4SLinus Torvalds /*
39515ecd9d40SDavid Rientjes  * A zone is low on free memory or too fragmented for high-order memory.  If
39525ecd9d40SDavid Rientjes  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
39535ecd9d40SDavid Rientjes  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
39545ecd9d40SDavid Rientjes  * has failed or is not needed, still wake up kcompactd if only compaction is
39555ecd9d40SDavid Rientjes  * needed.
39561da177e4SLinus Torvalds  */
39575ecd9d40SDavid Rientjes void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
395897a225e6SJoonsoo Kim 		   enum zone_type highest_zoneidx)
39591da177e4SLinus Torvalds {
39601da177e4SLinus Torvalds 	pg_data_t *pgdat;
39615644e1fbSQian Cai 	enum zone_type curr_idx;
39621da177e4SLinus Torvalds 
39636aa303deSMel Gorman 	if (!managed_zone(zone))
39641da177e4SLinus Torvalds 		return;
39651da177e4SLinus Torvalds 
39665ecd9d40SDavid Rientjes 	if (!cpuset_zone_allowed(zone, gfp_flags))
39671da177e4SLinus Torvalds 		return;
3968dffcac2cSShakeel Butt 
39695644e1fbSQian Cai 	pgdat = zone->zone_pgdat;
397097a225e6SJoonsoo Kim 	curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
39715644e1fbSQian Cai 
397297a225e6SJoonsoo Kim 	if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
397397a225e6SJoonsoo Kim 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
39745644e1fbSQian Cai 
39755644e1fbSQian Cai 	if (READ_ONCE(pgdat->kswapd_order) < order)
39765644e1fbSQian Cai 		WRITE_ONCE(pgdat->kswapd_order, order);
39775644e1fbSQian Cai 
39788d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
39791da177e4SLinus Torvalds 		return;
3980e1a55637SMel Gorman 
39815ecd9d40SDavid Rientjes 	/* Hopeless node, leave it to direct reclaim if possible */
39825ecd9d40SDavid Rientjes 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
398397a225e6SJoonsoo Kim 	    (pgdat_balanced(pgdat, order, highest_zoneidx) &&
398497a225e6SJoonsoo Kim 	     !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
39855ecd9d40SDavid Rientjes 		/*
39865ecd9d40SDavid Rientjes 		 * There may be plenty of free memory available, but it's too
39875ecd9d40SDavid Rientjes 		 * fragmented for high-order allocations.  Wake up kcompactd
39885ecd9d40SDavid Rientjes 		 * and rely on compaction_suitable() to determine if it's
39895ecd9d40SDavid Rientjes 		 * needed.  If it fails, it will defer subsequent attempts to
39905ecd9d40SDavid Rientjes 		 * ratelimit its work.
39915ecd9d40SDavid Rientjes 		 */
39925ecd9d40SDavid Rientjes 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
399397a225e6SJoonsoo Kim 			wakeup_kcompactd(pgdat, order, highest_zoneidx);
3994c73322d0SJohannes Weiner 		return;
39955ecd9d40SDavid Rientjes 	}
3996c73322d0SJohannes Weiner 
399797a225e6SJoonsoo Kim 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
39985ecd9d40SDavid Rientjes 				      gfp_flags);
39998d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
40001da177e4SLinus Torvalds }
40011da177e4SLinus Torvalds 
4002c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
40031da177e4SLinus Torvalds /*
40047b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
4005d6277db4SRafael J. Wysocki  * freed pages.
4006d6277db4SRafael J. Wysocki  *
4007d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
4008d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
4009d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
40101da177e4SLinus Torvalds  */
40117b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
40121da177e4SLinus Torvalds {
4013d6277db4SRafael J. Wysocki 	struct scan_control sc = {
40147b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
4015ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
4016b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
40179e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
4018ee814fe2SJohannes Weiner 		.may_writepage = 1,
4019ee814fe2SJohannes Weiner 		.may_unmap = 1,
4020ee814fe2SJohannes Weiner 		.may_swap = 1,
4021ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
40221da177e4SLinus Torvalds 	};
40237b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
40247b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
4025499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
40261da177e4SLinus Torvalds 
4027d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
402893781325SOmar Sandoval 	noreclaim_flag = memalloc_noreclaim_save();
40291732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
4030d6277db4SRafael J. Wysocki 
40313115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4032d6277db4SRafael J. Wysocki 
40331732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
4034499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
403593781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4036d6277db4SRafael J. Wysocki 
40377b51755cSKOSAKI Motohiro 	return nr_reclaimed;
40381da177e4SLinus Torvalds }
4039c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
40401da177e4SLinus Torvalds 
40413218ae14SYasunori Goto /*
40423218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
40433218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
40443218ae14SYasunori Goto  */
40453218ae14SYasunori Goto int kswapd_run(int nid)
40463218ae14SYasunori Goto {
40473218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
40483218ae14SYasunori Goto 	int ret = 0;
40493218ae14SYasunori Goto 
40503218ae14SYasunori Goto 	if (pgdat->kswapd)
40513218ae14SYasunori Goto 		return 0;
40523218ae14SYasunori Goto 
40533218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
40543218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
40553218ae14SYasunori Goto 		/* failure at boot is fatal */
4056c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
4057d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
4058d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
4059d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
40603218ae14SYasunori Goto 	}
40613218ae14SYasunori Goto 	return ret;
40623218ae14SYasunori Goto }
40633218ae14SYasunori Goto 
40648fe23e05SDavid Rientjes /*
4065d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
4066bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
40678fe23e05SDavid Rientjes  */
40688fe23e05SDavid Rientjes void kswapd_stop(int nid)
40698fe23e05SDavid Rientjes {
40708fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
40718fe23e05SDavid Rientjes 
4072d8adde17SJiang Liu 	if (kswapd) {
40738fe23e05SDavid Rientjes 		kthread_stop(kswapd);
4074d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
4075d8adde17SJiang Liu 	}
40768fe23e05SDavid Rientjes }
40778fe23e05SDavid Rientjes 
40781da177e4SLinus Torvalds static int __init kswapd_init(void)
40791da177e4SLinus Torvalds {
40806b700b5bSWei Yang 	int nid;
408169e05944SAndrew Morton 
40821da177e4SLinus Torvalds 	swap_setup();
408348fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
40843218ae14SYasunori Goto  		kswapd_run(nid);
40851da177e4SLinus Torvalds 	return 0;
40861da177e4SLinus Torvalds }
40871da177e4SLinus Torvalds 
40881da177e4SLinus Torvalds module_init(kswapd_init)
40899eeff239SChristoph Lameter 
40909eeff239SChristoph Lameter #ifdef CONFIG_NUMA
40919eeff239SChristoph Lameter /*
4092a5f5f91dSMel Gorman  * Node reclaim mode
40939eeff239SChristoph Lameter  *
4094a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
40959eeff239SChristoph Lameter  * the watermarks.
40969eeff239SChristoph Lameter  */
4097a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
40989eeff239SChristoph Lameter 
4099648b5cf3SAlex Shi #define RECLAIM_WRITE (1<<0)	/* Writeout pages during reclaim */
4100648b5cf3SAlex Shi #define RECLAIM_UNMAP (1<<1)	/* Unmap pages during reclaim */
41011b2ffb78SChristoph Lameter 
41029eeff239SChristoph Lameter /*
4103a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
4104a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
4105a92f7126SChristoph Lameter  * a zone.
4106a92f7126SChristoph Lameter  */
4107a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
4108a92f7126SChristoph Lameter 
41099eeff239SChristoph Lameter /*
4110a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
41119614634fSChristoph Lameter  * occur.
41129614634fSChristoph Lameter  */
41139614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
41149614634fSChristoph Lameter 
41159614634fSChristoph Lameter /*
41160ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
41170ff38490SChristoph Lameter  * slab reclaim needs to occur.
41180ff38490SChristoph Lameter  */
41190ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
41200ff38490SChristoph Lameter 
412111fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
412290afa5deSMel Gorman {
412311fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
412411fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
412511fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
412690afa5deSMel Gorman 
412790afa5deSMel Gorman 	/*
412890afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
412990afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
413090afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
413190afa5deSMel Gorman 	 */
413290afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
413390afa5deSMel Gorman }
413490afa5deSMel Gorman 
413590afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4136a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
413790afa5deSMel Gorman {
4138d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
4139d031a157SAlexandru Moise 	unsigned long delta = 0;
414090afa5deSMel Gorman 
414190afa5deSMel Gorman 	/*
414295bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
414390afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
414411fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
414590afa5deSMel Gorman 	 * a better estimate
414690afa5deSMel Gorman 	 */
4147a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
4148a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
414990afa5deSMel Gorman 	else
4150a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
415190afa5deSMel Gorman 
415290afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
4153a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
4154a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
415590afa5deSMel Gorman 
415690afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
415790afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
415890afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
415990afa5deSMel Gorman 
416090afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
416190afa5deSMel Gorman }
416290afa5deSMel Gorman 
41630ff38490SChristoph Lameter /*
4164a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
41659eeff239SChristoph Lameter  */
4166a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
41679eeff239SChristoph Lameter {
41687fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
416969e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
41709eeff239SChristoph Lameter 	struct task_struct *p = current;
4171499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
4172179e9639SAndrew Morton 	struct scan_control sc = {
417362b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4174f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
4175bd2f6199SJohannes Weiner 		.order = order,
4176a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
4177a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4178a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4179ee814fe2SJohannes Weiner 		.may_swap = 1,
4180f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
4181179e9639SAndrew Morton 	};
41829eeff239SChristoph Lameter 
4183132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4184132bb8cfSYafang Shao 					   sc.gfp_mask);
4185132bb8cfSYafang Shao 
41869eeff239SChristoph Lameter 	cond_resched();
418793781325SOmar Sandoval 	fs_reclaim_acquire(sc.gfp_mask);
4188d4f7796eSChristoph Lameter 	/*
418995bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4190d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
419195bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
4192d4f7796eSChristoph Lameter 	 */
4193499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
4194499118e9SVlastimil Babka 	p->flags |= PF_SWAPWRITE;
41951732d2b0SAndrew Morton 	set_task_reclaim_state(p, &sc.reclaim_state);
4196c84db23cSChristoph Lameter 
4197a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
4198a92f7126SChristoph Lameter 		/*
4199894befecSAndrey Ryabinin 		 * Free memory by calling shrink node with increasing
42000ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
4201a92f7126SChristoph Lameter 		 */
4202a92f7126SChristoph Lameter 		do {
4203970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
42049e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
42050ff38490SChristoph Lameter 	}
4206a92f7126SChristoph Lameter 
42071732d2b0SAndrew Morton 	set_task_reclaim_state(p, NULL);
4208499118e9SVlastimil Babka 	current->flags &= ~PF_SWAPWRITE;
4209499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
421093781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4211132bb8cfSYafang Shao 
4212132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4213132bb8cfSYafang Shao 
4214a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
42159eeff239SChristoph Lameter }
4216179e9639SAndrew Morton 
4217a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4218179e9639SAndrew Morton {
4219d773ed6bSDavid Rientjes 	int ret;
4220179e9639SAndrew Morton 
4221179e9639SAndrew Morton 	/*
4222a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
42230ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
422434aa1330SChristoph Lameter 	 *
42259614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
42269614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
4227a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
4228a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
42299614634fSChristoph Lameter 	 * unmapped file backed pages.
4230179e9639SAndrew Morton 	 */
4231a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4232d42f3245SRoman Gushchin 	    node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
4233d42f3245SRoman Gushchin 	    pgdat->min_slab_pages)
4234a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
4235179e9639SAndrew Morton 
4236179e9639SAndrew Morton 	/*
4237d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
4238179e9639SAndrew Morton 	 */
4239d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4240a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4241179e9639SAndrew Morton 
4242179e9639SAndrew Morton 	/*
4243a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
4244179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
4245179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
4246179e9639SAndrew Morton 	 * as wide as possible.
4247179e9639SAndrew Morton 	 */
4248a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4249a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4250d773ed6bSDavid Rientjes 
4251a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4252a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4253fa5e084eSMel Gorman 
4254a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
4255a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4256d773ed6bSDavid Rientjes 
425724cf7251SMel Gorman 	if (!ret)
425824cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
425924cf7251SMel Gorman 
4260d773ed6bSDavid Rientjes 	return ret;
4261179e9639SAndrew Morton }
42629eeff239SChristoph Lameter #endif
4263894bc310SLee Schermerhorn 
426489e004eaSLee Schermerhorn /**
426564e3d12fSKuo-Hsin Yang  * check_move_unevictable_pages - check pages for evictability and move to
426664e3d12fSKuo-Hsin Yang  * appropriate zone lru list
426764e3d12fSKuo-Hsin Yang  * @pvec: pagevec with lru pages to check
426889e004eaSLee Schermerhorn  *
426964e3d12fSKuo-Hsin Yang  * Checks pages for evictability, if an evictable page is in the unevictable
427064e3d12fSKuo-Hsin Yang  * lru list, moves it to the appropriate evictable lru list. This function
427164e3d12fSKuo-Hsin Yang  * should be only used for lru pages.
427289e004eaSLee Schermerhorn  */
427364e3d12fSKuo-Hsin Yang void check_move_unevictable_pages(struct pagevec *pvec)
427489e004eaSLee Schermerhorn {
4275925b7673SJohannes Weiner 	struct lruvec *lruvec;
4276785b99feSMel Gorman 	struct pglist_data *pgdat = NULL;
427724513264SHugh Dickins 	int pgscanned = 0;
427824513264SHugh Dickins 	int pgrescued = 0;
427989e004eaSLee Schermerhorn 	int i;
428089e004eaSLee Schermerhorn 
428164e3d12fSKuo-Hsin Yang 	for (i = 0; i < pvec->nr; i++) {
428264e3d12fSKuo-Hsin Yang 		struct page *page = pvec->pages[i];
4283785b99feSMel Gorman 		struct pglist_data *pagepgdat = page_pgdat(page);
42848d8869caSHugh Dickins 		int nr_pages;
428589e004eaSLee Schermerhorn 
42868d8869caSHugh Dickins 		if (PageTransTail(page))
42878d8869caSHugh Dickins 			continue;
42888d8869caSHugh Dickins 
42898d8869caSHugh Dickins 		nr_pages = thp_nr_pages(page);
42908d8869caSHugh Dickins 		pgscanned += nr_pages;
42918d8869caSHugh Dickins 
4292785b99feSMel Gorman 		if (pagepgdat != pgdat) {
4293785b99feSMel Gorman 			if (pgdat)
4294785b99feSMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
4295785b99feSMel Gorman 			pgdat = pagepgdat;
4296785b99feSMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
429789e004eaSLee Schermerhorn 		}
4298785b99feSMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
429989e004eaSLee Schermerhorn 
430024513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
430124513264SHugh Dickins 			continue;
430289e004eaSLee Schermerhorn 
430339b5f29aSHugh Dickins 		if (page_evictable(page)) {
430424513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
430524513264SHugh Dickins 
4306309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
430724513264SHugh Dickins 			ClearPageUnevictable(page);
4308fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
4309fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
43108d8869caSHugh Dickins 			pgrescued += nr_pages;
431189e004eaSLee Schermerhorn 		}
431289e004eaSLee Schermerhorn 	}
431324513264SHugh Dickins 
4314785b99feSMel Gorman 	if (pgdat) {
431524513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
431624513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
4317785b99feSMel Gorman 		spin_unlock_irq(&pgdat->lru_lock);
431824513264SHugh Dickins 	}
431985046579SHugh Dickins }
432064e3d12fSKuo-Hsin Yang EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
4321