xref: /openbmc/linux/mm/vmscan.c (revision b17f18aff2876ceb3f1fde580c96cd489babf28e)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  *  linux/mm/vmscan.c
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
61da177e4SLinus Torvalds  *
71da177e4SLinus Torvalds  *  Swap reorganised 29.12.95, Stephen Tweedie.
81da177e4SLinus Torvalds  *  kswapd added: 7.1.96  sct
91da177e4SLinus Torvalds  *  Removed kswapd_ctl limits, and swap out as many pages as needed
101da177e4SLinus Torvalds  *  to bring the system back to freepages.high: 2.4.97, Rik van Riel.
111da177e4SLinus Torvalds  *  Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
121da177e4SLinus Torvalds  *  Multiqueue VM started 5.8.00, Rik van Riel.
131da177e4SLinus Torvalds  */
141da177e4SLinus Torvalds 
15b1de0d13SMitchel Humpherys #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16b1de0d13SMitchel Humpherys 
171da177e4SLinus Torvalds #include <linux/mm.h>
185b3cc15aSIngo Molnar #include <linux/sched/mm.h>
191da177e4SLinus Torvalds #include <linux/module.h>
205a0e3ad6STejun Heo #include <linux/gfp.h>
211da177e4SLinus Torvalds #include <linux/kernel_stat.h>
221da177e4SLinus Torvalds #include <linux/swap.h>
231da177e4SLinus Torvalds #include <linux/pagemap.h>
241da177e4SLinus Torvalds #include <linux/init.h>
251da177e4SLinus Torvalds #include <linux/highmem.h>
2670ddf637SAnton Vorontsov #include <linux/vmpressure.h>
27e129b5c2SAndrew Morton #include <linux/vmstat.h>
281da177e4SLinus Torvalds #include <linux/file.h>
291da177e4SLinus Torvalds #include <linux/writeback.h>
301da177e4SLinus Torvalds #include <linux/blkdev.h>
311da177e4SLinus Torvalds #include <linux/buffer_head.h>	/* for try_to_release_page(),
321da177e4SLinus Torvalds 					buffer_heads_over_limit */
331da177e4SLinus Torvalds #include <linux/mm_inline.h>
341da177e4SLinus Torvalds #include <linux/backing-dev.h>
351da177e4SLinus Torvalds #include <linux/rmap.h>
361da177e4SLinus Torvalds #include <linux/topology.h>
371da177e4SLinus Torvalds #include <linux/cpu.h>
381da177e4SLinus Torvalds #include <linux/cpuset.h>
393e7d3449SMel Gorman #include <linux/compaction.h>
401da177e4SLinus Torvalds #include <linux/notifier.h>
411da177e4SLinus Torvalds #include <linux/rwsem.h>
42248a0301SRafael J. Wysocki #include <linux/delay.h>
433218ae14SYasunori Goto #include <linux/kthread.h>
447dfb7103SNigel Cunningham #include <linux/freezer.h>
4566e1707bSBalbir Singh #include <linux/memcontrol.h>
46873b4771SKeika Kobayashi #include <linux/delayacct.h>
47af936a16SLee Schermerhorn #include <linux/sysctl.h>
48929bea7cSKOSAKI Motohiro #include <linux/oom.h>
4964e3d12fSKuo-Hsin Yang #include <linux/pagevec.h>
50268bb0ceSLinus Torvalds #include <linux/prefetch.h>
51b1de0d13SMitchel Humpherys #include <linux/printk.h>
52f9fe48beSRoss Zwisler #include <linux/dax.h>
53eb414681SJohannes Weiner #include <linux/psi.h>
541da177e4SLinus Torvalds 
551da177e4SLinus Torvalds #include <asm/tlbflush.h>
561da177e4SLinus Torvalds #include <asm/div64.h>
571da177e4SLinus Torvalds 
581da177e4SLinus Torvalds #include <linux/swapops.h>
59117aad1eSRafael Aquini #include <linux/balloon_compaction.h>
601da177e4SLinus Torvalds 
610f8053a5SNick Piggin #include "internal.h"
620f8053a5SNick Piggin 
6333906bc5SMel Gorman #define CREATE_TRACE_POINTS
6433906bc5SMel Gorman #include <trace/events/vmscan.h>
6533906bc5SMel Gorman 
661da177e4SLinus Torvalds struct scan_control {
6722fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6822fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
6922fba335SKOSAKI Motohiro 
70ee814fe2SJohannes Weiner 	/*
71ee814fe2SJohannes Weiner 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
72ee814fe2SJohannes Weiner 	 * are scanned.
73ee814fe2SJohannes Weiner 	 */
74ee814fe2SJohannes Weiner 	nodemask_t	*nodemask;
759e3b2f8cSKonstantin Khlebnikov 
765f53e762SKOSAKI Motohiro 	/*
77f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
78f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
79f16015fbSJohannes Weiner 	 */
80f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
8166e1707bSBalbir Singh 
821276ad68SJohannes Weiner 	/* Writepage batching in laptop mode; RECLAIM_WRITE */
83ee814fe2SJohannes Weiner 	unsigned int may_writepage:1;
84ee814fe2SJohannes Weiner 
85ee814fe2SJohannes Weiner 	/* Can mapped pages be reclaimed? */
86ee814fe2SJohannes Weiner 	unsigned int may_unmap:1;
87ee814fe2SJohannes Weiner 
88ee814fe2SJohannes Weiner 	/* Can pages be swapped as part of reclaim? */
89ee814fe2SJohannes Weiner 	unsigned int may_swap:1;
90ee814fe2SJohannes Weiner 
911c30844dSMel Gorman 	/* e.g. boosted watermark reclaim leaves slabs alone */
921c30844dSMel Gorman 	unsigned int may_shrinkslab:1;
931c30844dSMel Gorman 
94d6622f63SYisheng Xie 	/*
95d6622f63SYisheng Xie 	 * Cgroups are not reclaimed below their configured memory.low,
96d6622f63SYisheng Xie 	 * unless we threaten to OOM. If any cgroups are skipped due to
97d6622f63SYisheng Xie 	 * memory.low and nothing was reclaimed, go back for memory.low.
98d6622f63SYisheng Xie 	 */
99d6622f63SYisheng Xie 	unsigned int memcg_low_reclaim:1;
100d6622f63SYisheng Xie 	unsigned int memcg_low_skipped:1;
101241994edSJohannes Weiner 
102ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
103ee814fe2SJohannes Weiner 
104ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
105ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
106ee814fe2SJohannes Weiner 
107bb451fdfSGreg Thelen 	/* Allocation order */
108bb451fdfSGreg Thelen 	s8 order;
109bb451fdfSGreg Thelen 
110bb451fdfSGreg Thelen 	/* Scan (total_size >> priority) pages at once */
111bb451fdfSGreg Thelen 	s8 priority;
112bb451fdfSGreg Thelen 
113bb451fdfSGreg Thelen 	/* The highest zone to isolate pages for reclaim from */
114bb451fdfSGreg Thelen 	s8 reclaim_idx;
115bb451fdfSGreg Thelen 
116bb451fdfSGreg Thelen 	/* This context's GFP mask */
117bb451fdfSGreg Thelen 	gfp_t gfp_mask;
118bb451fdfSGreg Thelen 
119ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
120ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
121ee814fe2SJohannes Weiner 
122ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
123ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
124d108c772SAndrey Ryabinin 
125d108c772SAndrey Ryabinin 	struct {
126d108c772SAndrey Ryabinin 		unsigned int dirty;
127d108c772SAndrey Ryabinin 		unsigned int unqueued_dirty;
128d108c772SAndrey Ryabinin 		unsigned int congested;
129d108c772SAndrey Ryabinin 		unsigned int writeback;
130d108c772SAndrey Ryabinin 		unsigned int immediate;
131d108c772SAndrey Ryabinin 		unsigned int file_taken;
132d108c772SAndrey Ryabinin 		unsigned int taken;
133d108c772SAndrey Ryabinin 	} nr;
1341da177e4SLinus Torvalds };
1351da177e4SLinus Torvalds 
1361da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCH
1371da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field)			\
1381da177e4SLinus Torvalds 	do {								\
1391da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1401da177e4SLinus Torvalds 			struct page *prev;				\
1411da177e4SLinus Torvalds 									\
1421da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1431da177e4SLinus Torvalds 			prefetch(&prev->_field);			\
1441da177e4SLinus Torvalds 		}							\
1451da177e4SLinus Torvalds 	} while (0)
1461da177e4SLinus Torvalds #else
1471da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
1481da177e4SLinus Torvalds #endif
1491da177e4SLinus Torvalds 
1501da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1511da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1521da177e4SLinus Torvalds 	do {								\
1531da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1541da177e4SLinus Torvalds 			struct page *prev;				\
1551da177e4SLinus Torvalds 									\
1561da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1571da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1581da177e4SLinus Torvalds 		}							\
1591da177e4SLinus Torvalds 	} while (0)
1601da177e4SLinus Torvalds #else
1611da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1621da177e4SLinus Torvalds #endif
1631da177e4SLinus Torvalds 
1641da177e4SLinus Torvalds /*
1651da177e4SLinus Torvalds  * From 0 .. 100.  Higher means more swappy.
1661da177e4SLinus Torvalds  */
1671da177e4SLinus Torvalds int vm_swappiness = 60;
168d0480be4SWang Sheng-Hui /*
169d0480be4SWang Sheng-Hui  * The total number of pages which are beyond the high watermark within all
170d0480be4SWang Sheng-Hui  * zones.
171d0480be4SWang Sheng-Hui  */
172d0480be4SWang Sheng-Hui unsigned long vm_total_pages;
1731da177e4SLinus Torvalds 
1741da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1751da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1761da177e4SLinus Torvalds 
177b4c2b231SKirill Tkhai #ifdef CONFIG_MEMCG_KMEM
1787e010df5SKirill Tkhai 
1797e010df5SKirill Tkhai /*
1807e010df5SKirill Tkhai  * We allow subsystems to populate their shrinker-related
1817e010df5SKirill Tkhai  * LRU lists before register_shrinker_prepared() is called
1827e010df5SKirill Tkhai  * for the shrinker, since we don't want to impose
1837e010df5SKirill Tkhai  * restrictions on their internal registration order.
1847e010df5SKirill Tkhai  * In this case shrink_slab_memcg() may find corresponding
1857e010df5SKirill Tkhai  * bit is set in the shrinkers map.
1867e010df5SKirill Tkhai  *
1877e010df5SKirill Tkhai  * This value is used by the function to detect registering
1887e010df5SKirill Tkhai  * shrinkers and to skip do_shrink_slab() calls for them.
1897e010df5SKirill Tkhai  */
1907e010df5SKirill Tkhai #define SHRINKER_REGISTERING ((struct shrinker *)~0UL)
1917e010df5SKirill Tkhai 
192b4c2b231SKirill Tkhai static DEFINE_IDR(shrinker_idr);
193b4c2b231SKirill Tkhai static int shrinker_nr_max;
194b4c2b231SKirill Tkhai 
195b4c2b231SKirill Tkhai static int prealloc_memcg_shrinker(struct shrinker *shrinker)
196b4c2b231SKirill Tkhai {
197b4c2b231SKirill Tkhai 	int id, ret = -ENOMEM;
198b4c2b231SKirill Tkhai 
199b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
200b4c2b231SKirill Tkhai 	/* This may call shrinker, so it must use down_read_trylock() */
2017e010df5SKirill Tkhai 	id = idr_alloc(&shrinker_idr, SHRINKER_REGISTERING, 0, 0, GFP_KERNEL);
202b4c2b231SKirill Tkhai 	if (id < 0)
203b4c2b231SKirill Tkhai 		goto unlock;
204b4c2b231SKirill Tkhai 
2050a4465d3SKirill Tkhai 	if (id >= shrinker_nr_max) {
2060a4465d3SKirill Tkhai 		if (memcg_expand_shrinker_maps(id)) {
2070a4465d3SKirill Tkhai 			idr_remove(&shrinker_idr, id);
2080a4465d3SKirill Tkhai 			goto unlock;
2090a4465d3SKirill Tkhai 		}
2100a4465d3SKirill Tkhai 
211b4c2b231SKirill Tkhai 		shrinker_nr_max = id + 1;
2120a4465d3SKirill Tkhai 	}
213b4c2b231SKirill Tkhai 	shrinker->id = id;
214b4c2b231SKirill Tkhai 	ret = 0;
215b4c2b231SKirill Tkhai unlock:
216b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
217b4c2b231SKirill Tkhai 	return ret;
218b4c2b231SKirill Tkhai }
219b4c2b231SKirill Tkhai 
220b4c2b231SKirill Tkhai static void unregister_memcg_shrinker(struct shrinker *shrinker)
221b4c2b231SKirill Tkhai {
222b4c2b231SKirill Tkhai 	int id = shrinker->id;
223b4c2b231SKirill Tkhai 
224b4c2b231SKirill Tkhai 	BUG_ON(id < 0);
225b4c2b231SKirill Tkhai 
226b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
227b4c2b231SKirill Tkhai 	idr_remove(&shrinker_idr, id);
228b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
229b4c2b231SKirill Tkhai }
230b4c2b231SKirill Tkhai #else /* CONFIG_MEMCG_KMEM */
231b4c2b231SKirill Tkhai static int prealloc_memcg_shrinker(struct shrinker *shrinker)
232b4c2b231SKirill Tkhai {
233b4c2b231SKirill Tkhai 	return 0;
234b4c2b231SKirill Tkhai }
235b4c2b231SKirill Tkhai 
236b4c2b231SKirill Tkhai static void unregister_memcg_shrinker(struct shrinker *shrinker)
237b4c2b231SKirill Tkhai {
238b4c2b231SKirill Tkhai }
239b4c2b231SKirill Tkhai #endif /* CONFIG_MEMCG_KMEM */
240b4c2b231SKirill Tkhai 
241c255a458SAndrew Morton #ifdef CONFIG_MEMCG
24289b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
24389b5fae5SJohannes Weiner {
244f16015fbSJohannes Weiner 	return !sc->target_mem_cgroup;
24589b5fae5SJohannes Weiner }
24697c9341fSTejun Heo 
24797c9341fSTejun Heo /**
24897c9341fSTejun Heo  * sane_reclaim - is the usual dirty throttling mechanism operational?
24997c9341fSTejun Heo  * @sc: scan_control in question
25097c9341fSTejun Heo  *
25197c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
25297c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
25397c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
25497c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
25597c9341fSTejun Heo  * allocation and configurability.
25697c9341fSTejun Heo  *
25797c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
25897c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
25997c9341fSTejun Heo  */
26097c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
26197c9341fSTejun Heo {
26297c9341fSTejun Heo 	struct mem_cgroup *memcg = sc->target_mem_cgroup;
26397c9341fSTejun Heo 
26497c9341fSTejun Heo 	if (!memcg)
26597c9341fSTejun Heo 		return true;
26697c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
26769234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
26897c9341fSTejun Heo 		return true;
26997c9341fSTejun Heo #endif
27097c9341fSTejun Heo 	return false;
27197c9341fSTejun Heo }
272e3c1ac58SAndrey Ryabinin 
273e3c1ac58SAndrey Ryabinin static void set_memcg_congestion(pg_data_t *pgdat,
274e3c1ac58SAndrey Ryabinin 				struct mem_cgroup *memcg,
275e3c1ac58SAndrey Ryabinin 				bool congested)
276e3c1ac58SAndrey Ryabinin {
277e3c1ac58SAndrey Ryabinin 	struct mem_cgroup_per_node *mn;
278e3c1ac58SAndrey Ryabinin 
279e3c1ac58SAndrey Ryabinin 	if (!memcg)
280e3c1ac58SAndrey Ryabinin 		return;
281e3c1ac58SAndrey Ryabinin 
282e3c1ac58SAndrey Ryabinin 	mn = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
283e3c1ac58SAndrey Ryabinin 	WRITE_ONCE(mn->congested, congested);
284e3c1ac58SAndrey Ryabinin }
285e3c1ac58SAndrey Ryabinin 
286e3c1ac58SAndrey Ryabinin static bool memcg_congested(pg_data_t *pgdat,
287e3c1ac58SAndrey Ryabinin 			struct mem_cgroup *memcg)
288e3c1ac58SAndrey Ryabinin {
289e3c1ac58SAndrey Ryabinin 	struct mem_cgroup_per_node *mn;
290e3c1ac58SAndrey Ryabinin 
291e3c1ac58SAndrey Ryabinin 	mn = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
292e3c1ac58SAndrey Ryabinin 	return READ_ONCE(mn->congested);
293e3c1ac58SAndrey Ryabinin 
294e3c1ac58SAndrey Ryabinin }
29591a45470SKAMEZAWA Hiroyuki #else
29689b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
29789b5fae5SJohannes Weiner {
29889b5fae5SJohannes Weiner 	return true;
29989b5fae5SJohannes Weiner }
30097c9341fSTejun Heo 
30197c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
30297c9341fSTejun Heo {
30397c9341fSTejun Heo 	return true;
30497c9341fSTejun Heo }
305e3c1ac58SAndrey Ryabinin 
306e3c1ac58SAndrey Ryabinin static inline void set_memcg_congestion(struct pglist_data *pgdat,
307e3c1ac58SAndrey Ryabinin 				struct mem_cgroup *memcg, bool congested)
308e3c1ac58SAndrey Ryabinin {
309e3c1ac58SAndrey Ryabinin }
310e3c1ac58SAndrey Ryabinin 
311e3c1ac58SAndrey Ryabinin static inline bool memcg_congested(struct pglist_data *pgdat,
312e3c1ac58SAndrey Ryabinin 			struct mem_cgroup *memcg)
313e3c1ac58SAndrey Ryabinin {
314e3c1ac58SAndrey Ryabinin 	return false;
315e3c1ac58SAndrey Ryabinin 
316e3c1ac58SAndrey Ryabinin }
31791a45470SKAMEZAWA Hiroyuki #endif
31891a45470SKAMEZAWA Hiroyuki 
3195a1c84b4SMel Gorman /*
3205a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
3215a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
3225a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
3235a1c84b4SMel Gorman  */
3245a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
3255a1c84b4SMel Gorman {
3265a1c84b4SMel Gorman 	unsigned long nr;
3275a1c84b4SMel Gorman 
3285a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
3295a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
3305a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
3315a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
3325a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
3335a1c84b4SMel Gorman 
3345a1c84b4SMel Gorman 	return nr;
3355a1c84b4SMel Gorman }
3365a1c84b4SMel Gorman 
337fd538803SMichal Hocko /**
338fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
339fd538803SMichal Hocko  * @lruvec: lru vector
340fd538803SMichal Hocko  * @lru: lru to use
341fd538803SMichal Hocko  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
342fd538803SMichal Hocko  */
343fd538803SMichal Hocko unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, int zone_idx)
344c9f299d9SKOSAKI Motohiro {
345fd538803SMichal Hocko 	unsigned long lru_size;
346fd538803SMichal Hocko 	int zid;
347a3d8e054SKOSAKI Motohiro 
348fd538803SMichal Hocko 	if (!mem_cgroup_disabled())
349205b20ccSJohannes Weiner 		lru_size = lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
350fd538803SMichal Hocko 	else
351fd538803SMichal Hocko 		lru_size = node_page_state(lruvec_pgdat(lruvec), NR_LRU_BASE + lru);
352fd538803SMichal Hocko 
353fd538803SMichal Hocko 	for (zid = zone_idx + 1; zid < MAX_NR_ZONES; zid++) {
354fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
355fd538803SMichal Hocko 		unsigned long size;
356fd538803SMichal Hocko 
357fd538803SMichal Hocko 		if (!managed_zone(zone))
358fd538803SMichal Hocko 			continue;
359fd538803SMichal Hocko 
360fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
361fd538803SMichal Hocko 			size = mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
362fd538803SMichal Hocko 		else
363fd538803SMichal Hocko 			size = zone_page_state(&lruvec_pgdat(lruvec)->node_zones[zid],
364fd538803SMichal Hocko 				       NR_ZONE_LRU_BASE + lru);
365fd538803SMichal Hocko 		lru_size -= min(size, lru_size);
366c9f299d9SKOSAKI Motohiro 	}
367c9f299d9SKOSAKI Motohiro 
368fd538803SMichal Hocko 	return lru_size;
369b4536f0cSMichal Hocko 
370b4536f0cSMichal Hocko }
371b4536f0cSMichal Hocko 
3721da177e4SLinus Torvalds /*
3731d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
3741da177e4SLinus Torvalds  */
3758e04944fSTetsuo Handa int prealloc_shrinker(struct shrinker *shrinker)
3761da177e4SLinus Torvalds {
377b9726c26SAlexey Dobriyan 	unsigned int size = sizeof(*shrinker->nr_deferred);
3781d3d4437SGlauber Costa 
3791d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
3801d3d4437SGlauber Costa 		size *= nr_node_ids;
3811d3d4437SGlauber Costa 
3821d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
3831d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
3841d3d4437SGlauber Costa 		return -ENOMEM;
385b4c2b231SKirill Tkhai 
386b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
387b4c2b231SKirill Tkhai 		if (prealloc_memcg_shrinker(shrinker))
388b4c2b231SKirill Tkhai 			goto free_deferred;
389b4c2b231SKirill Tkhai 	}
390b4c2b231SKirill Tkhai 
3918e04944fSTetsuo Handa 	return 0;
392b4c2b231SKirill Tkhai 
393b4c2b231SKirill Tkhai free_deferred:
394b4c2b231SKirill Tkhai 	kfree(shrinker->nr_deferred);
395b4c2b231SKirill Tkhai 	shrinker->nr_deferred = NULL;
396b4c2b231SKirill Tkhai 	return -ENOMEM;
3978e04944fSTetsuo Handa }
3981d3d4437SGlauber Costa 
3998e04944fSTetsuo Handa void free_prealloced_shrinker(struct shrinker *shrinker)
4008e04944fSTetsuo Handa {
401b4c2b231SKirill Tkhai 	if (!shrinker->nr_deferred)
402b4c2b231SKirill Tkhai 		return;
403b4c2b231SKirill Tkhai 
404b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
405b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
406b4c2b231SKirill Tkhai 
4078e04944fSTetsuo Handa 	kfree(shrinker->nr_deferred);
4088e04944fSTetsuo Handa 	shrinker->nr_deferred = NULL;
4098e04944fSTetsuo Handa }
4108e04944fSTetsuo Handa 
4118e04944fSTetsuo Handa void register_shrinker_prepared(struct shrinker *shrinker)
4128e04944fSTetsuo Handa {
4131da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
4141da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
4157e010df5SKirill Tkhai #ifdef CONFIG_MEMCG_KMEM
4168df4a44cSKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
4177e010df5SKirill Tkhai 		idr_replace(&shrinker_idr, shrinker, shrinker->id);
4187e010df5SKirill Tkhai #endif
4191da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
4208e04944fSTetsuo Handa }
4218e04944fSTetsuo Handa 
4228e04944fSTetsuo Handa int register_shrinker(struct shrinker *shrinker)
4238e04944fSTetsuo Handa {
4248e04944fSTetsuo Handa 	int err = prealloc_shrinker(shrinker);
4258e04944fSTetsuo Handa 
4268e04944fSTetsuo Handa 	if (err)
4278e04944fSTetsuo Handa 		return err;
4288e04944fSTetsuo Handa 	register_shrinker_prepared(shrinker);
4291d3d4437SGlauber Costa 	return 0;
4301da177e4SLinus Torvalds }
4318e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
4321da177e4SLinus Torvalds 
4331da177e4SLinus Torvalds /*
4341da177e4SLinus Torvalds  * Remove one
4351da177e4SLinus Torvalds  */
4368e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
4371da177e4SLinus Torvalds {
438bb422a73STetsuo Handa 	if (!shrinker->nr_deferred)
439bb422a73STetsuo Handa 		return;
440b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
441b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
4421da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
4431da177e4SLinus Torvalds 	list_del(&shrinker->list);
4441da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
445ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
446bb422a73STetsuo Handa 	shrinker->nr_deferred = NULL;
4471da177e4SLinus Torvalds }
4488e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
4491da177e4SLinus Torvalds 
4501da177e4SLinus Torvalds #define SHRINK_BATCH 128
4511d3d4437SGlauber Costa 
452cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
4539092c71bSJosef Bacik 				    struct shrinker *shrinker, int priority)
4541da177e4SLinus Torvalds {
45524f7c6b9SDave Chinner 	unsigned long freed = 0;
4561da177e4SLinus Torvalds 	unsigned long long delta;
457635697c6SKonstantin Khlebnikov 	long total_scan;
458d5bc5fd3SVladimir Davydov 	long freeable;
459acf92b48SDave Chinner 	long nr;
460acf92b48SDave Chinner 	long new_nr;
4611d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
462e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
463e9299f50SDave Chinner 					  : SHRINK_BATCH;
4645f33a080SShaohua Li 	long scanned = 0, next_deferred;
4651da177e4SLinus Torvalds 
466ac7fb3adSKirill Tkhai 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
467ac7fb3adSKirill Tkhai 		nid = 0;
468ac7fb3adSKirill Tkhai 
469d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
4709b996468SKirill Tkhai 	if (freeable == 0 || freeable == SHRINK_EMPTY)
4719b996468SKirill Tkhai 		return freeable;
472635697c6SKonstantin Khlebnikov 
473acf92b48SDave Chinner 	/*
474acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
475acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
476acf92b48SDave Chinner 	 * don't also do this scanning work.
477acf92b48SDave Chinner 	 */
4781d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
479acf92b48SDave Chinner 
480acf92b48SDave Chinner 	total_scan = nr;
4814b85afbdSJohannes Weiner 	if (shrinker->seeks) {
4829092c71bSJosef Bacik 		delta = freeable >> priority;
4839092c71bSJosef Bacik 		delta *= 4;
4849092c71bSJosef Bacik 		do_div(delta, shrinker->seeks);
4854b85afbdSJohannes Weiner 	} else {
4864b85afbdSJohannes Weiner 		/*
4874b85afbdSJohannes Weiner 		 * These objects don't require any IO to create. Trim
4884b85afbdSJohannes Weiner 		 * them aggressively under memory pressure to keep
4894b85afbdSJohannes Weiner 		 * them from causing refetches in the IO caches.
4904b85afbdSJohannes Weiner 		 */
4914b85afbdSJohannes Weiner 		delta = freeable / 2;
4924b85afbdSJohannes Weiner 	}
493172b06c3SRoman Gushchin 
494acf92b48SDave Chinner 	total_scan += delta;
495acf92b48SDave Chinner 	if (total_scan < 0) {
496d75f773cSSakari Ailus 		pr_err("shrink_slab: %pS negative objects to delete nr=%ld\n",
497a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
498d5bc5fd3SVladimir Davydov 		total_scan = freeable;
4995f33a080SShaohua Li 		next_deferred = nr;
5005f33a080SShaohua Li 	} else
5015f33a080SShaohua Li 		next_deferred = total_scan;
502ea164d73SAndrea Arcangeli 
503ea164d73SAndrea Arcangeli 	/*
5043567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
5053567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
5063567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
5073567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
5083567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
509d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
5103567b59aSDave Chinner 	 * memory.
5113567b59aSDave Chinner 	 *
5123567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
5133567b59aSDave Chinner 	 * a large delta change is calculated directly.
5143567b59aSDave Chinner 	 */
515d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
516d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
5173567b59aSDave Chinner 
5183567b59aSDave Chinner 	/*
519ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
520ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
521ea164d73SAndrea Arcangeli 	 * freeable entries.
522ea164d73SAndrea Arcangeli 	 */
523d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
524d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
5251da177e4SLinus Torvalds 
52624f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
5279092c71bSJosef Bacik 				   freeable, delta, total_scan, priority);
52809576073SDave Chinner 
5290b1fb40aSVladimir Davydov 	/*
5300b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
5310b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
5320b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
5330b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
5340b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
5350b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
5360b1fb40aSVladimir Davydov 	 * batch_size.
5370b1fb40aSVladimir Davydov 	 *
5380b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
5390b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
540d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
5410b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
5420b1fb40aSVladimir Davydov 	 * possible.
5430b1fb40aSVladimir Davydov 	 */
5440b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
545d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
54624f7c6b9SDave Chinner 		unsigned long ret;
5470b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
5481da177e4SLinus Torvalds 
5490b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
550d460acb5SChris Wilson 		shrinkctl->nr_scanned = nr_to_scan;
55124f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
55224f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
5531da177e4SLinus Torvalds 			break;
55424f7c6b9SDave Chinner 		freed += ret;
55524f7c6b9SDave Chinner 
556d460acb5SChris Wilson 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
557d460acb5SChris Wilson 		total_scan -= shrinkctl->nr_scanned;
558d460acb5SChris Wilson 		scanned += shrinkctl->nr_scanned;
5591da177e4SLinus Torvalds 
5601da177e4SLinus Torvalds 		cond_resched();
5611da177e4SLinus Torvalds 	}
5621da177e4SLinus Torvalds 
5635f33a080SShaohua Li 	if (next_deferred >= scanned)
5645f33a080SShaohua Li 		next_deferred -= scanned;
5655f33a080SShaohua Li 	else
5665f33a080SShaohua Li 		next_deferred = 0;
567acf92b48SDave Chinner 	/*
568acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
569acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
570acf92b48SDave Chinner 	 * scan, there is no need to do an update.
571acf92b48SDave Chinner 	 */
5725f33a080SShaohua Li 	if (next_deferred > 0)
5735f33a080SShaohua Li 		new_nr = atomic_long_add_return(next_deferred,
5741d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
57583aeeadaSKonstantin Khlebnikov 	else
5761d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
577acf92b48SDave Chinner 
578df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
5791d3d4437SGlauber Costa 	return freed;
5801d3d4437SGlauber Costa }
5811d3d4437SGlauber Costa 
582b0dedc49SKirill Tkhai #ifdef CONFIG_MEMCG_KMEM
583b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
584b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
585b0dedc49SKirill Tkhai {
586b0dedc49SKirill Tkhai 	struct memcg_shrinker_map *map;
587b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
588b8e57efaSKirill Tkhai 	int i;
589b0dedc49SKirill Tkhai 
590b0dedc49SKirill Tkhai 	if (!memcg_kmem_enabled() || !mem_cgroup_online(memcg))
591b0dedc49SKirill Tkhai 		return 0;
592b0dedc49SKirill Tkhai 
593b0dedc49SKirill Tkhai 	if (!down_read_trylock(&shrinker_rwsem))
594b0dedc49SKirill Tkhai 		return 0;
595b0dedc49SKirill Tkhai 
596b0dedc49SKirill Tkhai 	map = rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_map,
597b0dedc49SKirill Tkhai 					true);
598b0dedc49SKirill Tkhai 	if (unlikely(!map))
599b0dedc49SKirill Tkhai 		goto unlock;
600b0dedc49SKirill Tkhai 
601b0dedc49SKirill Tkhai 	for_each_set_bit(i, map->map, shrinker_nr_max) {
602b0dedc49SKirill Tkhai 		struct shrink_control sc = {
603b0dedc49SKirill Tkhai 			.gfp_mask = gfp_mask,
604b0dedc49SKirill Tkhai 			.nid = nid,
605b0dedc49SKirill Tkhai 			.memcg = memcg,
606b0dedc49SKirill Tkhai 		};
607b0dedc49SKirill Tkhai 		struct shrinker *shrinker;
608b0dedc49SKirill Tkhai 
609b0dedc49SKirill Tkhai 		shrinker = idr_find(&shrinker_idr, i);
6107e010df5SKirill Tkhai 		if (unlikely(!shrinker || shrinker == SHRINKER_REGISTERING)) {
6117e010df5SKirill Tkhai 			if (!shrinker)
612b0dedc49SKirill Tkhai 				clear_bit(i, map->map);
613b0dedc49SKirill Tkhai 			continue;
614b0dedc49SKirill Tkhai 		}
615b0dedc49SKirill Tkhai 
616b0dedc49SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
617f90280d6SKirill Tkhai 		if (ret == SHRINK_EMPTY) {
618f90280d6SKirill Tkhai 			clear_bit(i, map->map);
619f90280d6SKirill Tkhai 			/*
620f90280d6SKirill Tkhai 			 * After the shrinker reported that it had no objects to
621f90280d6SKirill Tkhai 			 * free, but before we cleared the corresponding bit in
622f90280d6SKirill Tkhai 			 * the memcg shrinker map, a new object might have been
623f90280d6SKirill Tkhai 			 * added. To make sure, we have the bit set in this
624f90280d6SKirill Tkhai 			 * case, we invoke the shrinker one more time and reset
625f90280d6SKirill Tkhai 			 * the bit if it reports that it is not empty anymore.
626f90280d6SKirill Tkhai 			 * The memory barrier here pairs with the barrier in
627f90280d6SKirill Tkhai 			 * memcg_set_shrinker_bit():
628f90280d6SKirill Tkhai 			 *
629f90280d6SKirill Tkhai 			 * list_lru_add()     shrink_slab_memcg()
630f90280d6SKirill Tkhai 			 *   list_add_tail()    clear_bit()
631f90280d6SKirill Tkhai 			 *   <MB>               <MB>
632f90280d6SKirill Tkhai 			 *   set_bit()          do_shrink_slab()
633f90280d6SKirill Tkhai 			 */
634f90280d6SKirill Tkhai 			smp_mb__after_atomic();
635f90280d6SKirill Tkhai 			ret = do_shrink_slab(&sc, shrinker, priority);
6369b996468SKirill Tkhai 			if (ret == SHRINK_EMPTY)
6379b996468SKirill Tkhai 				ret = 0;
638f90280d6SKirill Tkhai 			else
639f90280d6SKirill Tkhai 				memcg_set_shrinker_bit(memcg, nid, i);
640f90280d6SKirill Tkhai 		}
641b0dedc49SKirill Tkhai 		freed += ret;
642b0dedc49SKirill Tkhai 
643b0dedc49SKirill Tkhai 		if (rwsem_is_contended(&shrinker_rwsem)) {
644b0dedc49SKirill Tkhai 			freed = freed ? : 1;
645b0dedc49SKirill Tkhai 			break;
646b0dedc49SKirill Tkhai 		}
647b0dedc49SKirill Tkhai 	}
648b0dedc49SKirill Tkhai unlock:
649b0dedc49SKirill Tkhai 	up_read(&shrinker_rwsem);
650b0dedc49SKirill Tkhai 	return freed;
651b0dedc49SKirill Tkhai }
652b0dedc49SKirill Tkhai #else /* CONFIG_MEMCG_KMEM */
653b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
654b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
655b0dedc49SKirill Tkhai {
656b0dedc49SKirill Tkhai 	return 0;
657b0dedc49SKirill Tkhai }
658b0dedc49SKirill Tkhai #endif /* CONFIG_MEMCG_KMEM */
659b0dedc49SKirill Tkhai 
6606b4f7799SJohannes Weiner /**
661cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
6626b4f7799SJohannes Weiner  * @gfp_mask: allocation context
6636b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
664cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
6659092c71bSJosef Bacik  * @priority: the reclaim priority
6661d3d4437SGlauber Costa  *
6676b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
6681d3d4437SGlauber Costa  *
6696b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
6706b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
6711d3d4437SGlauber Costa  *
672aeed1d32SVladimir Davydov  * @memcg specifies the memory cgroup to target. Unaware shrinkers
673aeed1d32SVladimir Davydov  * are called only if it is the root cgroup.
674cb731d6cSVladimir Davydov  *
6759092c71bSJosef Bacik  * @priority is sc->priority, we take the number of objects and >> by priority
6769092c71bSJosef Bacik  * in order to get the scan target.
6771d3d4437SGlauber Costa  *
6786b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
6791d3d4437SGlauber Costa  */
680cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
681cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
6829092c71bSJosef Bacik 				 int priority)
6831d3d4437SGlauber Costa {
684b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
6851d3d4437SGlauber Costa 	struct shrinker *shrinker;
6861d3d4437SGlauber Costa 
687aeed1d32SVladimir Davydov 	if (!mem_cgroup_is_root(memcg))
688b0dedc49SKirill Tkhai 		return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
689cb731d6cSVladimir Davydov 
690e830c63aSTetsuo Handa 	if (!down_read_trylock(&shrinker_rwsem))
6911d3d4437SGlauber Costa 		goto out;
6921d3d4437SGlauber Costa 
6931d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
6946b4f7799SJohannes Weiner 		struct shrink_control sc = {
6956b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
6966b4f7799SJohannes Weiner 			.nid = nid,
697cb731d6cSVladimir Davydov 			.memcg = memcg,
6986b4f7799SJohannes Weiner 		};
6996b4f7799SJohannes Weiner 
7009b996468SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
7019b996468SKirill Tkhai 		if (ret == SHRINK_EMPTY)
7029b996468SKirill Tkhai 			ret = 0;
7039b996468SKirill Tkhai 		freed += ret;
704e496612cSMinchan Kim 		/*
705e496612cSMinchan Kim 		 * Bail out if someone want to register a new shrinker to
706e496612cSMinchan Kim 		 * prevent the regsitration from being stalled for long periods
707e496612cSMinchan Kim 		 * by parallel ongoing shrinking.
708e496612cSMinchan Kim 		 */
709e496612cSMinchan Kim 		if (rwsem_is_contended(&shrinker_rwsem)) {
710e496612cSMinchan Kim 			freed = freed ? : 1;
711e496612cSMinchan Kim 			break;
712e496612cSMinchan Kim 		}
713ec97097bSVladimir Davydov 	}
7141d3d4437SGlauber Costa 
7151da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
716f06590bdSMinchan Kim out:
717f06590bdSMinchan Kim 	cond_resched();
71824f7c6b9SDave Chinner 	return freed;
7191da177e4SLinus Torvalds }
7201da177e4SLinus Torvalds 
721cb731d6cSVladimir Davydov void drop_slab_node(int nid)
722cb731d6cSVladimir Davydov {
723cb731d6cSVladimir Davydov 	unsigned long freed;
724cb731d6cSVladimir Davydov 
725cb731d6cSVladimir Davydov 	do {
726cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
727cb731d6cSVladimir Davydov 
728cb731d6cSVladimir Davydov 		freed = 0;
729aeed1d32SVladimir Davydov 		memcg = mem_cgroup_iter(NULL, NULL, NULL);
730cb731d6cSVladimir Davydov 		do {
7319092c71bSJosef Bacik 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
732cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
733cb731d6cSVladimir Davydov 	} while (freed > 10);
734cb731d6cSVladimir Davydov }
735cb731d6cSVladimir Davydov 
736cb731d6cSVladimir Davydov void drop_slab(void)
737cb731d6cSVladimir Davydov {
738cb731d6cSVladimir Davydov 	int nid;
739cb731d6cSVladimir Davydov 
740cb731d6cSVladimir Davydov 	for_each_online_node(nid)
741cb731d6cSVladimir Davydov 		drop_slab_node(nid);
742cb731d6cSVladimir Davydov }
743cb731d6cSVladimir Davydov 
7441da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
7451da177e4SLinus Torvalds {
746ceddc3a5SJohannes Weiner 	/*
747ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
74867891fffSMatthew Wilcox 	 * that isolated the page, the page cache and optional buffer
74967891fffSMatthew Wilcox 	 * heads at page->private.
750ceddc3a5SJohannes Weiner 	 */
75167891fffSMatthew Wilcox 	int page_cache_pins = PageTransHuge(page) && PageSwapCache(page) ?
752bd4c82c2SHuang Ying 		HPAGE_PMD_NR : 1;
75367891fffSMatthew Wilcox 	return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
7541da177e4SLinus Torvalds }
7551da177e4SLinus Torvalds 
756703c2708STejun Heo static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
7571da177e4SLinus Torvalds {
758930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
7591da177e4SLinus Torvalds 		return 1;
760703c2708STejun Heo 	if (!inode_write_congested(inode))
7611da177e4SLinus Torvalds 		return 1;
762703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
7631da177e4SLinus Torvalds 		return 1;
7641da177e4SLinus Torvalds 	return 0;
7651da177e4SLinus Torvalds }
7661da177e4SLinus Torvalds 
7671da177e4SLinus Torvalds /*
7681da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
7691da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
7701da177e4SLinus Torvalds  * fsync(), msync() or close().
7711da177e4SLinus Torvalds  *
7721da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
7731da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
7741da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
7751da177e4SLinus Torvalds  *
7761da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
7771da177e4SLinus Torvalds  * __GFP_FS.
7781da177e4SLinus Torvalds  */
7791da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
7801da177e4SLinus Torvalds 				struct page *page, int error)
7811da177e4SLinus Torvalds {
7827eaceaccSJens Axboe 	lock_page(page);
7833e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
7843e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
7851da177e4SLinus Torvalds 	unlock_page(page);
7861da177e4SLinus Torvalds }
7871da177e4SLinus Torvalds 
78804e62a29SChristoph Lameter /* possible outcome of pageout() */
78904e62a29SChristoph Lameter typedef enum {
79004e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
79104e62a29SChristoph Lameter 	PAGE_KEEP,
79204e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
79304e62a29SChristoph Lameter 	PAGE_ACTIVATE,
79404e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
79504e62a29SChristoph Lameter 	PAGE_SUCCESS,
79604e62a29SChristoph Lameter 	/* page is clean and locked */
79704e62a29SChristoph Lameter 	PAGE_CLEAN,
79804e62a29SChristoph Lameter } pageout_t;
79904e62a29SChristoph Lameter 
8001da177e4SLinus Torvalds /*
8011742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
8021742f19fSAndrew Morton  * Calls ->writepage().
8031da177e4SLinus Torvalds  */
804c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
8057d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
8061da177e4SLinus Torvalds {
8071da177e4SLinus Torvalds 	/*
8081da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
8091da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
8101da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
8111da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
8121da177e4SLinus Torvalds 	 * PagePrivate for that.
8131da177e4SLinus Torvalds 	 *
8148174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
8151da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
8161da177e4SLinus Torvalds 	 * will block.
8171da177e4SLinus Torvalds 	 *
8181da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
8191da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
8201da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
8211da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
8221da177e4SLinus Torvalds 	 */
8231da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
8241da177e4SLinus Torvalds 		return PAGE_KEEP;
8251da177e4SLinus Torvalds 	if (!mapping) {
8261da177e4SLinus Torvalds 		/*
8271da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
8281da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
8291da177e4SLinus Torvalds 		 */
830266cf658SDavid Howells 		if (page_has_private(page)) {
8311da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
8321da177e4SLinus Torvalds 				ClearPageDirty(page);
833b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
8341da177e4SLinus Torvalds 				return PAGE_CLEAN;
8351da177e4SLinus Torvalds 			}
8361da177e4SLinus Torvalds 		}
8371da177e4SLinus Torvalds 		return PAGE_KEEP;
8381da177e4SLinus Torvalds 	}
8391da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
8401da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
841703c2708STejun Heo 	if (!may_write_to_inode(mapping->host, sc))
8421da177e4SLinus Torvalds 		return PAGE_KEEP;
8431da177e4SLinus Torvalds 
8441da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
8451da177e4SLinus Torvalds 		int res;
8461da177e4SLinus Torvalds 		struct writeback_control wbc = {
8471da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
8481da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
849111ebb6eSOGAWA Hirofumi 			.range_start = 0,
850111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
8511da177e4SLinus Torvalds 			.for_reclaim = 1,
8521da177e4SLinus Torvalds 		};
8531da177e4SLinus Torvalds 
8541da177e4SLinus Torvalds 		SetPageReclaim(page);
8551da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
8561da177e4SLinus Torvalds 		if (res < 0)
8571da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
858994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
8591da177e4SLinus Torvalds 			ClearPageReclaim(page);
8601da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
8611da177e4SLinus Torvalds 		}
862c661b078SAndy Whitcroft 
8631da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
8641da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
8651da177e4SLinus Torvalds 			ClearPageReclaim(page);
8661da177e4SLinus Torvalds 		}
8673aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
868c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
8691da177e4SLinus Torvalds 		return PAGE_SUCCESS;
8701da177e4SLinus Torvalds 	}
8711da177e4SLinus Torvalds 
8721da177e4SLinus Torvalds 	return PAGE_CLEAN;
8731da177e4SLinus Torvalds }
8741da177e4SLinus Torvalds 
875a649fd92SAndrew Morton /*
876e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
877e286781dSNick Piggin  * gets returned with a refcount of 0.
878a649fd92SAndrew Morton  */
879a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
880a528910eSJohannes Weiner 			    bool reclaimed)
88149d2e9ccSChristoph Lameter {
882c4843a75SGreg Thelen 	unsigned long flags;
883bd4c82c2SHuang Ying 	int refcount;
884c4843a75SGreg Thelen 
88528e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
88628e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
88749d2e9ccSChristoph Lameter 
888b93b0163SMatthew Wilcox 	xa_lock_irqsave(&mapping->i_pages, flags);
88949d2e9ccSChristoph Lameter 	/*
8900fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
8910fd0e6b0SNick Piggin 	 *
8920fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
8930fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
8940fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
8950fd0e6b0SNick Piggin 	 * here, then the following race may occur:
8960fd0e6b0SNick Piggin 	 *
8970fd0e6b0SNick Piggin 	 * get_user_pages(&page);
8980fd0e6b0SNick Piggin 	 * [user mapping goes away]
8990fd0e6b0SNick Piggin 	 * write_to(page);
9000fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
9010fd0e6b0SNick Piggin 	 * SetPageDirty(page);
9020fd0e6b0SNick Piggin 	 * put_page(page);
9030fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
9040fd0e6b0SNick Piggin 	 *
9050fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
9060fd0e6b0SNick Piggin 	 *
9070fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
9080fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
9090139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
9100fd0e6b0SNick Piggin 	 *
9110fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
912b93b0163SMatthew Wilcox 	 * and thus under the i_pages lock, then this ordering is not required.
91349d2e9ccSChristoph Lameter 	 */
914bd4c82c2SHuang Ying 	if (unlikely(PageTransHuge(page)) && PageSwapCache(page))
915bd4c82c2SHuang Ying 		refcount = 1 + HPAGE_PMD_NR;
916bd4c82c2SHuang Ying 	else
917bd4c82c2SHuang Ying 		refcount = 2;
918bd4c82c2SHuang Ying 	if (!page_ref_freeze(page, refcount))
91949d2e9ccSChristoph Lameter 		goto cannot_free;
9201c4c3b99SJiang Biao 	/* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
921e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
922bd4c82c2SHuang Ying 		page_ref_unfreeze(page, refcount);
92349d2e9ccSChristoph Lameter 		goto cannot_free;
924e286781dSNick Piggin 	}
92549d2e9ccSChristoph Lameter 
92649d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
92749d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
9280a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
9294e17ec25SMatthew Wilcox 		__delete_from_swap_cache(page, swap);
930b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
93175f6d6d2SMinchan Kim 		put_swap_page(page, swap);
932e286781dSNick Piggin 	} else {
9336072d13cSLinus Torvalds 		void (*freepage)(struct page *);
934a528910eSJohannes Weiner 		void *shadow = NULL;
9356072d13cSLinus Torvalds 
9366072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
937a528910eSJohannes Weiner 		/*
938a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
939a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
940a528910eSJohannes Weiner 		 *
941a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
942a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
943a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
944a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
945a528910eSJohannes Weiner 		 * back.
946f9fe48beSRoss Zwisler 		 *
947f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
948f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
949f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
950f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
951b93b0163SMatthew Wilcox 		 * same address_space.
952a528910eSJohannes Weiner 		 */
953a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
954f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
955a7ca12f9SAndrey Ryabinin 			shadow = workingset_eviction(page);
95662cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
957b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
9586072d13cSLinus Torvalds 
9596072d13cSLinus Torvalds 		if (freepage != NULL)
9606072d13cSLinus Torvalds 			freepage(page);
961e286781dSNick Piggin 	}
962e286781dSNick Piggin 
96349d2e9ccSChristoph Lameter 	return 1;
96449d2e9ccSChristoph Lameter 
96549d2e9ccSChristoph Lameter cannot_free:
966b93b0163SMatthew Wilcox 	xa_unlock_irqrestore(&mapping->i_pages, flags);
96749d2e9ccSChristoph Lameter 	return 0;
96849d2e9ccSChristoph Lameter }
96949d2e9ccSChristoph Lameter 
9701da177e4SLinus Torvalds /*
971e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
972e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
973e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
974e286781dSNick Piggin  * this page.
975e286781dSNick Piggin  */
976e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
977e286781dSNick Piggin {
978a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
979e286781dSNick Piggin 		/*
980e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
981e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
982e286781dSNick Piggin 		 * atomic operation.
983e286781dSNick Piggin 		 */
984fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
985e286781dSNick Piggin 		return 1;
986e286781dSNick Piggin 	}
987e286781dSNick Piggin 	return 0;
988e286781dSNick Piggin }
989e286781dSNick Piggin 
990894bc310SLee Schermerhorn /**
991894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
992894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
993894bc310SLee Schermerhorn  *
994894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
995894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
996894bc310SLee Schermerhorn  *
997894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
998894bc310SLee Schermerhorn  */
999894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
1000894bc310SLee Schermerhorn {
1001c53954a0SMel Gorman 	lru_cache_add(page);
1002894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
1003894bc310SLee Schermerhorn }
1004894bc310SLee Schermerhorn 
1005dfc8d636SJohannes Weiner enum page_references {
1006dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
1007dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
100864574746SJohannes Weiner 	PAGEREF_KEEP,
1009dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
1010dfc8d636SJohannes Weiner };
1011dfc8d636SJohannes Weiner 
1012dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
1013dfc8d636SJohannes Weiner 						  struct scan_control *sc)
1014dfc8d636SJohannes Weiner {
101564574746SJohannes Weiner 	int referenced_ptes, referenced_page;
1016dfc8d636SJohannes Weiner 	unsigned long vm_flags;
1017dfc8d636SJohannes Weiner 
1018c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1019c3ac9a8aSJohannes Weiner 					  &vm_flags);
102064574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
1021dfc8d636SJohannes Weiner 
1022dfc8d636SJohannes Weiner 	/*
1023dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
1024dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
1025dfc8d636SJohannes Weiner 	 */
1026dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
1027dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
1028dfc8d636SJohannes Weiner 
102964574746SJohannes Weiner 	if (referenced_ptes) {
1030e4898273SMichal Hocko 		if (PageSwapBacked(page))
103164574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
103264574746SJohannes Weiner 		/*
103364574746SJohannes Weiner 		 * All mapped pages start out with page table
103464574746SJohannes Weiner 		 * references from the instantiating fault, so we need
103564574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
103664574746SJohannes Weiner 		 * than once.
103764574746SJohannes Weiner 		 *
103864574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
103964574746SJohannes Weiner 		 * inactive list.  Another page table reference will
104064574746SJohannes Weiner 		 * lead to its activation.
104164574746SJohannes Weiner 		 *
104264574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
104364574746SJohannes Weiner 		 * so that recently deactivated but used pages are
104464574746SJohannes Weiner 		 * quickly recovered.
104564574746SJohannes Weiner 		 */
104664574746SJohannes Weiner 		SetPageReferenced(page);
104764574746SJohannes Weiner 
104834dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
1049dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
1050dfc8d636SJohannes Weiner 
1051c909e993SKonstantin Khlebnikov 		/*
1052c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
1053c909e993SKonstantin Khlebnikov 		 */
1054c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
1055c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
1056c909e993SKonstantin Khlebnikov 
105764574746SJohannes Weiner 		return PAGEREF_KEEP;
105864574746SJohannes Weiner 	}
105964574746SJohannes Weiner 
1060dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
10612e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
1062dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
106364574746SJohannes Weiner 
106464574746SJohannes Weiner 	return PAGEREF_RECLAIM;
1065dfc8d636SJohannes Weiner }
1066dfc8d636SJohannes Weiner 
1067e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
1068e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
1069e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
1070e2be15f6SMel Gorman {
1071b4597226SMel Gorman 	struct address_space *mapping;
1072b4597226SMel Gorman 
1073e2be15f6SMel Gorman 	/*
1074e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
1075e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
1076e2be15f6SMel Gorman 	 */
1077802a3a92SShaohua Li 	if (!page_is_file_cache(page) ||
1078802a3a92SShaohua Li 	    (PageAnon(page) && !PageSwapBacked(page))) {
1079e2be15f6SMel Gorman 		*dirty = false;
1080e2be15f6SMel Gorman 		*writeback = false;
1081e2be15f6SMel Gorman 		return;
1082e2be15f6SMel Gorman 	}
1083e2be15f6SMel Gorman 
1084e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
1085e2be15f6SMel Gorman 	*dirty = PageDirty(page);
1086e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
1087b4597226SMel Gorman 
1088b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
1089b4597226SMel Gorman 	if (!page_has_private(page))
1090b4597226SMel Gorman 		return;
1091b4597226SMel Gorman 
1092b4597226SMel Gorman 	mapping = page_mapping(page);
1093b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
1094b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1095e2be15f6SMel Gorman }
1096e2be15f6SMel Gorman 
1097e286781dSNick Piggin /*
10981742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
10991da177e4SLinus Torvalds  */
11001742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
1101599d0c95SMel Gorman 				      struct pglist_data *pgdat,
1102f84f6e2bSMel Gorman 				      struct scan_control *sc,
110302c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
11043c710c1aSMichal Hocko 				      struct reclaim_stat *stat,
110502c6de8dSMinchan Kim 				      bool force_reclaim)
11061da177e4SLinus Torvalds {
11071da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
1108abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
11093c710c1aSMichal Hocko 	unsigned nr_reclaimed = 0;
1110886cf190SKirill Tkhai 	unsigned pgactivate = 0;
11111da177e4SLinus Torvalds 
1112060f005fSKirill Tkhai 	memset(stat, 0, sizeof(*stat));
11131da177e4SLinus Torvalds 	cond_resched();
11141da177e4SLinus Torvalds 
11151da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
11161da177e4SLinus Torvalds 		struct address_space *mapping;
11171da177e4SLinus Torvalds 		struct page *page;
11181da177e4SLinus Torvalds 		int may_enter_fs;
111902c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
1120e2be15f6SMel Gorman 		bool dirty, writeback;
11211da177e4SLinus Torvalds 
11221da177e4SLinus Torvalds 		cond_resched();
11231da177e4SLinus Torvalds 
11241da177e4SLinus Torvalds 		page = lru_to_page(page_list);
11251da177e4SLinus Torvalds 		list_del(&page->lru);
11261da177e4SLinus Torvalds 
1127529ae9aaSNick Piggin 		if (!trylock_page(page))
11281da177e4SLinus Torvalds 			goto keep;
11291da177e4SLinus Torvalds 
1130309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
11311da177e4SLinus Torvalds 
11321da177e4SLinus Torvalds 		sc->nr_scanned++;
113380e43426SChristoph Lameter 
113439b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
1135ad6b6704SMinchan Kim 			goto activate_locked;
1136894bc310SLee Schermerhorn 
1137a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
113880e43426SChristoph Lameter 			goto keep_locked;
113980e43426SChristoph Lameter 
11401da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
1141802a3a92SShaohua Li 		if ((page_mapped(page) || PageSwapCache(page)) &&
1142802a3a92SShaohua Li 		    !(PageAnon(page) && !PageSwapBacked(page)))
11431da177e4SLinus Torvalds 			sc->nr_scanned++;
11441da177e4SLinus Torvalds 
1145c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1146c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1147c661b078SAndy Whitcroft 
1148e62e384eSMichal Hocko 		/*
1149894befecSAndrey Ryabinin 		 * The number of dirty pages determines if a node is marked
1150e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
1151e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
1152e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
1153e2be15f6SMel Gorman 		 */
1154e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
1155e2be15f6SMel Gorman 		if (dirty || writeback)
1156060f005fSKirill Tkhai 			stat->nr_dirty++;
1157e2be15f6SMel Gorman 
1158e2be15f6SMel Gorman 		if (dirty && !writeback)
1159060f005fSKirill Tkhai 			stat->nr_unqueued_dirty++;
1160e2be15f6SMel Gorman 
1161d04e8acdSMel Gorman 		/*
1162d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
1163d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
1164d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
1165d04e8acdSMel Gorman 		 * end of the LRU a second time.
1166d04e8acdSMel Gorman 		 */
1167e2be15f6SMel Gorman 		mapping = page_mapping(page);
11681da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
1169703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
1170d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
1171060f005fSKirill Tkhai 			stat->nr_congested++;
1172e2be15f6SMel Gorman 
1173e2be15f6SMel Gorman 		/*
1174283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
1175283aba9fSMel Gorman 		 * are three cases to consider.
1176e62e384eSMichal Hocko 		 *
1177283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
1178283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
1179283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
1180283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
1181283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
1182283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
1183283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
1184b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
1185b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
1186c3b94f44SHugh Dickins 		 *
118797c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
1188ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1189ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1190ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
119197c9341fSTejun Heo 		 *    reclaim and continue scanning.
1192283aba9fSMel Gorman 		 *
1193ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1194ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1195283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1196283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1197283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1198283aba9fSMel Gorman 		 *    would probably show more reasons.
1199283aba9fSMel Gorman 		 *
12007fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1201283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1202283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1203283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1204283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1205c55e8d03SJohannes Weiner 		 *
1206c55e8d03SJohannes Weiner 		 * In cases 1) and 2) we activate the pages to get them out of
1207c55e8d03SJohannes Weiner 		 * the way while we continue scanning for clean pages on the
1208c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1209c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1210c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1211c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1212c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1213c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1214e62e384eSMichal Hocko 		 */
1215283aba9fSMel Gorman 		if (PageWriteback(page)) {
1216283aba9fSMel Gorman 			/* Case 1 above */
1217283aba9fSMel Gorman 			if (current_is_kswapd() &&
1218283aba9fSMel Gorman 			    PageReclaim(page) &&
1219599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1220060f005fSKirill Tkhai 				stat->nr_immediate++;
1221c55e8d03SJohannes Weiner 				goto activate_locked;
1222283aba9fSMel Gorman 
1223283aba9fSMel Gorman 			/* Case 2 above */
122497c9341fSTejun Heo 			} else if (sane_reclaim(sc) ||
1225ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1226c3b94f44SHugh Dickins 				/*
1227c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1228c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1229c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1230c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1231c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1232c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1233c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1234c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1235c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1236c3b94f44SHugh Dickins 				 */
1237c3b94f44SHugh Dickins 				SetPageReclaim(page);
1238060f005fSKirill Tkhai 				stat->nr_writeback++;
1239c55e8d03SJohannes Weiner 				goto activate_locked;
1240283aba9fSMel Gorman 
1241283aba9fSMel Gorman 			/* Case 3 above */
1242283aba9fSMel Gorman 			} else {
12437fadc820SHugh Dickins 				unlock_page(page);
1244c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
12457fadc820SHugh Dickins 				/* then go back and try same page again */
12467fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
12477fadc820SHugh Dickins 				continue;
1248e62e384eSMichal Hocko 			}
1249283aba9fSMel Gorman 		}
12501da177e4SLinus Torvalds 
125102c6de8dSMinchan Kim 		if (!force_reclaim)
12526a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
125302c6de8dSMinchan Kim 
1254dfc8d636SJohannes Weiner 		switch (references) {
1255dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
12561da177e4SLinus Torvalds 			goto activate_locked;
125764574746SJohannes Weiner 		case PAGEREF_KEEP:
1258060f005fSKirill Tkhai 			stat->nr_ref_keep++;
125964574746SJohannes Weiner 			goto keep_locked;
1260dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1261dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1262dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1263dfc8d636SJohannes Weiner 		}
12641da177e4SLinus Torvalds 
12651da177e4SLinus Torvalds 		/*
12661da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
12671da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1268802a3a92SShaohua Li 		 * Lazyfree page could be freed directly
12691da177e4SLinus Torvalds 		 */
1270bd4c82c2SHuang Ying 		if (PageAnon(page) && PageSwapBacked(page)) {
1271bd4c82c2SHuang Ying 			if (!PageSwapCache(page)) {
127263eb6b93SHugh Dickins 				if (!(sc->gfp_mask & __GFP_IO))
127363eb6b93SHugh Dickins 					goto keep_locked;
1274747552b1SHuang Ying 				if (PageTransHuge(page)) {
1275b8f593cdSHuang Ying 					/* cannot split THP, skip it */
1276747552b1SHuang Ying 					if (!can_split_huge_page(page, NULL))
1277b8f593cdSHuang Ying 						goto activate_locked;
1278747552b1SHuang Ying 					/*
1279747552b1SHuang Ying 					 * Split pages without a PMD map right
1280747552b1SHuang Ying 					 * away. Chances are some or all of the
1281747552b1SHuang Ying 					 * tail pages can be freed without IO.
1282747552b1SHuang Ying 					 */
1283747552b1SHuang Ying 					if (!compound_mapcount(page) &&
1284bd4c82c2SHuang Ying 					    split_huge_page_to_list(page,
1285bd4c82c2SHuang Ying 								    page_list))
1286747552b1SHuang Ying 						goto activate_locked;
1287747552b1SHuang Ying 				}
12880f074658SMinchan Kim 				if (!add_to_swap(page)) {
12890f074658SMinchan Kim 					if (!PageTransHuge(page))
12901da177e4SLinus Torvalds 						goto activate_locked;
1291bd4c82c2SHuang Ying 					/* Fallback to swap normal pages */
1292bd4c82c2SHuang Ying 					if (split_huge_page_to_list(page,
1293bd4c82c2SHuang Ying 								    page_list))
12940f074658SMinchan Kim 						goto activate_locked;
1295fe490cc0SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1296fe490cc0SHuang Ying 					count_vm_event(THP_SWPOUT_FALLBACK);
1297fe490cc0SHuang Ying #endif
12980f074658SMinchan Kim 					if (!add_to_swap(page))
12990f074658SMinchan Kim 						goto activate_locked;
13000f074658SMinchan Kim 				}
13010f074658SMinchan Kim 
130263eb6b93SHugh Dickins 				may_enter_fs = 1;
13031da177e4SLinus Torvalds 
1304e2be15f6SMel Gorman 				/* Adding to swap updated mapping */
13051da177e4SLinus Torvalds 				mapping = page_mapping(page);
1306bd4c82c2SHuang Ying 			}
13077751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
13087751b2daSKirill A. Shutemov 			/* Split file THP */
13097751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
13107751b2daSKirill A. Shutemov 				goto keep_locked;
1311e2be15f6SMel Gorman 		}
13121da177e4SLinus Torvalds 
13131da177e4SLinus Torvalds 		/*
13141da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
13151da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
13161da177e4SLinus Torvalds 		 */
1317802a3a92SShaohua Li 		if (page_mapped(page)) {
1318bd4c82c2SHuang Ying 			enum ttu_flags flags = ttu_flags | TTU_BATCH_FLUSH;
1319bd4c82c2SHuang Ying 
1320bd4c82c2SHuang Ying 			if (unlikely(PageTransHuge(page)))
1321bd4c82c2SHuang Ying 				flags |= TTU_SPLIT_HUGE_PMD;
1322bd4c82c2SHuang Ying 			if (!try_to_unmap(page, flags)) {
1323060f005fSKirill Tkhai 				stat->nr_unmap_fail++;
13241da177e4SLinus Torvalds 				goto activate_locked;
13251da177e4SLinus Torvalds 			}
13261da177e4SLinus Torvalds 		}
13271da177e4SLinus Torvalds 
13281da177e4SLinus Torvalds 		if (PageDirty(page)) {
1329ee72886dSMel Gorman 			/*
13304eda4823SJohannes Weiner 			 * Only kswapd can writeback filesystem pages
13314eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
13324eda4823SJohannes Weiner 			 * injecting inefficient single-page IO into
13334eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
13344eda4823SJohannes Weiner 			 * write pages when we've encountered many
13354eda4823SJohannes Weiner 			 * dirty pages, and when we've already scanned
13364eda4823SJohannes Weiner 			 * the rest of the LRU for clean pages and see
13374eda4823SJohannes Weiner 			 * the same dirty pages again (PageReclaim).
1338ee72886dSMel Gorman 			 */
1339f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
13404eda4823SJohannes Weiner 			    (!current_is_kswapd() || !PageReclaim(page) ||
1341599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
134249ea7eb6SMel Gorman 				/*
134349ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
134449ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
134549ea7eb6SMel Gorman 				 * except we already have the page isolated
134649ea7eb6SMel Gorman 				 * and know it's dirty
134749ea7eb6SMel Gorman 				 */
1348c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
134949ea7eb6SMel Gorman 				SetPageReclaim(page);
135049ea7eb6SMel Gorman 
1351c55e8d03SJohannes Weiner 				goto activate_locked;
1352ee72886dSMel Gorman 			}
1353ee72886dSMel Gorman 
1354dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
13551da177e4SLinus Torvalds 				goto keep_locked;
13564dd4b920SAndrew Morton 			if (!may_enter_fs)
13571da177e4SLinus Torvalds 				goto keep_locked;
135852a8363eSChristoph Lameter 			if (!sc->may_writepage)
13591da177e4SLinus Torvalds 				goto keep_locked;
13601da177e4SLinus Torvalds 
1361d950c947SMel Gorman 			/*
1362d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1363d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1364d950c947SMel Gorman 			 * starts and then write it out here.
1365d950c947SMel Gorman 			 */
1366d950c947SMel Gorman 			try_to_unmap_flush_dirty();
13677d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
13681da177e4SLinus Torvalds 			case PAGE_KEEP:
13691da177e4SLinus Torvalds 				goto keep_locked;
13701da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
13711da177e4SLinus Torvalds 				goto activate_locked;
13721da177e4SLinus Torvalds 			case PAGE_SUCCESS:
13737d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
137441ac1999SMel Gorman 					goto keep;
13757d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
13761da177e4SLinus Torvalds 					goto keep;
13777d3579e8SKOSAKI Motohiro 
13781da177e4SLinus Torvalds 				/*
13791da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
13801da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
13811da177e4SLinus Torvalds 				 */
1382529ae9aaSNick Piggin 				if (!trylock_page(page))
13831da177e4SLinus Torvalds 					goto keep;
13841da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
13851da177e4SLinus Torvalds 					goto keep_locked;
13861da177e4SLinus Torvalds 				mapping = page_mapping(page);
13871da177e4SLinus Torvalds 			case PAGE_CLEAN:
13881da177e4SLinus Torvalds 				; /* try to free the page below */
13891da177e4SLinus Torvalds 			}
13901da177e4SLinus Torvalds 		}
13911da177e4SLinus Torvalds 
13921da177e4SLinus Torvalds 		/*
13931da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
13941da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
13951da177e4SLinus Torvalds 		 * the page as well.
13961da177e4SLinus Torvalds 		 *
13971da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
13981da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
13991da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
14001da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
14011da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
14021da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
14031da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
14041da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
14051da177e4SLinus Torvalds 		 *
14061da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
14071da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
14081da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
14091da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
14101da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
14111da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
14121da177e4SLinus Torvalds 		 */
1413266cf658SDavid Howells 		if (page_has_private(page)) {
14141da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
14151da177e4SLinus Torvalds 				goto activate_locked;
1416e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1417e286781dSNick Piggin 				unlock_page(page);
1418e286781dSNick Piggin 				if (put_page_testzero(page))
14191da177e4SLinus Torvalds 					goto free_it;
1420e286781dSNick Piggin 				else {
1421e286781dSNick Piggin 					/*
1422e286781dSNick Piggin 					 * rare race with speculative reference.
1423e286781dSNick Piggin 					 * the speculative reference will free
1424e286781dSNick Piggin 					 * this page shortly, so we may
1425e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1426e286781dSNick Piggin 					 * leave it off the LRU).
1427e286781dSNick Piggin 					 */
1428e286781dSNick Piggin 					nr_reclaimed++;
1429e286781dSNick Piggin 					continue;
1430e286781dSNick Piggin 				}
1431e286781dSNick Piggin 			}
14321da177e4SLinus Torvalds 		}
14331da177e4SLinus Torvalds 
1434802a3a92SShaohua Li 		if (PageAnon(page) && !PageSwapBacked(page)) {
1435802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
1436802a3a92SShaohua Li 			if (!page_ref_freeze(page, 1))
143749d2e9ccSChristoph Lameter 				goto keep_locked;
1438802a3a92SShaohua Li 			if (PageDirty(page)) {
1439802a3a92SShaohua Li 				page_ref_unfreeze(page, 1);
1440802a3a92SShaohua Li 				goto keep_locked;
1441802a3a92SShaohua Li 			}
14421da177e4SLinus Torvalds 
1443802a3a92SShaohua Li 			count_vm_event(PGLAZYFREED);
14442262185cSRoman Gushchin 			count_memcg_page_event(page, PGLAZYFREED);
1445802a3a92SShaohua Li 		} else if (!mapping || !__remove_mapping(mapping, page, true))
1446802a3a92SShaohua Li 			goto keep_locked;
14479a1ea439SHugh Dickins 
14489a1ea439SHugh Dickins 		unlock_page(page);
1449e286781dSNick Piggin free_it:
145005ff5137SAndrew Morton 		nr_reclaimed++;
1451abe4c3b5SMel Gorman 
1452abe4c3b5SMel Gorman 		/*
1453abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1454abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1455abe4c3b5SMel Gorman 		 */
1456bd4c82c2SHuang Ying 		if (unlikely(PageTransHuge(page))) {
1457bd4c82c2SHuang Ying 			mem_cgroup_uncharge(page);
1458bd4c82c2SHuang Ying 			(*get_compound_page_dtor(page))(page);
1459bd4c82c2SHuang Ying 		} else
1460abe4c3b5SMel Gorman 			list_add(&page->lru, &free_pages);
14611da177e4SLinus Torvalds 		continue;
14621da177e4SLinus Torvalds 
14631da177e4SLinus Torvalds activate_locked:
146468a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
1465ad6b6704SMinchan Kim 		if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1466ad6b6704SMinchan Kim 						PageMlocked(page)))
1467a2c43eedSHugh Dickins 			try_to_free_swap(page);
1468309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
1469ad6b6704SMinchan Kim 		if (!PageMlocked(page)) {
1470886cf190SKirill Tkhai 			int type = page_is_file_cache(page);
14711da177e4SLinus Torvalds 			SetPageActive(page);
1472886cf190SKirill Tkhai 			pgactivate++;
1473886cf190SKirill Tkhai 			stat->nr_activate[type] += hpage_nr_pages(page);
14742262185cSRoman Gushchin 			count_memcg_page_event(page, PGACTIVATE);
1475ad6b6704SMinchan Kim 		}
14761da177e4SLinus Torvalds keep_locked:
14771da177e4SLinus Torvalds 		unlock_page(page);
14781da177e4SLinus Torvalds keep:
14791da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1480309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
14811da177e4SLinus Torvalds 	}
1482abe4c3b5SMel Gorman 
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 
149302c6de8dSMinchan Kim unsigned long 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 	};
1501060f005fSKirill Tkhai 	struct reclaim_stat dummy_stat;
15023c710c1aSMichal Hocko 	unsigned long ret;
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) {
1507117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1508b1123ea6SMinchan Kim 		    !__PageMovable(page)) {
150902c6de8dSMinchan Kim 			ClearPageActive(page);
151002c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
151102c6de8dSMinchan Kim 		}
151202c6de8dSMinchan Kim 	}
151302c6de8dSMinchan Kim 
1514599d0c95SMel Gorman 	ret = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1515060f005fSKirill Tkhai 			TTU_IGNORE_ACCESS, &dummy_stat, true);
151602c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
1517599d0c95SMel Gorman 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
151802c6de8dSMinchan Kim 	return ret;
151902c6de8dSMinchan Kim }
152002c6de8dSMinchan Kim 
15215ad333ebSAndy Whitcroft /*
15225ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
15235ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
15245ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
15255ad333ebSAndy Whitcroft  *
15265ad333ebSAndy Whitcroft  * page:	page to consider
15275ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
15285ad333ebSAndy Whitcroft  *
15295ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
15305ad333ebSAndy Whitcroft  */
1531f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
15325ad333ebSAndy Whitcroft {
15335ad333ebSAndy Whitcroft 	int ret = -EINVAL;
15345ad333ebSAndy Whitcroft 
15355ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
15365ad333ebSAndy Whitcroft 	if (!PageLRU(page))
15375ad333ebSAndy Whitcroft 		return ret;
15385ad333ebSAndy Whitcroft 
1539e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1540e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1541894bc310SLee Schermerhorn 		return ret;
1542894bc310SLee Schermerhorn 
15435ad333ebSAndy Whitcroft 	ret = -EBUSY;
154408e552c6SKAMEZAWA Hiroyuki 
1545c8244935SMel Gorman 	/*
1546c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1547c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1548c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1549c8244935SMel Gorman 	 *
1550c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1551c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1552c8244935SMel Gorman 	 */
15531276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1554c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1555c8244935SMel Gorman 		if (PageWriteback(page))
155639deaf85SMinchan Kim 			return ret;
155739deaf85SMinchan Kim 
1558c8244935SMel Gorman 		if (PageDirty(page)) {
1559c8244935SMel Gorman 			struct address_space *mapping;
156069d763fcSMel Gorman 			bool migrate_dirty;
1561c8244935SMel Gorman 
1562c8244935SMel Gorman 			/*
1563c8244935SMel Gorman 			 * Only pages without mappings or that have a
1564c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
156569d763fcSMel Gorman 			 * without blocking. However, we can be racing with
156669d763fcSMel Gorman 			 * truncation so it's necessary to lock the page
156769d763fcSMel Gorman 			 * to stabilise the mapping as truncation holds
156869d763fcSMel Gorman 			 * the page lock until after the page is removed
156969d763fcSMel Gorman 			 * from the page cache.
1570c8244935SMel Gorman 			 */
157169d763fcSMel Gorman 			if (!trylock_page(page))
157269d763fcSMel Gorman 				return ret;
157369d763fcSMel Gorman 
1574c8244935SMel Gorman 			mapping = page_mapping(page);
1575145e1a71SHugh Dickins 			migrate_dirty = !mapping || mapping->a_ops->migratepage;
157669d763fcSMel Gorman 			unlock_page(page);
157769d763fcSMel Gorman 			if (!migrate_dirty)
1578c8244935SMel Gorman 				return ret;
1579c8244935SMel Gorman 		}
1580c8244935SMel Gorman 	}
1581c8244935SMel Gorman 
1582f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1583f80c0673SMinchan Kim 		return ret;
1584f80c0673SMinchan Kim 
15855ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
15865ad333ebSAndy Whitcroft 		/*
15875ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
15885ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
15895ad333ebSAndy Whitcroft 		 * page release code relies on it.
15905ad333ebSAndy Whitcroft 		 */
15915ad333ebSAndy Whitcroft 		ClearPageLRU(page);
15925ad333ebSAndy Whitcroft 		ret = 0;
15935ad333ebSAndy Whitcroft 	}
15945ad333ebSAndy Whitcroft 
15955ad333ebSAndy Whitcroft 	return ret;
15965ad333ebSAndy Whitcroft }
15975ad333ebSAndy Whitcroft 
15987ee36a14SMel Gorman 
15997ee36a14SMel Gorman /*
16007ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
16017ee36a14SMel Gorman  * be complete before mem_cgroup_update_lru_size due to a santity check.
16027ee36a14SMel Gorman  */
16037ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1604b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
16057ee36a14SMel Gorman {
16067ee36a14SMel Gorman 	int zid;
16077ee36a14SMel Gorman 
16087ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
16097ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
16107ee36a14SMel Gorman 			continue;
16117ee36a14SMel Gorman 
16127ee36a14SMel Gorman 		__update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1613b4536f0cSMichal Hocko #ifdef CONFIG_MEMCG
1614b4536f0cSMichal Hocko 		mem_cgroup_update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1615b4536f0cSMichal Hocko #endif
16167ee36a14SMel Gorman 	}
16177ee36a14SMel Gorman 
16187ee36a14SMel Gorman }
16197ee36a14SMel Gorman 
1620f4b7e272SAndrey Ryabinin /**
1621f4b7e272SAndrey Ryabinin  * pgdat->lru_lock is heavily contended.  Some of the functions that
16221da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
16231da177e4SLinus Torvalds  * and working on them outside the LRU lock.
16241da177e4SLinus Torvalds  *
16251da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
16261da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
16271da177e4SLinus Torvalds  *
16281da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
16291da177e4SLinus Torvalds  *
1630791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
16315dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
16321da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1633f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1634fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
16355ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
16363cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
16371da177e4SLinus Torvalds  *
16381da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
16391da177e4SLinus Torvalds  */
164069e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
16415dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1642fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
1643a9e7c39fSKirill Tkhai 		enum lru_list lru)
16441da177e4SLinus Torvalds {
164575b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
164669e05944SAndrew Morton 	unsigned long nr_taken = 0;
1647599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
16487cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
16493db65812SJohannes Weiner 	unsigned long skipped = 0;
1650791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
1651b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
1652a9e7c39fSKirill Tkhai 	isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
16531da177e4SLinus Torvalds 
1654791b48b6SMinchan Kim 	scan = 0;
1655791b48b6SMinchan Kim 	for (total_scan = 0;
1656791b48b6SMinchan Kim 	     scan < nr_to_scan && nr_taken < nr_to_scan && !list_empty(src);
1657791b48b6SMinchan Kim 	     total_scan++) {
16585ad333ebSAndy Whitcroft 		struct page *page;
16595ad333ebSAndy Whitcroft 
16601da177e4SLinus Torvalds 		page = lru_to_page(src);
16611da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
16621da177e4SLinus Torvalds 
1663309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
16648d438f96SNick Piggin 
1665b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1666b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
16677cc30fcfSMel Gorman 			nr_skipped[page_zonenum(page)]++;
1668b2e18757SMel Gorman 			continue;
1669b2e18757SMel Gorman 		}
1670b2e18757SMel Gorman 
1671791b48b6SMinchan Kim 		/*
1672791b48b6SMinchan Kim 		 * Do not count skipped pages because that makes the function
1673791b48b6SMinchan Kim 		 * return with no isolated pages if the LRU mostly contains
1674791b48b6SMinchan Kim 		 * ineligible pages.  This causes the VM to not reclaim any
1675791b48b6SMinchan Kim 		 * pages, triggering a premature OOM.
1676791b48b6SMinchan Kim 		 */
1677791b48b6SMinchan Kim 		scan++;
1678f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
16795ad333ebSAndy Whitcroft 		case 0:
1680599d0c95SMel Gorman 			nr_pages = hpage_nr_pages(page);
1681599d0c95SMel Gorman 			nr_taken += nr_pages;
1682599d0c95SMel Gorman 			nr_zone_taken[page_zonenum(page)] += nr_pages;
16835ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
16845ad333ebSAndy Whitcroft 			break;
16857c8ee9a8SNick Piggin 
16865ad333ebSAndy Whitcroft 		case -EBUSY:
16875ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
16885ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
16895ad333ebSAndy Whitcroft 			continue;
16905ad333ebSAndy Whitcroft 
16915ad333ebSAndy Whitcroft 		default:
16925ad333ebSAndy Whitcroft 			BUG();
16935ad333ebSAndy Whitcroft 		}
16945ad333ebSAndy Whitcroft 	}
16951da177e4SLinus Torvalds 
1696b2e18757SMel Gorman 	/*
1697b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1698b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1699b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1700b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1701b2e18757SMel Gorman 	 * system at risk of premature OOM.
1702b2e18757SMel Gorman 	 */
17037cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
17047cc30fcfSMel Gorman 		int zid;
17057cc30fcfSMel Gorman 
17063db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
17077cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
17087cc30fcfSMel Gorman 			if (!nr_skipped[zid])
17097cc30fcfSMel Gorman 				continue;
17107cc30fcfSMel Gorman 
17117cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
17121265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
17137cc30fcfSMel Gorman 		}
17147cc30fcfSMel Gorman 	}
1715791b48b6SMinchan Kim 	*nr_scanned = total_scan;
17161265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1717791b48b6SMinchan Kim 				    total_scan, skipped, nr_taken, mode, lru);
1718b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
17191da177e4SLinus Torvalds 	return nr_taken;
17201da177e4SLinus Torvalds }
17211da177e4SLinus Torvalds 
172262695a84SNick Piggin /**
172362695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
172462695a84SNick Piggin  * @page: page to isolate from its LRU list
172562695a84SNick Piggin  *
172662695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
172762695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
172862695a84SNick Piggin  *
172962695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
173062695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
173162695a84SNick Piggin  *
173262695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1733894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1734894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1735894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
173662695a84SNick Piggin  *
173762695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
173862695a84SNick Piggin  * found will be decremented.
173962695a84SNick Piggin  *
174062695a84SNick Piggin  * Restrictions:
1741a5d09bedSMike Rapoport  *
174262695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
174362695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
174462695a84SNick Piggin  *     without a stable reference).
174562695a84SNick Piggin  * (2) the lru_lock must not be held.
174662695a84SNick Piggin  * (3) interrupts must be enabled.
174762695a84SNick Piggin  */
174862695a84SNick Piggin int isolate_lru_page(struct page *page)
174962695a84SNick Piggin {
175062695a84SNick Piggin 	int ret = -EBUSY;
175162695a84SNick Piggin 
1752309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1753cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
17540c917313SKonstantin Khlebnikov 
175562695a84SNick Piggin 	if (PageLRU(page)) {
1756f4b7e272SAndrey Ryabinin 		pg_data_t *pgdat = page_pgdat(page);
1757fa9add64SHugh Dickins 		struct lruvec *lruvec;
175862695a84SNick Piggin 
1759f4b7e272SAndrey Ryabinin 		spin_lock_irq(&pgdat->lru_lock);
1760f4b7e272SAndrey Ryabinin 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
17610c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1762894bc310SLee Schermerhorn 			int lru = page_lru(page);
17630c917313SKonstantin Khlebnikov 			get_page(page);
176462695a84SNick Piggin 			ClearPageLRU(page);
1765fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1766fa9add64SHugh Dickins 			ret = 0;
176762695a84SNick Piggin 		}
1768f4b7e272SAndrey Ryabinin 		spin_unlock_irq(&pgdat->lru_lock);
176962695a84SNick Piggin 	}
177062695a84SNick Piggin 	return ret;
177162695a84SNick Piggin }
177262695a84SNick Piggin 
17735ad333ebSAndy Whitcroft /*
1774d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1775d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1776d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1777d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1778d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
177935cd7815SRik van Riel  */
1780599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
178135cd7815SRik van Riel 		struct scan_control *sc)
178235cd7815SRik van Riel {
178335cd7815SRik van Riel 	unsigned long inactive, isolated;
178435cd7815SRik van Riel 
178535cd7815SRik van Riel 	if (current_is_kswapd())
178635cd7815SRik van Riel 		return 0;
178735cd7815SRik van Riel 
178897c9341fSTejun Heo 	if (!sane_reclaim(sc))
178935cd7815SRik van Riel 		return 0;
179035cd7815SRik van Riel 
179135cd7815SRik van Riel 	if (file) {
1792599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1793599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
179435cd7815SRik van Riel 	} else {
1795599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1796599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
179735cd7815SRik van Riel 	}
179835cd7815SRik van Riel 
17993cf23841SFengguang Wu 	/*
18003cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
18013cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
18023cf23841SFengguang Wu 	 * deadlock.
18033cf23841SFengguang Wu 	 */
1804d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
18053cf23841SFengguang Wu 		inactive >>= 3;
18063cf23841SFengguang Wu 
180735cd7815SRik van Riel 	return isolated > inactive;
180835cd7815SRik van Riel }
180935cd7815SRik van Riel 
1810a222f341SKirill Tkhai /*
1811a222f341SKirill Tkhai  * This moves pages from @list to corresponding LRU list.
1812a222f341SKirill Tkhai  *
1813a222f341SKirill Tkhai  * We move them the other way if the page is referenced by one or more
1814a222f341SKirill Tkhai  * processes, from rmap.
1815a222f341SKirill Tkhai  *
1816a222f341SKirill Tkhai  * If the pages are mostly unmapped, the processing is fast and it is
1817a222f341SKirill Tkhai  * appropriate to hold zone_lru_lock across the whole operation.  But if
1818a222f341SKirill Tkhai  * the pages are mapped, the processing is slow (page_referenced()) so we
1819a222f341SKirill Tkhai  * should drop zone_lru_lock around each page.  It's impossible to balance
1820a222f341SKirill Tkhai  * this, so instead we remove the pages from the LRU while processing them.
1821a222f341SKirill Tkhai  * It is safe to rely on PG_active against the non-LRU pages in here because
1822a222f341SKirill Tkhai  * nobody will play with that bit on a non-LRU page.
1823a222f341SKirill Tkhai  *
1824a222f341SKirill Tkhai  * The downside is that we have to touch page->_refcount against each page.
1825a222f341SKirill Tkhai  * But we had to alter page->flags anyway.
1826a222f341SKirill Tkhai  *
1827a222f341SKirill Tkhai  * Returns the number of pages moved to the given lruvec.
1828a222f341SKirill Tkhai  */
1829a222f341SKirill Tkhai 
1830a222f341SKirill Tkhai static unsigned noinline_for_stack move_pages_to_lru(struct lruvec *lruvec,
1831a222f341SKirill Tkhai 						     struct list_head *list)
183266635629SMel Gorman {
1833599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
1834a222f341SKirill Tkhai 	int nr_pages, nr_moved = 0;
18353f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
1836a222f341SKirill Tkhai 	struct page *page;
1837a222f341SKirill Tkhai 	enum lru_list lru;
183866635629SMel Gorman 
1839a222f341SKirill Tkhai 	while (!list_empty(list)) {
1840a222f341SKirill Tkhai 		page = lru_to_page(list);
1841309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
184239b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1843a222f341SKirill Tkhai 			list_del(&page->lru);
1844599d0c95SMel Gorman 			spin_unlock_irq(&pgdat->lru_lock);
184566635629SMel Gorman 			putback_lru_page(page);
1846599d0c95SMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
184766635629SMel Gorman 			continue;
184866635629SMel Gorman 		}
1849599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
1850fa9add64SHugh Dickins 
18517a608572SLinus Torvalds 		SetPageLRU(page);
185266635629SMel Gorman 		lru = page_lru(page);
1853a222f341SKirill Tkhai 
1854a222f341SKirill Tkhai 		nr_pages = hpage_nr_pages(page);
1855a222f341SKirill Tkhai 		update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
1856a222f341SKirill Tkhai 		list_move(&page->lru, &lruvec->lists[lru]);
1857fa9add64SHugh Dickins 
18582bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
18592bcf8879SHugh Dickins 			__ClearPageLRU(page);
18602bcf8879SHugh Dickins 			__ClearPageActive(page);
1861fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
18622bcf8879SHugh Dickins 
18632bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1864599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1865747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
18662bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1867599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
18682bcf8879SHugh Dickins 			} else
18692bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
1870a222f341SKirill Tkhai 		} else {
1871a222f341SKirill Tkhai 			nr_moved += nr_pages;
187266635629SMel Gorman 		}
187366635629SMel Gorman 	}
187466635629SMel Gorman 
18753f79768fSHugh Dickins 	/*
18763f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
18773f79768fSHugh Dickins 	 */
1878a222f341SKirill Tkhai 	list_splice(&pages_to_free, list);
1879a222f341SKirill Tkhai 
1880a222f341SKirill Tkhai 	return nr_moved;
188166635629SMel Gorman }
188266635629SMel Gorman 
188366635629SMel Gorman /*
1884399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1885399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1886399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1887399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1888399ba0b9SNeilBrown  */
1889399ba0b9SNeilBrown static int current_may_throttle(void)
1890399ba0b9SNeilBrown {
1891399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1892399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1893399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1894399ba0b9SNeilBrown }
1895399ba0b9SNeilBrown 
1896399ba0b9SNeilBrown /*
1897b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
18981742f19fSAndrew Morton  * of reclaimed pages
18991da177e4SLinus Torvalds  */
190066635629SMel Gorman static noinline_for_stack unsigned long
19011a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
19029e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
19031da177e4SLinus Torvalds {
19041da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1905e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
190605ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1907e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
1908060f005fSKirill Tkhai 	struct reclaim_stat stat;
19093cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1910f46b7912SKirill Tkhai 	enum vm_event_item item;
1911599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
19121a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1913db73ee0dSMichal Hocko 	bool stalled = false;
191478dc583dSKOSAKI Motohiro 
1915599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
1916db73ee0dSMichal Hocko 		if (stalled)
1917db73ee0dSMichal Hocko 			return 0;
1918db73ee0dSMichal Hocko 
1919db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
1920db73ee0dSMichal Hocko 		msleep(100);
1921db73ee0dSMichal Hocko 		stalled = true;
192235cd7815SRik van Riel 
192335cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
192435cd7815SRik van Riel 		if (fatal_signal_pending(current))
192535cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
192635cd7815SRik van Riel 	}
192735cd7815SRik van Riel 
19281da177e4SLinus Torvalds 	lru_add_drain();
1929f80c0673SMinchan Kim 
1930599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19311da177e4SLinus Torvalds 
19325dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
1933a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
193495d918fcSKonstantin Khlebnikov 
1935599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
19369d5e6a9fSHugh Dickins 	reclaim_stat->recent_scanned[file] += nr_taken;
193795d918fcSKonstantin Khlebnikov 
1938f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
19392262185cSRoman Gushchin 	if (global_reclaim(sc))
1940f46b7912SKirill Tkhai 		__count_vm_events(item, nr_scanned);
1941f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
1942599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
1943d563c050SHillf Danton 
1944d563c050SHillf Danton 	if (nr_taken == 0)
194566635629SMel Gorman 		return 0;
1946b35ea17bSKOSAKI Motohiro 
1947a128ca71SShaohua Li 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, 0,
19483c710c1aSMichal Hocko 				&stat, false);
1949c661b078SAndy Whitcroft 
1950599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19513f79768fSHugh Dickins 
1952f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
19532262185cSRoman Gushchin 	if (global_reclaim(sc))
1954f46b7912SKirill Tkhai 		__count_vm_events(item, nr_reclaimed);
1955f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
1956*b17f18afSKirill Tkhai 	reclaim_stat->recent_rotated[0] += stat.nr_activate[0];
1957*b17f18afSKirill Tkhai 	reclaim_stat->recent_rotated[1] += stat.nr_activate[1];
1958a74609faSNick Piggin 
1959a222f341SKirill Tkhai 	move_pages_to_lru(lruvec, &page_list);
19603f79768fSHugh Dickins 
1961599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
19623f79768fSHugh Dickins 
1963599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19643f79768fSHugh Dickins 
1965747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
19662d4894b5SMel Gorman 	free_unref_page_list(&page_list);
1967e11da5b4SMel Gorman 
196892df3a72SMel Gorman 	/*
19691c610d5fSAndrey Ryabinin 	 * If dirty pages are scanned that are not queued for IO, it
19701c610d5fSAndrey Ryabinin 	 * implies that flushers are not doing their job. This can
19711c610d5fSAndrey Ryabinin 	 * happen when memory pressure pushes dirty pages to the end of
19721c610d5fSAndrey Ryabinin 	 * the LRU before the dirty limits are breached and the dirty
19731c610d5fSAndrey Ryabinin 	 * data has expired. It can also happen when the proportion of
19741c610d5fSAndrey Ryabinin 	 * dirty pages grows not through writes but through memory
19751c610d5fSAndrey Ryabinin 	 * pressure reclaiming all the clean cache. And in some cases,
19761c610d5fSAndrey Ryabinin 	 * the flushers simply cannot keep up with the allocation
19771c610d5fSAndrey Ryabinin 	 * rate. Nudge the flusher threads in case they are asleep.
19781c610d5fSAndrey Ryabinin 	 */
19791c610d5fSAndrey Ryabinin 	if (stat.nr_unqueued_dirty == nr_taken)
19801c610d5fSAndrey Ryabinin 		wakeup_flusher_threads(WB_REASON_VMSCAN);
19811c610d5fSAndrey Ryabinin 
1982d108c772SAndrey Ryabinin 	sc->nr.dirty += stat.nr_dirty;
1983d108c772SAndrey Ryabinin 	sc->nr.congested += stat.nr_congested;
1984d108c772SAndrey Ryabinin 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
1985d108c772SAndrey Ryabinin 	sc->nr.writeback += stat.nr_writeback;
1986d108c772SAndrey Ryabinin 	sc->nr.immediate += stat.nr_immediate;
1987d108c772SAndrey Ryabinin 	sc->nr.taken += nr_taken;
1988d108c772SAndrey Ryabinin 	if (file)
1989d108c772SAndrey Ryabinin 		sc->nr.file_taken += nr_taken;
19908e950282SMel Gorman 
1991599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
1992d51d1e64SSteven Rostedt 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
199305ff5137SAndrew Morton 	return nr_reclaimed;
19941da177e4SLinus Torvalds }
19951da177e4SLinus Torvalds 
1996f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
19971a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1998f16015fbSJohannes Weiner 			       struct scan_control *sc,
19999e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
20001cfb419bSKAMEZAWA Hiroyuki {
200144c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
2002f626012dSHugh Dickins 	unsigned long nr_scanned;
20036fe6b7e3SWu Fengguang 	unsigned long vm_flags;
20041cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
20058cab4754SWu Fengguang 	LIST_HEAD(l_active);
2006b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
20071cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
20081a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
20099d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
20109d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
20113cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
2012599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
20131cfb419bSKAMEZAWA Hiroyuki 
20141da177e4SLinus Torvalds 	lru_add_drain();
2015f80c0673SMinchan Kim 
2016599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
2017925b7673SJohannes Weiner 
20185dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2019a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
202089b5fae5SJohannes Weiner 
2021599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2022b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
20231cfb419bSKAMEZAWA Hiroyuki 
2024599d0c95SMel Gorman 	__count_vm_events(PGREFILL, nr_scanned);
20252fa2690cSYafang Shao 	__count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
20269d5e6a9fSHugh Dickins 
2027599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
20281da177e4SLinus Torvalds 
20291da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
20301da177e4SLinus Torvalds 		cond_resched();
20311da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
20321da177e4SLinus Torvalds 		list_del(&page->lru);
20337e9cd484SRik van Riel 
203439b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
2035894bc310SLee Schermerhorn 			putback_lru_page(page);
2036894bc310SLee Schermerhorn 			continue;
2037894bc310SLee Schermerhorn 		}
2038894bc310SLee Schermerhorn 
2039cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
2040cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
2041cc715d99SMel Gorman 				if (page_has_private(page))
2042cc715d99SMel Gorman 					try_to_release_page(page, 0);
2043cc715d99SMel Gorman 				unlock_page(page);
2044cc715d99SMel Gorman 			}
2045cc715d99SMel Gorman 		}
2046cc715d99SMel Gorman 
2047c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
2048c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
20499992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
20508cab4754SWu Fengguang 			/*
20518cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
20528cab4754SWu Fengguang 			 * give them one more trip around the active list. So
20538cab4754SWu Fengguang 			 * that executable code get better chances to stay in
20548cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
20558cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
20568cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
20578cab4754SWu Fengguang 			 * so we ignore them here.
20588cab4754SWu Fengguang 			 */
205941e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
20608cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
20618cab4754SWu Fengguang 				continue;
20628cab4754SWu Fengguang 			}
20638cab4754SWu Fengguang 		}
20647e9cd484SRik van Riel 
20655205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
20661899ad18SJohannes Weiner 		SetPageWorkingset(page);
20671da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
20681da177e4SLinus Torvalds 	}
20691da177e4SLinus Torvalds 
2070b555749aSAndrew Morton 	/*
20718cab4754SWu Fengguang 	 * Move pages back to the lru list.
2072b555749aSAndrew Morton 	 */
2073599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
20744f98a2feSRik van Riel 	/*
20758cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
20768cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
20778cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
20787c0db9e9SJerome Marchand 	 * get_scan_count.
2079556adecbSRik van Riel 	 */
2080b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
2081556adecbSRik van Riel 
2082a222f341SKirill Tkhai 	nr_activate = move_pages_to_lru(lruvec, &l_active);
2083a222f341SKirill Tkhai 	nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2084f372d89eSKirill Tkhai 	/* Keep all free pages in l_active list */
2085f372d89eSKirill Tkhai 	list_splice(&l_inactive, &l_active);
20869851ac13SKirill Tkhai 
20879851ac13SKirill Tkhai 	__count_vm_events(PGDEACTIVATE, nr_deactivate);
20889851ac13SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
20899851ac13SKirill Tkhai 
2090599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2091599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
20922bcf8879SHugh Dickins 
2093f372d89eSKirill Tkhai 	mem_cgroup_uncharge_list(&l_active);
2094f372d89eSKirill Tkhai 	free_unref_page_list(&l_active);
20959d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
20969d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
20971da177e4SLinus Torvalds }
20981da177e4SLinus Torvalds 
209959dc76b0SRik van Riel /*
210059dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
210159dc76b0SRik van Riel  * to do too much work.
210214797e23SKOSAKI Motohiro  *
210359dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
210459dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
210559dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
210659dc76b0SRik van Riel  *
210759dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
210859dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
210959dc76b0SRik van Riel  *
21102a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
21112a2e4885SJohannes Weiner  *
211259dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
21133a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
211459dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
211559dc76b0SRik van Riel  *
211659dc76b0SRik van Riel  * total     target    max
211759dc76b0SRik van Riel  * memory    ratio     inactive
211859dc76b0SRik van Riel  * -------------------------------------
211959dc76b0SRik van Riel  *   10MB       1         5MB
212059dc76b0SRik van Riel  *  100MB       1        50MB
212159dc76b0SRik van Riel  *    1GB       3       250MB
212259dc76b0SRik van Riel  *   10GB      10       0.9GB
212359dc76b0SRik van Riel  *  100GB      31         3GB
212459dc76b0SRik van Riel  *    1TB     101        10GB
212559dc76b0SRik van Riel  *   10TB     320        32GB
212614797e23SKOSAKI Motohiro  */
2127f8d1a311SMel Gorman static bool inactive_list_is_low(struct lruvec *lruvec, bool file,
21282a2e4885SJohannes Weiner 				 struct scan_control *sc, bool actual_reclaim)
212914797e23SKOSAKI Motohiro {
2130fd538803SMichal Hocko 	enum lru_list active_lru = file * LRU_FILE + LRU_ACTIVE;
21312a2e4885SJohannes Weiner 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
21322a2e4885SJohannes Weiner 	enum lru_list inactive_lru = file * LRU_FILE;
21332a2e4885SJohannes Weiner 	unsigned long inactive, active;
21342a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
21352a2e4885SJohannes Weiner 	unsigned long refaults;
213659dc76b0SRik van Riel 	unsigned long gb;
213759dc76b0SRik van Riel 
213874e3f3c3SMinchan Kim 	/*
213974e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
214074e3f3c3SMinchan Kim 	 * is pointless.
214174e3f3c3SMinchan Kim 	 */
214259dc76b0SRik van Riel 	if (!file && !total_swap_pages)
214342e2e457SYaowei Bai 		return false;
214474e3f3c3SMinchan Kim 
2145fd538803SMichal Hocko 	inactive = lruvec_lru_size(lruvec, inactive_lru, sc->reclaim_idx);
2146fd538803SMichal Hocko 	active = lruvec_lru_size(lruvec, active_lru, sc->reclaim_idx);
2147f8d1a311SMel Gorman 
21482a2e4885SJohannes Weiner 	/*
21492a2e4885SJohannes Weiner 	 * When refaults are being observed, it means a new workingset
21502a2e4885SJohannes Weiner 	 * is being established. Disable active list protection to get
21512a2e4885SJohannes Weiner 	 * rid of the stale workingset quickly.
21522a2e4885SJohannes Weiner 	 */
2153205b20ccSJohannes Weiner 	refaults = lruvec_page_state_local(lruvec, WORKINGSET_ACTIVATE);
21542a2e4885SJohannes Weiner 	if (file && actual_reclaim && lruvec->refaults != refaults) {
21552a2e4885SJohannes Weiner 		inactive_ratio = 0;
21562a2e4885SJohannes Weiner 	} else {
215759dc76b0SRik van Riel 		gb = (inactive + active) >> (30 - PAGE_SHIFT);
215859dc76b0SRik van Riel 		if (gb)
215959dc76b0SRik van Riel 			inactive_ratio = int_sqrt(10 * gb);
2160b39415b2SRik van Riel 		else
216159dc76b0SRik van Riel 			inactive_ratio = 1;
21622a2e4885SJohannes Weiner 	}
216359dc76b0SRik van Riel 
21642a2e4885SJohannes Weiner 	if (actual_reclaim)
21652a2e4885SJohannes Weiner 		trace_mm_vmscan_inactive_list_is_low(pgdat->node_id, sc->reclaim_idx,
2166fd538803SMichal Hocko 			lruvec_lru_size(lruvec, inactive_lru, MAX_NR_ZONES), inactive,
2167fd538803SMichal Hocko 			lruvec_lru_size(lruvec, active_lru, MAX_NR_ZONES), active,
2168fd538803SMichal Hocko 			inactive_ratio, file);
2169fd538803SMichal Hocko 
217059dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2171b39415b2SRik van Riel }
2172b39415b2SRik van Riel 
21734f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
21743b991208SJohannes Weiner 				 struct lruvec *lruvec, struct scan_control *sc)
2175b69408e8SChristoph Lameter {
2176b39415b2SRik van Riel 	if (is_active_lru(lru)) {
21773b991208SJohannes Weiner 		if (inactive_list_is_low(lruvec, is_file_lru(lru), sc, true))
21781a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2179556adecbSRik van Riel 		return 0;
2180556adecbSRik van Riel 	}
2181556adecbSRik van Riel 
21821a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2183b69408e8SChristoph Lameter }
2184b69408e8SChristoph Lameter 
21859a265114SJohannes Weiner enum scan_balance {
21869a265114SJohannes Weiner 	SCAN_EQUAL,
21879a265114SJohannes Weiner 	SCAN_FRACT,
21889a265114SJohannes Weiner 	SCAN_ANON,
21899a265114SJohannes Weiner 	SCAN_FILE,
21909a265114SJohannes Weiner };
21919a265114SJohannes Weiner 
21921da177e4SLinus Torvalds /*
21934f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
21944f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
21954f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
21964f98a2feSRik van Riel  * onto the active list instead of evict.
21974f98a2feSRik van Riel  *
2198be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2199be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
22004f98a2feSRik van Riel  */
220133377678SVladimir Davydov static void get_scan_count(struct lruvec *lruvec, struct mem_cgroup *memcg,
22026b4f7799SJohannes Weiner 			   struct scan_control *sc, unsigned long *nr,
22036b4f7799SJohannes Weiner 			   unsigned long *lru_pages)
22044f98a2feSRik van Riel {
220533377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
220690126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
22079a265114SJohannes Weiner 	u64 fraction[2];
22089a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
2209599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
22109a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
22119a265114SJohannes Weiner 	enum scan_balance scan_balance;
22120bf1457fSJohannes Weiner 	unsigned long anon, file;
22139a265114SJohannes Weiner 	unsigned long ap, fp;
22149a265114SJohannes Weiner 	enum lru_list lru;
221576a33fc3SShaohua Li 
221676a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2217d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
22189a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
221976a33fc3SShaohua Li 		goto out;
222076a33fc3SShaohua Li 	}
22214f98a2feSRik van Riel 
222210316b31SJohannes Weiner 	/*
222310316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
222410316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
222510316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
222610316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
222710316b31SJohannes Weiner 	 * too expensive.
222810316b31SJohannes Weiner 	 */
222902695175SJohannes Weiner 	if (!global_reclaim(sc) && !swappiness) {
22309a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
223110316b31SJohannes Weiner 		goto out;
223210316b31SJohannes Weiner 	}
223310316b31SJohannes Weiner 
223410316b31SJohannes Weiner 	/*
223510316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
223610316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
223710316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
223810316b31SJohannes Weiner 	 */
223902695175SJohannes Weiner 	if (!sc->priority && swappiness) {
22409a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
224110316b31SJohannes Weiner 		goto out;
224210316b31SJohannes Weiner 	}
224310316b31SJohannes Weiner 
224411d16c25SJohannes Weiner 	/*
224562376251SJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
224662376251SJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
224762376251SJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
224862376251SJohannes Weiner 	 * shrinks, so does the window for rotation from references.
224962376251SJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
225062376251SJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
225162376251SJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
225262376251SJohannes Weiner 	 */
225362376251SJohannes Weiner 	if (global_reclaim(sc)) {
2254599d0c95SMel Gorman 		unsigned long pgdatfile;
2255599d0c95SMel Gorman 		unsigned long pgdatfree;
2256599d0c95SMel Gorman 		int z;
2257599d0c95SMel Gorman 		unsigned long total_high_wmark = 0;
225862376251SJohannes Weiner 
2259599d0c95SMel Gorman 		pgdatfree = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2260599d0c95SMel Gorman 		pgdatfile = node_page_state(pgdat, NR_ACTIVE_FILE) +
2261599d0c95SMel Gorman 			   node_page_state(pgdat, NR_INACTIVE_FILE);
22622ab051e1SJerome Marchand 
2263599d0c95SMel Gorman 		for (z = 0; z < MAX_NR_ZONES; z++) {
2264599d0c95SMel Gorman 			struct zone *zone = &pgdat->node_zones[z];
22656aa303deSMel Gorman 			if (!managed_zone(zone))
2266599d0c95SMel Gorman 				continue;
2267599d0c95SMel Gorman 
2268599d0c95SMel Gorman 			total_high_wmark += high_wmark_pages(zone);
2269599d0c95SMel Gorman 		}
2270599d0c95SMel Gorman 
2271599d0c95SMel Gorman 		if (unlikely(pgdatfile + pgdatfree <= total_high_wmark)) {
227206226226SDavid Rientjes 			/*
227306226226SDavid Rientjes 			 * Force SCAN_ANON if there are enough inactive
227406226226SDavid Rientjes 			 * anonymous pages on the LRU in eligible zones.
227506226226SDavid Rientjes 			 * Otherwise, the small LRU gets thrashed.
227606226226SDavid Rientjes 			 */
22773b991208SJohannes Weiner 			if (!inactive_list_is_low(lruvec, false, sc, false) &&
227806226226SDavid Rientjes 			    lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, sc->reclaim_idx)
227906226226SDavid Rientjes 					>> sc->priority) {
228062376251SJohannes Weiner 				scan_balance = SCAN_ANON;
228162376251SJohannes Weiner 				goto out;
228262376251SJohannes Weiner 			}
228362376251SJohannes Weiner 		}
228406226226SDavid Rientjes 	}
228562376251SJohannes Weiner 
228662376251SJohannes Weiner 	/*
2287316bda0eSVladimir Davydov 	 * If there is enough inactive page cache, i.e. if the size of the
2288316bda0eSVladimir Davydov 	 * inactive list is greater than that of the active list *and* the
2289316bda0eSVladimir Davydov 	 * inactive list actually has some pages to scan on this priority, we
2290316bda0eSVladimir Davydov 	 * do not reclaim anything from the anonymous working set right now.
2291316bda0eSVladimir Davydov 	 * Without the second condition we could end up never scanning an
2292316bda0eSVladimir Davydov 	 * lruvec even if it has plenty of old anonymous pages unless the
2293316bda0eSVladimir Davydov 	 * system is under heavy pressure.
2294e9868505SRik van Riel 	 */
22953b991208SJohannes Weiner 	if (!inactive_list_is_low(lruvec, true, sc, false) &&
229671ab6cfeSMichal Hocko 	    lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, sc->reclaim_idx) >> sc->priority) {
22979a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2298e9868505SRik van Riel 		goto out;
22994f98a2feSRik van Riel 	}
23004f98a2feSRik van Riel 
23019a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
23029a265114SJohannes Weiner 
23034f98a2feSRik van Riel 	/*
230458c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
230558c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
230658c37f6eSKOSAKI Motohiro 	 */
230702695175SJohannes Weiner 	anon_prio = swappiness;
230875b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
230958c37f6eSKOSAKI Motohiro 
231058c37f6eSKOSAKI Motohiro 	/*
23114f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
23124f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
23134f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
23144f98a2feSRik van Riel 	 *
23154f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
23164f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
23174f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
23184f98a2feSRik van Riel 	 *
23194f98a2feSRik van Riel 	 * anon in [0], file in [1]
23204f98a2feSRik van Riel 	 */
23212ab051e1SJerome Marchand 
2322fd538803SMichal Hocko 	anon  = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON, MAX_NR_ZONES) +
2323fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, MAX_NR_ZONES);
2324fd538803SMichal Hocko 	file  = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE, MAX_NR_ZONES) +
2325fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, MAX_NR_ZONES);
23262ab051e1SJerome Marchand 
2327599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
232858c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
23296e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
23306e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
23314f98a2feSRik van Riel 	}
23324f98a2feSRik van Riel 
23336e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
23346e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
23356e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
23364f98a2feSRik van Riel 	}
23374f98a2feSRik van Riel 
23384f98a2feSRik van Riel 	/*
233900d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
234000d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
234100d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
23424f98a2feSRik van Riel 	 */
2343fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
23446e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
23454f98a2feSRik van Riel 
2346fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
23476e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
2348599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
23494f98a2feSRik van Riel 
235076a33fc3SShaohua Li 	fraction[0] = ap;
235176a33fc3SShaohua Li 	fraction[1] = fp;
235276a33fc3SShaohua Li 	denominator = ap + fp + 1;
235376a33fc3SShaohua Li out:
23546b4f7799SJohannes Weiner 	*lru_pages = 0;
23554111304dSHugh Dickins 	for_each_evictable_lru(lru) {
23564111304dSHugh Dickins 		int file = is_file_lru(lru);
2357d778df51SJohannes Weiner 		unsigned long size;
235876a33fc3SShaohua Li 		unsigned long scan;
235976a33fc3SShaohua Li 
236071ab6cfeSMichal Hocko 		size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2361d778df51SJohannes Weiner 		scan = size >> sc->priority;
2362688035f7SJohannes Weiner 		/*
2363688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2364688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2365688035f7SJohannes Weiner 		 */
2366688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
2367d778df51SJohannes Weiner 			scan = min(size, SWAP_CLUSTER_MAX);
23689a265114SJohannes Weiner 
23699a265114SJohannes Weiner 		switch (scan_balance) {
23709a265114SJohannes Weiner 		case SCAN_EQUAL:
23719a265114SJohannes Weiner 			/* Scan lists relative to size */
23729a265114SJohannes Weiner 			break;
23739a265114SJohannes Weiner 		case SCAN_FRACT:
23749a265114SJohannes Weiner 			/*
23759a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
23769a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
237768600f62SRoman Gushchin 			 * Make sure we don't miss the last page
237868600f62SRoman Gushchin 			 * because of a round-off error.
23799a265114SJohannes Weiner 			 */
238068600f62SRoman Gushchin 			scan = DIV64_U64_ROUND_UP(scan * fraction[file],
23816f04f48dSSuleiman Souhlal 						  denominator);
23829a265114SJohannes Weiner 			break;
23839a265114SJohannes Weiner 		case SCAN_FILE:
23849a265114SJohannes Weiner 		case SCAN_ANON:
23859a265114SJohannes Weiner 			/* Scan one type exclusively */
23866b4f7799SJohannes Weiner 			if ((scan_balance == SCAN_FILE) != file) {
23876b4f7799SJohannes Weiner 				size = 0;
23889a265114SJohannes Weiner 				scan = 0;
23896b4f7799SJohannes Weiner 			}
23909a265114SJohannes Weiner 			break;
23919a265114SJohannes Weiner 		default:
23929a265114SJohannes Weiner 			/* Look ma, no brain */
23939a265114SJohannes Weiner 			BUG();
23949a265114SJohannes Weiner 		}
23956b4f7799SJohannes Weiner 
23966b4f7799SJohannes Weiner 		*lru_pages += size;
23974111304dSHugh Dickins 		nr[lru] = scan;
239876a33fc3SShaohua Li 	}
23996e08a369SWu Fengguang }
24004f98a2feSRik van Riel 
24019b4f98cdSJohannes Weiner /*
2402a9dd0a83SMel Gorman  * This is a basic per-node page freer.  Used by both kswapd and direct reclaim.
24039b4f98cdSJohannes Weiner  */
2404a9dd0a83SMel Gorman static void shrink_node_memcg(struct pglist_data *pgdat, struct mem_cgroup *memcg,
24056b4f7799SJohannes Weiner 			      struct scan_control *sc, unsigned long *lru_pages)
24069b4f98cdSJohannes Weiner {
2407ef8f2327SMel Gorman 	struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
24089b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2409e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
24109b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
24119b4f98cdSJohannes Weiner 	enum lru_list lru;
24129b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
24139b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
24149b4f98cdSJohannes Weiner 	struct blk_plug plug;
24151a501907SMel Gorman 	bool scan_adjusted;
24169b4f98cdSJohannes Weiner 
241733377678SVladimir Davydov 	get_scan_count(lruvec, memcg, sc, nr, lru_pages);
24189b4f98cdSJohannes Weiner 
2419e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2420e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2421e82e0561SMel Gorman 
24221a501907SMel Gorman 	/*
24231a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
24241a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
24251a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
24261a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
24271a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
24281a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
24291a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
24301a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
24311a501907SMel Gorman 	 * dropped to zero at the first pass.
24321a501907SMel Gorman 	 */
24331a501907SMel Gorman 	scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
24341a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
24351a501907SMel Gorman 
24369b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
24379b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
24389b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2439e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2440e82e0561SMel Gorman 		unsigned long nr_scanned;
2441e82e0561SMel Gorman 
24429b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
24439b4f98cdSJohannes Weiner 			if (nr[lru]) {
24449b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
24459b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
24469b4f98cdSJohannes Weiner 
24479b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
24483b991208SJohannes Weiner 							    lruvec, sc);
24499b4f98cdSJohannes Weiner 			}
24509b4f98cdSJohannes Weiner 		}
2451e82e0561SMel Gorman 
2452bd041733SMichal Hocko 		cond_resched();
2453bd041733SMichal Hocko 
2454e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2455e82e0561SMel Gorman 			continue;
2456e82e0561SMel Gorman 
24579b4f98cdSJohannes Weiner 		/*
2458e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
24591a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2460e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2461e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2462e82e0561SMel Gorman 		 * proportional to the original scan target.
2463e82e0561SMel Gorman 		 */
2464e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2465e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2466e82e0561SMel Gorman 
24671a501907SMel Gorman 		/*
24681a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
24691a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
24701a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
24711a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
24721a501907SMel Gorman 		 */
24731a501907SMel Gorman 		if (!nr_file || !nr_anon)
24741a501907SMel Gorman 			break;
24751a501907SMel Gorman 
2476e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2477e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2478e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2479e82e0561SMel Gorman 			lru = LRU_BASE;
2480e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2481e82e0561SMel Gorman 		} else {
2482e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2483e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2484e82e0561SMel Gorman 			lru = LRU_FILE;
2485e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2486e82e0561SMel Gorman 		}
2487e82e0561SMel Gorman 
2488e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2489e82e0561SMel Gorman 		nr[lru] = 0;
2490e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2491e82e0561SMel Gorman 
2492e82e0561SMel Gorman 		/*
2493e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2494e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2495e82e0561SMel Gorman 		 */
2496e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2497e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2498e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2499e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2500e82e0561SMel Gorman 
2501e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2502e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2503e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2504e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2505e82e0561SMel Gorman 
2506e82e0561SMel Gorman 		scan_adjusted = true;
25079b4f98cdSJohannes Weiner 	}
25089b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
25099b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
25109b4f98cdSJohannes Weiner 
25119b4f98cdSJohannes Weiner 	/*
25129b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
25139b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
25149b4f98cdSJohannes Weiner 	 */
25153b991208SJohannes Weiner 	if (inactive_list_is_low(lruvec, false, sc, true))
25169b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
25179b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
25189b4f98cdSJohannes Weiner }
25199b4f98cdSJohannes Weiner 
252023b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
25219e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
252223b9da55SMel Gorman {
2523d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
252423b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
25259e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
252623b9da55SMel Gorman 		return true;
252723b9da55SMel Gorman 
252823b9da55SMel Gorman 	return false;
252923b9da55SMel Gorman }
253023b9da55SMel Gorman 
25314f98a2feSRik van Riel /*
253223b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
253323b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
253423b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
253523b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
253623b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
25373e7d3449SMel Gorman  */
2538a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
25393e7d3449SMel Gorman 					unsigned long nr_reclaimed,
25403e7d3449SMel Gorman 					unsigned long nr_scanned,
25413e7d3449SMel Gorman 					struct scan_control *sc)
25423e7d3449SMel Gorman {
25433e7d3449SMel Gorman 	unsigned long pages_for_compaction;
25443e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2545a9dd0a83SMel Gorman 	int z;
25463e7d3449SMel Gorman 
25473e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
25489e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
25493e7d3449SMel Gorman 		return false;
25503e7d3449SMel Gorman 
25512876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
2552dcda9b04SMichal Hocko 	if (sc->gfp_mask & __GFP_RETRY_MAYFAIL) {
25533e7d3449SMel Gorman 		/*
2554dcda9b04SMichal Hocko 		 * For __GFP_RETRY_MAYFAIL allocations, stop reclaiming if the
25552876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
25562876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
2557dcda9b04SMichal Hocko 		 * expensive but a __GFP_RETRY_MAYFAIL caller really wants to succeed
25583e7d3449SMel Gorman 		 */
25593e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
25603e7d3449SMel Gorman 			return false;
25612876592fSMel Gorman 	} else {
25622876592fSMel Gorman 		/*
2563dcda9b04SMichal Hocko 		 * For non-__GFP_RETRY_MAYFAIL allocations which can presumably
25642876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
25652876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
25662876592fSMel Gorman 		 * pages that were scanned. This will return to the
25672876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
25682876592fSMel Gorman 		 * the resulting allocation attempt fails
25692876592fSMel Gorman 		 */
25702876592fSMel Gorman 		if (!nr_reclaimed)
25712876592fSMel Gorman 			return false;
25722876592fSMel Gorman 	}
25733e7d3449SMel Gorman 
25743e7d3449SMel Gorman 	/*
25753e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
25763e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
25773e7d3449SMel Gorman 	 */
25789861a62cSVlastimil Babka 	pages_for_compaction = compact_gap(sc->order);
2579a9dd0a83SMel Gorman 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
2580ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
2581a9dd0a83SMel Gorman 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
25823e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
25833e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
25843e7d3449SMel Gorman 		return true;
25853e7d3449SMel Gorman 
25863e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2587a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2588a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
25896aa303deSMel Gorman 		if (!managed_zone(zone))
2590a9dd0a83SMel Gorman 			continue;
2591a9dd0a83SMel Gorman 
2592a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2593cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
25943e7d3449SMel Gorman 		case COMPACT_CONTINUE:
25953e7d3449SMel Gorman 			return false;
25963e7d3449SMel Gorman 		default:
2597a9dd0a83SMel Gorman 			/* check next zone */
2598a9dd0a83SMel Gorman 			;
25993e7d3449SMel Gorman 		}
26003e7d3449SMel Gorman 	}
2601a9dd0a83SMel Gorman 	return true;
2602a9dd0a83SMel Gorman }
26033e7d3449SMel Gorman 
2604e3c1ac58SAndrey Ryabinin static bool pgdat_memcg_congested(pg_data_t *pgdat, struct mem_cgroup *memcg)
2605e3c1ac58SAndrey Ryabinin {
2606e3c1ac58SAndrey Ryabinin 	return test_bit(PGDAT_CONGESTED, &pgdat->flags) ||
2607e3c1ac58SAndrey Ryabinin 		(memcg && memcg_congested(pgdat, memcg));
2608e3c1ac58SAndrey Ryabinin }
2609e3c1ac58SAndrey Ryabinin 
2610970a39a3SMel Gorman static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc)
2611f16015fbSJohannes Weiner {
2612cb731d6cSVladimir Davydov 	struct reclaim_state *reclaim_state = current->reclaim_state;
26139b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
26142344d7e4SJohannes Weiner 	bool reclaimable = false;
26159b4f98cdSJohannes Weiner 
26169b4f98cdSJohannes Weiner 	do {
26175660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
26185660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
2619ef8f2327SMel Gorman 			.pgdat = pgdat,
26209e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
26215660048cSJohannes Weiner 		};
2622a9dd0a83SMel Gorman 		unsigned long node_lru_pages = 0;
2623694fbc0fSAndrew Morton 		struct mem_cgroup *memcg;
26245660048cSJohannes Weiner 
2625d108c772SAndrey Ryabinin 		memset(&sc->nr, 0, sizeof(sc->nr));
2626d108c772SAndrey Ryabinin 
26279b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
26289b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
26299b4f98cdSJohannes Weiner 
2630694fbc0fSAndrew Morton 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
2631694fbc0fSAndrew Morton 		do {
26326b4f7799SJohannes Weiner 			unsigned long lru_pages;
26338e8ae645SJohannes Weiner 			unsigned long reclaimed;
2634cb731d6cSVladimir Davydov 			unsigned long scanned;
26359b4f98cdSJohannes Weiner 
2636bf8d5d52SRoman Gushchin 			switch (mem_cgroup_protected(root, memcg)) {
2637bf8d5d52SRoman Gushchin 			case MEMCG_PROT_MIN:
2638bf8d5d52SRoman Gushchin 				/*
2639bf8d5d52SRoman Gushchin 				 * Hard protection.
2640bf8d5d52SRoman Gushchin 				 * If there is no reclaimable memory, OOM.
2641bf8d5d52SRoman Gushchin 				 */
2642bf8d5d52SRoman Gushchin 				continue;
2643bf8d5d52SRoman Gushchin 			case MEMCG_PROT_LOW:
2644bf8d5d52SRoman Gushchin 				/*
2645bf8d5d52SRoman Gushchin 				 * Soft protection.
2646bf8d5d52SRoman Gushchin 				 * Respect the protection only as long as
2647bf8d5d52SRoman Gushchin 				 * there is an unprotected supply
2648bf8d5d52SRoman Gushchin 				 * of reclaimable memory from other cgroups.
2649bf8d5d52SRoman Gushchin 				 */
2650d6622f63SYisheng Xie 				if (!sc->memcg_low_reclaim) {
2651d6622f63SYisheng Xie 					sc->memcg_low_skipped = 1;
2652241994edSJohannes Weiner 					continue;
2653d6622f63SYisheng Xie 				}
2654e27be240SJohannes Weiner 				memcg_memory_event(memcg, MEMCG_LOW);
2655bf8d5d52SRoman Gushchin 				break;
2656bf8d5d52SRoman Gushchin 			case MEMCG_PROT_NONE:
2657bf8d5d52SRoman Gushchin 				break;
2658241994edSJohannes Weiner 			}
2659241994edSJohannes Weiner 
26608e8ae645SJohannes Weiner 			reclaimed = sc->nr_reclaimed;
2661cb731d6cSVladimir Davydov 			scanned = sc->nr_scanned;
2662a9dd0a83SMel Gorman 			shrink_node_memcg(pgdat, memcg, sc, &lru_pages);
2663a9dd0a83SMel Gorman 			node_lru_pages += lru_pages;
2664f9be23d6SKonstantin Khlebnikov 
26651c30844dSMel Gorman 			if (sc->may_shrinkslab) {
2666a9dd0a83SMel Gorman 				shrink_slab(sc->gfp_mask, pgdat->node_id,
26679092c71bSJosef Bacik 				    memcg, sc->priority);
26681c30844dSMel Gorman 			}
2669cb731d6cSVladimir Davydov 
26708e8ae645SJohannes Weiner 			/* Record the group's reclaim efficiency */
26718e8ae645SJohannes Weiner 			vmpressure(sc->gfp_mask, memcg, false,
26728e8ae645SJohannes Weiner 				   sc->nr_scanned - scanned,
26738e8ae645SJohannes Weiner 				   sc->nr_reclaimed - reclaimed);
26748e8ae645SJohannes Weiner 
26755660048cSJohannes Weiner 			/*
26762bb0f34fSYang Shi 			 * Kswapd have to scan all memory cgroups to fulfill
26772bb0f34fSYang Shi 			 * the overall scan target for the node.
2678a394cb8eSMichal Hocko 			 *
2679a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2680a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2681a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2682a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
26835660048cSJohannes Weiner 			 */
26842bb0f34fSYang Shi 			if (!current_is_kswapd() &&
2685a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
26865660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
26875660048cSJohannes Weiner 				break;
26885660048cSJohannes Weiner 			}
2689241994edSJohannes Weiner 		} while ((memcg = mem_cgroup_iter(root, memcg, &reclaim)));
269070ddf637SAnton Vorontsov 
26916b4f7799SJohannes Weiner 		if (reclaim_state) {
2692cb731d6cSVladimir Davydov 			sc->nr_reclaimed += reclaim_state->reclaimed_slab;
26936b4f7799SJohannes Weiner 			reclaim_state->reclaimed_slab = 0;
26946b4f7799SJohannes Weiner 		}
26956b4f7799SJohannes Weiner 
26968e8ae645SJohannes Weiner 		/* Record the subtree's reclaim efficiency */
26978e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
269870ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
269970ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
270070ddf637SAnton Vorontsov 
27012344d7e4SJohannes Weiner 		if (sc->nr_reclaimed - nr_reclaimed)
27022344d7e4SJohannes Weiner 			reclaimable = true;
27032344d7e4SJohannes Weiner 
2704e3c1ac58SAndrey Ryabinin 		if (current_is_kswapd()) {
2705d108c772SAndrey Ryabinin 			/*
2706e3c1ac58SAndrey Ryabinin 			 * If reclaim is isolating dirty pages under writeback,
2707e3c1ac58SAndrey Ryabinin 			 * it implies that the long-lived page allocation rate
2708e3c1ac58SAndrey Ryabinin 			 * is exceeding the page laundering rate. Either the
2709e3c1ac58SAndrey Ryabinin 			 * global limits are not being effective at throttling
2710e3c1ac58SAndrey Ryabinin 			 * processes due to the page distribution throughout
2711e3c1ac58SAndrey Ryabinin 			 * zones or there is heavy usage of a slow backing
2712e3c1ac58SAndrey Ryabinin 			 * device. The only option is to throttle from reclaim
2713e3c1ac58SAndrey Ryabinin 			 * context which is not ideal as there is no guarantee
2714d108c772SAndrey Ryabinin 			 * the dirtying process is throttled in the same way
2715d108c772SAndrey Ryabinin 			 * balance_dirty_pages() manages.
2716d108c772SAndrey Ryabinin 			 *
2717e3c1ac58SAndrey Ryabinin 			 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
2718e3c1ac58SAndrey Ryabinin 			 * count the number of pages under pages flagged for
2719e3c1ac58SAndrey Ryabinin 			 * immediate reclaim and stall if any are encountered
2720e3c1ac58SAndrey Ryabinin 			 * in the nr_immediate check below.
2721d108c772SAndrey Ryabinin 			 */
2722d108c772SAndrey Ryabinin 			if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
2723d108c772SAndrey Ryabinin 				set_bit(PGDAT_WRITEBACK, &pgdat->flags);
2724d108c772SAndrey Ryabinin 
2725d108c772SAndrey Ryabinin 			/*
2726d108c772SAndrey Ryabinin 			 * Tag a node as congested if all the dirty pages
2727d108c772SAndrey Ryabinin 			 * scanned were backed by a congested BDI and
2728d108c772SAndrey Ryabinin 			 * wait_iff_congested will stall.
2729d108c772SAndrey Ryabinin 			 */
2730d108c772SAndrey Ryabinin 			if (sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
2731d108c772SAndrey Ryabinin 				set_bit(PGDAT_CONGESTED, &pgdat->flags);
2732d108c772SAndrey Ryabinin 
2733d108c772SAndrey Ryabinin 			/* Allow kswapd to start writing pages during reclaim.*/
2734d108c772SAndrey Ryabinin 			if (sc->nr.unqueued_dirty == sc->nr.file_taken)
2735d108c772SAndrey Ryabinin 				set_bit(PGDAT_DIRTY, &pgdat->flags);
2736d108c772SAndrey Ryabinin 
2737d108c772SAndrey Ryabinin 			/*
2738d108c772SAndrey Ryabinin 			 * If kswapd scans pages marked marked for immediate
2739d108c772SAndrey Ryabinin 			 * reclaim and under writeback (nr_immediate), it
2740d108c772SAndrey Ryabinin 			 * implies that pages are cycling through the LRU
2741d108c772SAndrey Ryabinin 			 * faster than they are written so also forcibly stall.
2742d108c772SAndrey Ryabinin 			 */
2743d108c772SAndrey Ryabinin 			if (sc->nr.immediate)
2744d108c772SAndrey Ryabinin 				congestion_wait(BLK_RW_ASYNC, HZ/10);
2745d108c772SAndrey Ryabinin 		}
2746d108c772SAndrey Ryabinin 
2747d108c772SAndrey Ryabinin 		/*
2748e3c1ac58SAndrey Ryabinin 		 * Legacy memcg will stall in page writeback so avoid forcibly
2749e3c1ac58SAndrey Ryabinin 		 * stalling in wait_iff_congested().
2750e3c1ac58SAndrey Ryabinin 		 */
2751e3c1ac58SAndrey Ryabinin 		if (!global_reclaim(sc) && sane_reclaim(sc) &&
2752e3c1ac58SAndrey Ryabinin 		    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
2753e3c1ac58SAndrey Ryabinin 			set_memcg_congestion(pgdat, root, true);
2754e3c1ac58SAndrey Ryabinin 
2755e3c1ac58SAndrey Ryabinin 		/*
2756d108c772SAndrey Ryabinin 		 * Stall direct reclaim for IO completions if underlying BDIs
2757d108c772SAndrey Ryabinin 		 * and node is congested. Allow kswapd to continue until it
2758d108c772SAndrey Ryabinin 		 * starts encountering unqueued dirty pages or cycling through
2759d108c772SAndrey Ryabinin 		 * the LRU too quickly.
2760d108c772SAndrey Ryabinin 		 */
2761d108c772SAndrey Ryabinin 		if (!sc->hibernation_mode && !current_is_kswapd() &&
2762e3c1ac58SAndrey Ryabinin 		   current_may_throttle() && pgdat_memcg_congested(pgdat, root))
2763e3c1ac58SAndrey Ryabinin 			wait_iff_congested(BLK_RW_ASYNC, HZ/10);
2764d108c772SAndrey Ryabinin 
2765a9dd0a83SMel Gorman 	} while (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
27669b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
27672344d7e4SJohannes Weiner 
2768c73322d0SJohannes Weiner 	/*
2769c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
2770c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
2771c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
2772c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
2773c73322d0SJohannes Weiner 	 */
2774c73322d0SJohannes Weiner 	if (reclaimable)
2775c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
2776c73322d0SJohannes Weiner 
27772344d7e4SJohannes Weiner 	return reclaimable;
2778f16015fbSJohannes Weiner }
2779f16015fbSJohannes Weiner 
278053853e2dSVlastimil Babka /*
2781fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
2782fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
2783fdd4c614SVlastimil Babka  * should reclaim first.
278453853e2dSVlastimil Babka  */
27854f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2786fe4b1b24SMel Gorman {
278731483b6aSMel Gorman 	unsigned long watermark;
2788fdd4c614SVlastimil Babka 	enum compact_result suitable;
2789fe4b1b24SMel Gorman 
2790fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2791fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
2792fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
2793fdd4c614SVlastimil Babka 		return true;
2794fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
2795fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
2796fe4b1b24SMel Gorman 		return false;
2797fe4b1b24SMel Gorman 
2798fdd4c614SVlastimil Babka 	/*
2799fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
2800fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
2801fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
2802fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
2803fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
2804fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
2805fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
2806fdd4c614SVlastimil Babka 	 */
2807fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
2808fdd4c614SVlastimil Babka 
2809fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
2810fe4b1b24SMel Gorman }
2811fe4b1b24SMel Gorman 
28121da177e4SLinus Torvalds /*
28131da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
28141da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
28151da177e4SLinus Torvalds  * request.
28161da177e4SLinus Torvalds  *
28171da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
28181da177e4SLinus Torvalds  * scan then give up on it.
28191da177e4SLinus Torvalds  */
28200a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
28211da177e4SLinus Torvalds {
2822dd1a239fSMel Gorman 	struct zoneref *z;
282354a6eb5cSMel Gorman 	struct zone *zone;
28240608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
28250608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2826619d0d76SWeijie Yang 	gfp_t orig_mask;
282779dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
28281cfb419bSKAMEZAWA Hiroyuki 
2829cc715d99SMel Gorman 	/*
2830cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2831cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2832cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2833cc715d99SMel Gorman 	 */
2834619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2835b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
2836cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
28374f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
2838b2e18757SMel Gorman 	}
2839cc715d99SMel Gorman 
2840d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2841b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
2842b2e18757SMel Gorman 		/*
28431cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
28441cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
28451cfb419bSKAMEZAWA Hiroyuki 		 */
284689b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2847344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2848344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
28491da177e4SLinus Torvalds 				continue;
285065ec02cbSVladimir Davydov 
2851e0887c19SRik van Riel 			/*
2852e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2853e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2854e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2855e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2856e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2857c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2858c7cfa37bSCopot Alexandru 			 * page allocations.
2859e0887c19SRik van Riel 			 */
28600b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
28610b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
28624f588331SMel Gorman 			    compaction_ready(zone, sc)) {
28630b06496aSJohannes Weiner 				sc->compaction_ready = true;
2864e0887c19SRik van Riel 				continue;
2865e0887c19SRik van Riel 			}
28660b06496aSJohannes Weiner 
28670608f43dSAndrew Morton 			/*
286879dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
286979dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
287079dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
287179dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
287279dafcdcSMel Gorman 			 */
287379dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
287479dafcdcSMel Gorman 				continue;
287579dafcdcSMel Gorman 
287679dafcdcSMel Gorman 			/*
28770608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
28780608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
28790608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
28800608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
28810608f43dSAndrew Morton 			 */
28820608f43dSAndrew Morton 			nr_soft_scanned = 0;
2883ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
28840608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
28850608f43dSAndrew Morton 						&nr_soft_scanned);
28860608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
28870608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
2888ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2889ac34a1a3SKAMEZAWA Hiroyuki 		}
2890d149e3b2SYing Han 
289179dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
289279dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
289379dafcdcSMel Gorman 			continue;
289479dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
2895970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
28961da177e4SLinus Torvalds 	}
2897e0c23279SMel Gorman 
289865ec02cbSVladimir Davydov 	/*
2899619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2900619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
2901619d0d76SWeijie Yang 	 */
2902619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
29031da177e4SLinus Torvalds }
29041da177e4SLinus Torvalds 
29052a2e4885SJohannes Weiner static void snapshot_refaults(struct mem_cgroup *root_memcg, pg_data_t *pgdat)
29062a2e4885SJohannes Weiner {
29072a2e4885SJohannes Weiner 	struct mem_cgroup *memcg;
29082a2e4885SJohannes Weiner 
29092a2e4885SJohannes Weiner 	memcg = mem_cgroup_iter(root_memcg, NULL, NULL);
29102a2e4885SJohannes Weiner 	do {
29112a2e4885SJohannes Weiner 		unsigned long refaults;
29122a2e4885SJohannes Weiner 		struct lruvec *lruvec;
29132a2e4885SJohannes Weiner 
29142a2e4885SJohannes Weiner 		lruvec = mem_cgroup_lruvec(pgdat, memcg);
2915205b20ccSJohannes Weiner 		refaults = lruvec_page_state_local(lruvec, WORKINGSET_ACTIVATE);
29162a2e4885SJohannes Weiner 		lruvec->refaults = refaults;
29172a2e4885SJohannes Weiner 	} while ((memcg = mem_cgroup_iter(root_memcg, memcg, NULL)));
29182a2e4885SJohannes Weiner }
29192a2e4885SJohannes Weiner 
29201da177e4SLinus Torvalds /*
29211da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
29221da177e4SLinus Torvalds  *
29231da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
29241da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
29251da177e4SLinus Torvalds  *
29261da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
29271da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
29285b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
29295b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
29305b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
29315b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2932a41f24eaSNishanth Aravamudan  *
2933a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2934a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
29351da177e4SLinus Torvalds  */
2936dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
29373115cd91SVladimir Davydov 					  struct scan_control *sc)
29381da177e4SLinus Torvalds {
2939241994edSJohannes Weiner 	int initial_priority = sc->priority;
29402a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
29412a2e4885SJohannes Weiner 	struct zoneref *z;
29422a2e4885SJohannes Weiner 	struct zone *zone;
2943241994edSJohannes Weiner retry:
2944873b4771SKeika Kobayashi 	delayacct_freepages_start();
2945873b4771SKeika Kobayashi 
294689b5fae5SJohannes Weiner 	if (global_reclaim(sc))
29477cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
29481da177e4SLinus Torvalds 
29499e3b2f8cSKonstantin Khlebnikov 	do {
295070ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
295170ddf637SAnton Vorontsov 				sc->priority);
295266e1707bSBalbir Singh 		sc->nr_scanned = 0;
29530a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
2954e0c23279SMel Gorman 
2955bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
29560b06496aSJohannes Weiner 			break;
29570b06496aSJohannes Weiner 
29580b06496aSJohannes Weiner 		if (sc->compaction_ready)
29590b06496aSJohannes Weiner 			break;
29601da177e4SLinus Torvalds 
29611da177e4SLinus Torvalds 		/*
29620e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
29630e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
29640e50ce3bSMinchan Kim 		 */
29650e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
29660e50ce3bSMinchan Kim 			sc->may_writepage = 1;
29670b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
2968bb21c7ceSKOSAKI Motohiro 
29692a2e4885SJohannes Weiner 	last_pgdat = NULL;
29702a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
29712a2e4885SJohannes Weiner 					sc->nodemask) {
29722a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
29732a2e4885SJohannes Weiner 			continue;
29742a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
29752a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
2976e3c1ac58SAndrey Ryabinin 		set_memcg_congestion(last_pgdat, sc->target_mem_cgroup, false);
29772a2e4885SJohannes Weiner 	}
29782a2e4885SJohannes Weiner 
2979873b4771SKeika Kobayashi 	delayacct_freepages_end();
2980873b4771SKeika Kobayashi 
2981bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2982bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2983bb21c7ceSKOSAKI Motohiro 
29840cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
29850b06496aSJohannes Weiner 	if (sc->compaction_ready)
29867335084dSMel Gorman 		return 1;
29877335084dSMel Gorman 
2988241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
2989d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
2990241994edSJohannes Weiner 		sc->priority = initial_priority;
2991d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
2992d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
2993241994edSJohannes Weiner 		goto retry;
2994241994edSJohannes Weiner 	}
2995241994edSJohannes Weiner 
2996bb21c7ceSKOSAKI Motohiro 	return 0;
29971da177e4SLinus Torvalds }
29981da177e4SLinus Torvalds 
2999c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
30005515061dSMel Gorman {
30015515061dSMel Gorman 	struct zone *zone;
30025515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
30035515061dSMel Gorman 	unsigned long free_pages = 0;
30045515061dSMel Gorman 	int i;
30055515061dSMel Gorman 	bool wmark_ok;
30065515061dSMel Gorman 
3007c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3008c73322d0SJohannes Weiner 		return true;
3009c73322d0SJohannes Weiner 
30105515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
30115515061dSMel Gorman 		zone = &pgdat->node_zones[i];
3012d450abd8SJohannes Weiner 		if (!managed_zone(zone))
3013d450abd8SJohannes Weiner 			continue;
3014d450abd8SJohannes Weiner 
3015d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
3016675becceSMel Gorman 			continue;
3017675becceSMel Gorman 
30185515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
30195515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
30205515061dSMel Gorman 	}
30215515061dSMel Gorman 
3022675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
3023675becceSMel Gorman 	if (!pfmemalloc_reserve)
3024675becceSMel Gorman 		return true;
3025675becceSMel Gorman 
30265515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
30275515061dSMel Gorman 
30285515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
30295515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
303038087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
30315515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
30325515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
30335515061dSMel Gorman 	}
30345515061dSMel Gorman 
30355515061dSMel Gorman 	return wmark_ok;
30365515061dSMel Gorman }
30375515061dSMel Gorman 
30385515061dSMel Gorman /*
30395515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
30405515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
30415515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
304250694c28SMel Gorman  * when the low watermark is reached.
304350694c28SMel Gorman  *
304450694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
304550694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
30465515061dSMel Gorman  */
304750694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
30485515061dSMel Gorman 					nodemask_t *nodemask)
30495515061dSMel Gorman {
3050675becceSMel Gorman 	struct zoneref *z;
30515515061dSMel Gorman 	struct zone *zone;
3052675becceSMel Gorman 	pg_data_t *pgdat = NULL;
30535515061dSMel Gorman 
30545515061dSMel Gorman 	/*
30555515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
30565515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
30575515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
30585515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
30595515061dSMel Gorman 	 * processes to block on log_wait_commit().
30605515061dSMel Gorman 	 */
30615515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
306250694c28SMel Gorman 		goto out;
306350694c28SMel Gorman 
306450694c28SMel Gorman 	/*
306550694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
306650694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
306750694c28SMel Gorman 	 */
306850694c28SMel Gorman 	if (fatal_signal_pending(current))
306950694c28SMel Gorman 		goto out;
30705515061dSMel Gorman 
3071675becceSMel Gorman 	/*
3072675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
3073675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3074675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
3075675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
3076675becceSMel Gorman 	 *
3077675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
3078675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
3079675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
3080675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
3081675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
3082675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
3083675becceSMel Gorman 	 * should make reasonable progress.
3084675becceSMel Gorman 	 */
3085675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
308617636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
3087675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
3088675becceSMel Gorman 			continue;
3089675becceSMel Gorman 
3090675becceSMel Gorman 		/* Throttle based on the first usable node */
30915515061dSMel Gorman 		pgdat = zone->zone_pgdat;
3092c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
309350694c28SMel Gorman 			goto out;
3094675becceSMel Gorman 		break;
3095675becceSMel Gorman 	}
3096675becceSMel Gorman 
3097675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
3098675becceSMel Gorman 	if (!pgdat)
3099675becceSMel Gorman 		goto out;
31005515061dSMel Gorman 
310168243e76SMel Gorman 	/* Account for the throttling */
310268243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
310368243e76SMel Gorman 
31045515061dSMel Gorman 	/*
31055515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
31065515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
31075515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
31085515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
31095515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
31105515061dSMel Gorman 	 * second before continuing.
31115515061dSMel Gorman 	 */
31125515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
31135515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3114c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
311550694c28SMel Gorman 
311650694c28SMel Gorman 		goto check_pending;
31175515061dSMel Gorman 	}
31185515061dSMel Gorman 
31195515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
31205515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3121c73322d0SJohannes Weiner 		allow_direct_reclaim(pgdat));
312250694c28SMel Gorman 
312350694c28SMel Gorman check_pending:
312450694c28SMel Gorman 	if (fatal_signal_pending(current))
312550694c28SMel Gorman 		return true;
312650694c28SMel Gorman 
312750694c28SMel Gorman out:
312850694c28SMel Gorman 	return false;
31295515061dSMel Gorman }
31305515061dSMel Gorman 
3131dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3132327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
313366e1707bSBalbir Singh {
313433906bc5SMel Gorman 	unsigned long nr_reclaimed;
313566e1707bSBalbir Singh 	struct scan_control sc = {
313622fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3137f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3138b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
3139ee814fe2SJohannes Weiner 		.order = order,
3140ee814fe2SJohannes Weiner 		.nodemask = nodemask,
3141ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
3142ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3143a6dc60f8SJohannes Weiner 		.may_unmap = 1,
31442e2e4259SKOSAKI Motohiro 		.may_swap = 1,
31451c30844dSMel Gorman 		.may_shrinkslab = 1,
314666e1707bSBalbir Singh 	};
314766e1707bSBalbir Singh 
31485515061dSMel Gorman 	/*
3149bb451fdfSGreg Thelen 	 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3150bb451fdfSGreg Thelen 	 * Confirm they are large enough for max values.
3151bb451fdfSGreg Thelen 	 */
3152bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3153bb451fdfSGreg Thelen 	BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3154bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3155bb451fdfSGreg Thelen 
3156bb451fdfSGreg Thelen 	/*
315750694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
315850694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
315950694c28SMel Gorman 	 * point.
31605515061dSMel Gorman 	 */
3161f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
31625515061dSMel Gorman 		return 1;
31635515061dSMel Gorman 
31643481c37fSYafang Shao 	trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
316533906bc5SMel Gorman 
31663115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
316733906bc5SMel Gorman 
316833906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
316933906bc5SMel Gorman 
317033906bc5SMel Gorman 	return nr_reclaimed;
317166e1707bSBalbir Singh }
317266e1707bSBalbir Singh 
3173c255a458SAndrew Morton #ifdef CONFIG_MEMCG
317466e1707bSBalbir Singh 
3175a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
31764e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
3177ef8f2327SMel Gorman 						pg_data_t *pgdat,
31780ae5e89cSYing Han 						unsigned long *nr_scanned)
31794e416953SBalbir Singh {
31804e416953SBalbir Singh 	struct scan_control sc = {
3181b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3182ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
31834e416953SBalbir Singh 		.may_writepage = !laptop_mode,
31844e416953SBalbir Singh 		.may_unmap = 1,
3185b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
31864e416953SBalbir Singh 		.may_swap = !noswap,
31871c30844dSMel Gorman 		.may_shrinkslab = 1,
31884e416953SBalbir Singh 	};
31896b4f7799SJohannes Weiner 	unsigned long lru_pages;
31900ae5e89cSYing Han 
31914e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
31924e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3193bdce6d9eSKOSAKI Motohiro 
31949e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
31953481c37fSYafang Shao 						      sc.gfp_mask);
3196bdce6d9eSKOSAKI Motohiro 
31974e416953SBalbir Singh 	/*
31984e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
31994e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3200a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
32014e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
32024e416953SBalbir Singh 	 * the priority and make it zero.
32034e416953SBalbir Singh 	 */
3204ef8f2327SMel Gorman 	shrink_node_memcg(pgdat, memcg, &sc, &lru_pages);
3205bdce6d9eSKOSAKI Motohiro 
3206bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3207bdce6d9eSKOSAKI Motohiro 
32080ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
32094e416953SBalbir Singh 	return sc.nr_reclaimed;
32104e416953SBalbir Singh }
32114e416953SBalbir Singh 
321272835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3213b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
32148c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3215b70a2a21SJohannes Weiner 					   bool may_swap)
321666e1707bSBalbir Singh {
32174e416953SBalbir Singh 	struct zonelist *zonelist;
3218bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3219eb414681SJohannes Weiner 	unsigned long pflags;
3220889976dbSYing Han 	int nid;
3221499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
322266e1707bSBalbir Singh 	struct scan_control sc = {
3223b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
32247dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3225ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3226b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3227ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3228ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
322966e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3230a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3231b70a2a21SJohannes Weiner 		.may_swap = may_swap,
32321c30844dSMel Gorman 		.may_shrinkslab = 1,
3233a09ed5e0SYing Han 	};
323466e1707bSBalbir Singh 
3235889976dbSYing Han 	/*
3236889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
3237889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
3238889976dbSYing Han 	 * scan does not need to be the current node.
3239889976dbSYing Han 	 */
324072835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
3241889976dbSYing Han 
3242c9634cf0SAneesh Kumar K.V 	zonelist = &NODE_DATA(nid)->node_zonelists[ZONELIST_FALLBACK];
3243bdce6d9eSKOSAKI Motohiro 
32443481c37fSYafang Shao 	trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
3245bdce6d9eSKOSAKI Motohiro 
3246eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
3247499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3248eb414681SJohannes Weiner 
32493115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3250eb414681SJohannes Weiner 
3251499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3252eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
3253bdce6d9eSKOSAKI Motohiro 
3254bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
3255bdce6d9eSKOSAKI Motohiro 
3256bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
325766e1707bSBalbir Singh }
325866e1707bSBalbir Singh #endif
325966e1707bSBalbir Singh 
32601d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3261ef8f2327SMel Gorman 				struct scan_control *sc)
3262f16015fbSJohannes Weiner {
3263b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3264b95a2f2dSJohannes Weiner 
3265b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3266b95a2f2dSJohannes Weiner 		return;
3267b95a2f2dSJohannes Weiner 
3268b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3269b95a2f2dSJohannes Weiner 	do {
3270ef8f2327SMel Gorman 		struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
3271f16015fbSJohannes Weiner 
32723b991208SJohannes Weiner 		if (inactive_list_is_low(lruvec, false, sc, true))
32731a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
32749e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
3275b95a2f2dSJohannes Weiner 
3276b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3277b95a2f2dSJohannes Weiner 	} while (memcg);
3278f16015fbSJohannes Weiner }
3279f16015fbSJohannes Weiner 
32801c30844dSMel Gorman static bool pgdat_watermark_boosted(pg_data_t *pgdat, int classzone_idx)
32811c30844dSMel Gorman {
32821c30844dSMel Gorman 	int i;
32831c30844dSMel Gorman 	struct zone *zone;
32841c30844dSMel Gorman 
32851c30844dSMel Gorman 	/*
32861c30844dSMel Gorman 	 * Check for watermark boosts top-down as the higher zones
32871c30844dSMel Gorman 	 * are more likely to be boosted. Both watermarks and boosts
32881c30844dSMel Gorman 	 * should not be checked at the time time as reclaim would
32891c30844dSMel Gorman 	 * start prematurely when there is no boosting and a lower
32901c30844dSMel Gorman 	 * zone is balanced.
32911c30844dSMel Gorman 	 */
32921c30844dSMel Gorman 	for (i = classzone_idx; i >= 0; i--) {
32931c30844dSMel Gorman 		zone = pgdat->node_zones + i;
32941c30844dSMel Gorman 		if (!managed_zone(zone))
32951c30844dSMel Gorman 			continue;
32961c30844dSMel Gorman 
32971c30844dSMel Gorman 		if (zone->watermark_boost)
32981c30844dSMel Gorman 			return true;
32991c30844dSMel Gorman 	}
33001c30844dSMel Gorman 
33011c30844dSMel Gorman 	return false;
33021c30844dSMel Gorman }
33031c30844dSMel Gorman 
3304e716f2ebSMel Gorman /*
3305e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
3306e716f2ebSMel Gorman  * and classzone_idx
3307e716f2ebSMel Gorman  */
3308e716f2ebSMel Gorman static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
330960cefed4SJohannes Weiner {
3310e716f2ebSMel Gorman 	int i;
3311e716f2ebSMel Gorman 	unsigned long mark = -1;
3312e716f2ebSMel Gorman 	struct zone *zone;
331360cefed4SJohannes Weiner 
33141c30844dSMel Gorman 	/*
33151c30844dSMel Gorman 	 * Check watermarks bottom-up as lower zones are more likely to
33161c30844dSMel Gorman 	 * meet watermarks.
33171c30844dSMel Gorman 	 */
3318e716f2ebSMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
3319e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
33206256c6b4SMel Gorman 
3321e716f2ebSMel Gorman 		if (!managed_zone(zone))
3322e716f2ebSMel Gorman 			continue;
3323e716f2ebSMel Gorman 
3324e716f2ebSMel Gorman 		mark = high_wmark_pages(zone);
3325e716f2ebSMel Gorman 		if (zone_watermark_ok_safe(zone, order, mark, classzone_idx))
33266256c6b4SMel Gorman 			return true;
332760cefed4SJohannes Weiner 	}
332860cefed4SJohannes Weiner 
3329e716f2ebSMel Gorman 	/*
3330e716f2ebSMel Gorman 	 * If a node has no populated zone within classzone_idx, it does not
3331e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3332e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3333e716f2ebSMel Gorman 	 */
3334e716f2ebSMel Gorman 	if (mark == -1)
3335e716f2ebSMel Gorman 		return true;
3336e716f2ebSMel Gorman 
3337e716f2ebSMel Gorman 	return false;
3338e716f2ebSMel Gorman }
3339e716f2ebSMel Gorman 
3340631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
3341631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
3342631b6e08SMel Gorman {
3343631b6e08SMel Gorman 	clear_bit(PGDAT_CONGESTED, &pgdat->flags);
3344631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
3345631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3346631b6e08SMel Gorman }
3347631b6e08SMel Gorman 
33481741c877SMel Gorman /*
33495515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
33505515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
33515515061dSMel Gorman  *
33525515061dSMel Gorman  * Returns true if kswapd is ready to sleep
33535515061dSMel Gorman  */
3354d9f21d42SMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3355f50de2d3SMel Gorman {
33565515061dSMel Gorman 	/*
33579e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3358c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
33599e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
33609e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
33619e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
33629e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
33639e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
33649e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
33659e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
33669e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
33679e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
33685515061dSMel Gorman 	 */
33699e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
33709e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3371f50de2d3SMel Gorman 
3372c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3373c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3374c73322d0SJohannes Weiner 		return true;
3375c73322d0SJohannes Weiner 
3376e716f2ebSMel Gorman 	if (pgdat_balanced(pgdat, order, classzone_idx)) {
3377631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
3378333b0a45SShantanu Goel 		return true;
33791d82de61SMel Gorman 	}
33801d82de61SMel Gorman 
3381333b0a45SShantanu Goel 	return false;
3382f50de2d3SMel Gorman }
3383f50de2d3SMel Gorman 
33841da177e4SLinus Torvalds /*
33851d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
33861d82de61SMel Gorman  * zone that is currently unbalanced.
3387b8e83b94SMel Gorman  *
3388b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3389283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3390283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
339175485363SMel Gorman  */
33921d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3393accf6242SVlastimil Babka 			       struct scan_control *sc)
339475485363SMel Gorman {
33951d82de61SMel Gorman 	struct zone *zone;
33961d82de61SMel Gorman 	int z;
339775485363SMel Gorman 
33981d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
33991d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3400970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
34011d82de61SMel Gorman 		zone = pgdat->node_zones + z;
34026aa303deSMel Gorman 		if (!managed_zone(zone))
34031d82de61SMel Gorman 			continue;
34047c954f6dSMel Gorman 
34051d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
34067c954f6dSMel Gorman 	}
34077c954f6dSMel Gorman 
34081d82de61SMel Gorman 	/*
34091d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
34101d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
34111d82de61SMel Gorman 	 */
3412970a39a3SMel Gorman 	shrink_node(pgdat, sc);
34131d82de61SMel Gorman 
34141d82de61SMel Gorman 	/*
34151d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
34161d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
34171d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
34181d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
34191d82de61SMel Gorman 	 * can direct reclaim/compact.
34201d82de61SMel Gorman 	 */
34219861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
34221d82de61SMel Gorman 		sc->order = 0;
34231d82de61SMel Gorman 
3424b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
342575485363SMel Gorman }
342675485363SMel Gorman 
342775485363SMel Gorman /*
34281d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
34291d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
34301d82de61SMel Gorman  * balanced.
34311da177e4SLinus Torvalds  *
34321d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
34331da177e4SLinus Torvalds  *
34341da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
343541858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
34368bb4e7a2SWei Yang  * found to have free_pages <= high_wmark_pages(zone), any page in that zone
34371d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
34381d82de61SMel Gorman  * balanced.
34391da177e4SLinus Torvalds  */
3440accf6242SVlastimil Babka static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
34411da177e4SLinus Torvalds {
34421da177e4SLinus Torvalds 	int i;
34430608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
34440608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3445eb414681SJohannes Weiner 	unsigned long pflags;
34461c30844dSMel Gorman 	unsigned long nr_boost_reclaim;
34471c30844dSMel Gorman 	unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
34481c30844dSMel Gorman 	bool boosted;
34491d82de61SMel Gorman 	struct zone *zone;
3450179e9639SAndrew Morton 	struct scan_control sc = {
3451179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3452ee814fe2SJohannes Weiner 		.order = order,
3453a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3454179e9639SAndrew Morton 	};
345593781325SOmar Sandoval 
3456eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
345793781325SOmar Sandoval 	__fs_reclaim_acquire();
345893781325SOmar Sandoval 
3459f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
34601da177e4SLinus Torvalds 
34611c30844dSMel Gorman 	/*
34621c30844dSMel Gorman 	 * Account for the reclaim boost. Note that the zone boost is left in
34631c30844dSMel Gorman 	 * place so that parallel allocations that are near the watermark will
34641c30844dSMel Gorman 	 * stall or direct reclaim until kswapd is finished.
34651c30844dSMel Gorman 	 */
34661c30844dSMel Gorman 	nr_boost_reclaim = 0;
34671c30844dSMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
34681c30844dSMel Gorman 		zone = pgdat->node_zones + i;
34691c30844dSMel Gorman 		if (!managed_zone(zone))
34701c30844dSMel Gorman 			continue;
34711c30844dSMel Gorman 
34721c30844dSMel Gorman 		nr_boost_reclaim += zone->watermark_boost;
34731c30844dSMel Gorman 		zone_boosts[i] = zone->watermark_boost;
34741c30844dSMel Gorman 	}
34751c30844dSMel Gorman 	boosted = nr_boost_reclaim;
34761c30844dSMel Gorman 
34771c30844dSMel Gorman restart:
34781c30844dSMel Gorman 	sc.priority = DEF_PRIORITY;
34799e3b2f8cSKonstantin Khlebnikov 	do {
3480c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
3481b8e83b94SMel Gorman 		bool raise_priority = true;
34821c30844dSMel Gorman 		bool balanced;
348393781325SOmar Sandoval 		bool ret;
3484b8e83b94SMel Gorman 
348584c7a777SMel Gorman 		sc.reclaim_idx = classzone_idx;
34861da177e4SLinus Torvalds 
348786c79f6bSMel Gorman 		/*
348884c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
348984c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
349084c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
349184c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
349284c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
349384c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
349484c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
349584c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
349686c79f6bSMel Gorman 		 */
349786c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
349886c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
349986c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
35006aa303deSMel Gorman 				if (!managed_zone(zone))
350186c79f6bSMel Gorman 					continue;
350286c79f6bSMel Gorman 
3503970a39a3SMel Gorman 				sc.reclaim_idx = i;
350486c79f6bSMel Gorman 				break;
350586c79f6bSMel Gorman 			}
350686c79f6bSMel Gorman 		}
350786c79f6bSMel Gorman 
350886c79f6bSMel Gorman 		/*
35091c30844dSMel Gorman 		 * If the pgdat is imbalanced then ignore boosting and preserve
35101c30844dSMel Gorman 		 * the watermarks for a later time and restart. Note that the
35111c30844dSMel Gorman 		 * zone watermarks will be still reset at the end of balancing
35121c30844dSMel Gorman 		 * on the grounds that the normal reclaim should be enough to
35131c30844dSMel Gorman 		 * re-evaluate if boosting is required when kswapd next wakes.
351486c79f6bSMel Gorman 		 */
35151c30844dSMel Gorman 		balanced = pgdat_balanced(pgdat, sc.order, classzone_idx);
35161c30844dSMel Gorman 		if (!balanced && nr_boost_reclaim) {
35171c30844dSMel Gorman 			nr_boost_reclaim = 0;
35181c30844dSMel Gorman 			goto restart;
35191c30844dSMel Gorman 		}
35201c30844dSMel Gorman 
35211c30844dSMel Gorman 		/*
35221c30844dSMel Gorman 		 * If boosting is not active then only reclaim if there are no
35231c30844dSMel Gorman 		 * eligible zones. Note that sc.reclaim_idx is not used as
35241c30844dSMel Gorman 		 * buffer_heads_over_limit may have adjusted it.
35251c30844dSMel Gorman 		 */
35261c30844dSMel Gorman 		if (!nr_boost_reclaim && balanced)
35271da177e4SLinus Torvalds 			goto out;
3528e1dbeda6SAndrew Morton 
35291c30844dSMel Gorman 		/* Limit the priority of boosting to avoid reclaim writeback */
35301c30844dSMel Gorman 		if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
35311c30844dSMel Gorman 			raise_priority = false;
35321c30844dSMel Gorman 
35331c30844dSMel Gorman 		/*
35341c30844dSMel Gorman 		 * Do not writeback or swap pages for boosted reclaim. The
35351c30844dSMel Gorman 		 * intent is to relieve pressure not issue sub-optimal IO
35361c30844dSMel Gorman 		 * from reclaim context. If no pages are reclaimed, the
35371c30844dSMel Gorman 		 * reclaim will be aborted.
35381c30844dSMel Gorman 		 */
35391c30844dSMel Gorman 		sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
35401c30844dSMel Gorman 		sc.may_swap = !nr_boost_reclaim;
35411c30844dSMel Gorman 		sc.may_shrinkslab = !nr_boost_reclaim;
35421c30844dSMel Gorman 
35431da177e4SLinus Torvalds 		/*
35441d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
35451d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
35461d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
35471d82de61SMel Gorman 		 * about consistent aging.
35481d82de61SMel Gorman 		 */
3549ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
35501d82de61SMel Gorman 
35511d82de61SMel Gorman 		/*
3552b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3553b7ea3c41SMel Gorman 		 * even in laptop mode.
3554b7ea3c41SMel Gorman 		 */
3555047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
3556b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3557b7ea3c41SMel Gorman 
35581d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
35591da177e4SLinus Torvalds 		sc.nr_scanned = 0;
35600608f43dSAndrew Morton 		nr_soft_scanned = 0;
3561ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
35621d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
35630608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
35640608f43dSAndrew Morton 
356532a4330dSRik van Riel 		/*
35661d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
35671d82de61SMel Gorman 		 * enough pages are already being scanned that that high
35681d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
356932a4330dSRik van Riel 		 */
3570970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3571b8e83b94SMel Gorman 			raise_priority = false;
3572d7868daeSMel Gorman 
35735515061dSMel Gorman 		/*
35745515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
35755515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
35765515061dSMel Gorman 		 * able to safely make forward progress. Wake them
35775515061dSMel Gorman 		 */
35785515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3579c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
3580cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
35815515061dSMel Gorman 
3582b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
358393781325SOmar Sandoval 		__fs_reclaim_release();
358493781325SOmar Sandoval 		ret = try_to_freeze();
358593781325SOmar Sandoval 		__fs_reclaim_acquire();
358693781325SOmar Sandoval 		if (ret || kthread_should_stop())
3587b8e83b94SMel Gorman 			break;
3588b8e83b94SMel Gorman 
3589b8e83b94SMel Gorman 		/*
3590b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3591b8e83b94SMel Gorman 		 * progress in reclaiming pages
3592b8e83b94SMel Gorman 		 */
3593c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
35941c30844dSMel Gorman 		nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
35951c30844dSMel Gorman 
35961c30844dSMel Gorman 		/*
35971c30844dSMel Gorman 		 * If reclaim made no progress for a boost, stop reclaim as
35981c30844dSMel Gorman 		 * IO cannot be queued and it could be an infinite loop in
35991c30844dSMel Gorman 		 * extreme circumstances.
36001c30844dSMel Gorman 		 */
36011c30844dSMel Gorman 		if (nr_boost_reclaim && !nr_reclaimed)
36021c30844dSMel Gorman 			break;
36031c30844dSMel Gorman 
3604c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
3605b8e83b94SMel Gorman 			sc.priority--;
36061d82de61SMel Gorman 	} while (sc.priority >= 1);
36071da177e4SLinus Torvalds 
3608c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
3609c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
3610c73322d0SJohannes Weiner 
3611b8e83b94SMel Gorman out:
36121c30844dSMel Gorman 	/* If reclaim was boosted, account for the reclaim done in this pass */
36131c30844dSMel Gorman 	if (boosted) {
36141c30844dSMel Gorman 		unsigned long flags;
36151c30844dSMel Gorman 
36161c30844dSMel Gorman 		for (i = 0; i <= classzone_idx; i++) {
36171c30844dSMel Gorman 			if (!zone_boosts[i])
36181c30844dSMel Gorman 				continue;
36191c30844dSMel Gorman 
36201c30844dSMel Gorman 			/* Increments are under the zone lock */
36211c30844dSMel Gorman 			zone = pgdat->node_zones + i;
36221c30844dSMel Gorman 			spin_lock_irqsave(&zone->lock, flags);
36231c30844dSMel Gorman 			zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
36241c30844dSMel Gorman 			spin_unlock_irqrestore(&zone->lock, flags);
36251c30844dSMel Gorman 		}
36261c30844dSMel Gorman 
36271c30844dSMel Gorman 		/*
36281c30844dSMel Gorman 		 * As there is now likely space, wakeup kcompact to defragment
36291c30844dSMel Gorman 		 * pageblocks.
36301c30844dSMel Gorman 		 */
36311c30844dSMel Gorman 		wakeup_kcompactd(pgdat, pageblock_order, classzone_idx);
36321c30844dSMel Gorman 	}
36331c30844dSMel Gorman 
36342a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
363593781325SOmar Sandoval 	__fs_reclaim_release();
3636eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
36370abdee2bSMel Gorman 	/*
36381d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
36391d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
36401d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
36411d82de61SMel Gorman 	 * remain at the higher level.
36420abdee2bSMel Gorman 	 */
36431d82de61SMel Gorman 	return sc.order;
36441da177e4SLinus Torvalds }
36451da177e4SLinus Torvalds 
3646e716f2ebSMel Gorman /*
3647e716f2ebSMel Gorman  * pgdat->kswapd_classzone_idx is the highest zone index that a recent
3648e716f2ebSMel Gorman  * allocation request woke kswapd for. When kswapd has not woken recently,
3649e716f2ebSMel Gorman  * the value is MAX_NR_ZONES which is not a valid index. This compares a
3650e716f2ebSMel Gorman  * given classzone and returns it or the highest classzone index kswapd
3651e716f2ebSMel Gorman  * was recently woke for.
3652e716f2ebSMel Gorman  */
3653e716f2ebSMel Gorman static enum zone_type kswapd_classzone_idx(pg_data_t *pgdat,
3654e716f2ebSMel Gorman 					   enum zone_type classzone_idx)
3655e716f2ebSMel Gorman {
3656e716f2ebSMel Gorman 	if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3657e716f2ebSMel Gorman 		return classzone_idx;
3658e716f2ebSMel Gorman 
3659e716f2ebSMel Gorman 	return max(pgdat->kswapd_classzone_idx, classzone_idx);
3660e716f2ebSMel Gorman }
3661e716f2ebSMel Gorman 
366238087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
366338087d9bSMel Gorman 				unsigned int classzone_idx)
3664f0bc0a60SKOSAKI Motohiro {
3665f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3666f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3667f0bc0a60SKOSAKI Motohiro 
3668f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3669f0bc0a60SKOSAKI Motohiro 		return;
3670f0bc0a60SKOSAKI Motohiro 
3671f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3672f0bc0a60SKOSAKI Motohiro 
3673333b0a45SShantanu Goel 	/*
3674333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
3675333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
3676333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
3677333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
3678333b0a45SShantanu Goel 	 * succeed.
3679333b0a45SShantanu Goel 	 */
3680d9f21d42SMel Gorman 	if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3681fd901c95SVlastimil Babka 		/*
3682fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3683fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3684fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3685fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3686fd901c95SVlastimil Babka 		 */
3687fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3688fd901c95SVlastimil Babka 
3689fd901c95SVlastimil Babka 		/*
3690fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3691fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3692fd901c95SVlastimil Babka 		 */
369338087d9bSMel Gorman 		wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
3694fd901c95SVlastimil Babka 
3695f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
369638087d9bSMel Gorman 
369738087d9bSMel Gorman 		/*
369838087d9bSMel Gorman 		 * If woken prematurely then reset kswapd_classzone_idx and
369938087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
370038087d9bSMel Gorman 		 * the previous request that slept prematurely.
370138087d9bSMel Gorman 		 */
370238087d9bSMel Gorman 		if (remaining) {
3703e716f2ebSMel Gorman 			pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
370438087d9bSMel Gorman 			pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
370538087d9bSMel Gorman 		}
370638087d9bSMel Gorman 
3707f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3708f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3709f0bc0a60SKOSAKI Motohiro 	}
3710f0bc0a60SKOSAKI Motohiro 
3711f0bc0a60SKOSAKI Motohiro 	/*
3712f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3713f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3714f0bc0a60SKOSAKI Motohiro 	 */
3715d9f21d42SMel Gorman 	if (!remaining &&
3716d9f21d42SMel Gorman 	    prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3717f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3718f0bc0a60SKOSAKI Motohiro 
3719f0bc0a60SKOSAKI Motohiro 		/*
3720f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3721f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3722f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3723f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3724f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3725f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3726f0bc0a60SKOSAKI Motohiro 		 */
3727f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
37281c7e7f6cSAaditya Kumar 
37291c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3730f0bc0a60SKOSAKI Motohiro 			schedule();
37311c7e7f6cSAaditya Kumar 
3732f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3733f0bc0a60SKOSAKI Motohiro 	} else {
3734f0bc0a60SKOSAKI Motohiro 		if (remaining)
3735f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3736f0bc0a60SKOSAKI Motohiro 		else
3737f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3738f0bc0a60SKOSAKI Motohiro 	}
3739f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3740f0bc0a60SKOSAKI Motohiro }
3741f0bc0a60SKOSAKI Motohiro 
37421da177e4SLinus Torvalds /*
37431da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
37441da177e4SLinus Torvalds  * from the init process.
37451da177e4SLinus Torvalds  *
37461da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
37471da177e4SLinus Torvalds  * free memory available even if there is no other activity
37481da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
37491da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
37501da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
37511da177e4SLinus Torvalds  *
37521da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
37531da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
37541da177e4SLinus Torvalds  */
37551da177e4SLinus Torvalds static int kswapd(void *p)
37561da177e4SLinus Torvalds {
3757e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
3758e716f2ebSMel Gorman 	unsigned int classzone_idx = MAX_NR_ZONES - 1;
37591da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
37601da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3761f0bc0a60SKOSAKI Motohiro 
37621da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
37631da177e4SLinus Torvalds 		.reclaimed_slab = 0,
37641da177e4SLinus Torvalds 	};
3765a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
37661da177e4SLinus Torvalds 
3767174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3768c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
37691da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
37701da177e4SLinus Torvalds 
37711da177e4SLinus Torvalds 	/*
37721da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
37731da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
37741da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
37751da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
37761da177e4SLinus Torvalds 	 *
37771da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
37781da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
37791da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
37801da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
37811da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
37821da177e4SLinus Torvalds 	 */
3783930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
378483144186SRafael J. Wysocki 	set_freezable();
37851da177e4SLinus Torvalds 
3786e716f2ebSMel Gorman 	pgdat->kswapd_order = 0;
3787e716f2ebSMel Gorman 	pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
37881da177e4SLinus Torvalds 	for ( ; ; ) {
37896f6313d4SJeff Liu 		bool ret;
37903e1d1d28SChristoph Lameter 
3791e716f2ebSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3792e716f2ebSMel Gorman 		classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
3793e716f2ebSMel Gorman 
379438087d9bSMel Gorman kswapd_try_sleep:
379538087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
379638087d9bSMel Gorman 					classzone_idx);
3797215ddd66SMel Gorman 
379838087d9bSMel Gorman 		/* Read the new order and classzone_idx */
379938087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3800e716f2ebSMel Gorman 		classzone_idx = kswapd_classzone_idx(pgdat, 0);
380138087d9bSMel Gorman 		pgdat->kswapd_order = 0;
3802e716f2ebSMel Gorman 		pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
38031da177e4SLinus Torvalds 
38048fe23e05SDavid Rientjes 		ret = try_to_freeze();
38058fe23e05SDavid Rientjes 		if (kthread_should_stop())
38068fe23e05SDavid Rientjes 			break;
38078fe23e05SDavid Rientjes 
38088fe23e05SDavid Rientjes 		/*
38098fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
38108fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3811b1296cc4SRafael J. Wysocki 		 */
381238087d9bSMel Gorman 		if (ret)
381338087d9bSMel Gorman 			continue;
38141d82de61SMel Gorman 
381538087d9bSMel Gorman 		/*
381638087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
381738087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
381838087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
381938087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
382038087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
382138087d9bSMel Gorman 		 * request (alloc_order).
382238087d9bSMel Gorman 		 */
3823e5146b12SMel Gorman 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
3824e5146b12SMel Gorman 						alloc_order);
382538087d9bSMel Gorman 		reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
382638087d9bSMel Gorman 		if (reclaim_order < alloc_order)
382738087d9bSMel Gorman 			goto kswapd_try_sleep;
382833906bc5SMel Gorman 	}
3829b0a8cc58STakamori Yamaguchi 
383071abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
3831b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
383271abdc15SJohannes Weiner 
38331da177e4SLinus Torvalds 	return 0;
38341da177e4SLinus Torvalds }
38351da177e4SLinus Torvalds 
38361da177e4SLinus Torvalds /*
38375ecd9d40SDavid Rientjes  * A zone is low on free memory or too fragmented for high-order memory.  If
38385ecd9d40SDavid Rientjes  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
38395ecd9d40SDavid Rientjes  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
38405ecd9d40SDavid Rientjes  * has failed or is not needed, still wake up kcompactd if only compaction is
38415ecd9d40SDavid Rientjes  * needed.
38421da177e4SLinus Torvalds  */
38435ecd9d40SDavid Rientjes void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
38445ecd9d40SDavid Rientjes 		   enum zone_type classzone_idx)
38451da177e4SLinus Torvalds {
38461da177e4SLinus Torvalds 	pg_data_t *pgdat;
38471da177e4SLinus Torvalds 
38486aa303deSMel Gorman 	if (!managed_zone(zone))
38491da177e4SLinus Torvalds 		return;
38501da177e4SLinus Torvalds 
38515ecd9d40SDavid Rientjes 	if (!cpuset_zone_allowed(zone, gfp_flags))
38521da177e4SLinus Torvalds 		return;
385388f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
3854e716f2ebSMel Gorman 	pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat,
3855e716f2ebSMel Gorman 							   classzone_idx);
385638087d9bSMel Gorman 	pgdat->kswapd_order = max(pgdat->kswapd_order, order);
38578d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
38581da177e4SLinus Torvalds 		return;
3859e1a55637SMel Gorman 
38605ecd9d40SDavid Rientjes 	/* Hopeless node, leave it to direct reclaim if possible */
38615ecd9d40SDavid Rientjes 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
38621c30844dSMel Gorman 	    (pgdat_balanced(pgdat, order, classzone_idx) &&
38631c30844dSMel Gorman 	     !pgdat_watermark_boosted(pgdat, classzone_idx))) {
38645ecd9d40SDavid Rientjes 		/*
38655ecd9d40SDavid Rientjes 		 * There may be plenty of free memory available, but it's too
38665ecd9d40SDavid Rientjes 		 * fragmented for high-order allocations.  Wake up kcompactd
38675ecd9d40SDavid Rientjes 		 * and rely on compaction_suitable() to determine if it's
38685ecd9d40SDavid Rientjes 		 * needed.  If it fails, it will defer subsequent attempts to
38695ecd9d40SDavid Rientjes 		 * ratelimit its work.
38705ecd9d40SDavid Rientjes 		 */
38715ecd9d40SDavid Rientjes 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
38725ecd9d40SDavid Rientjes 			wakeup_kcompactd(pgdat, order, classzone_idx);
3873c73322d0SJohannes Weiner 		return;
38745ecd9d40SDavid Rientjes 	}
3875c73322d0SJohannes Weiner 
38765ecd9d40SDavid Rientjes 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, classzone_idx, order,
38775ecd9d40SDavid Rientjes 				      gfp_flags);
38788d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
38791da177e4SLinus Torvalds }
38801da177e4SLinus Torvalds 
3881c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
38821da177e4SLinus Torvalds /*
38837b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3884d6277db4SRafael J. Wysocki  * freed pages.
3885d6277db4SRafael J. Wysocki  *
3886d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3887d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3888d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
38891da177e4SLinus Torvalds  */
38907b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
38911da177e4SLinus Torvalds {
3892d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3893d6277db4SRafael J. Wysocki 	struct scan_control sc = {
38947b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
3895ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
3896b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
38979e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
3898ee814fe2SJohannes Weiner 		.may_writepage = 1,
3899ee814fe2SJohannes Weiner 		.may_unmap = 1,
3900ee814fe2SJohannes Weiner 		.may_swap = 1,
3901ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
39021da177e4SLinus Torvalds 	};
39037b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
39047b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
39057b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3906499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
39071da177e4SLinus Torvalds 
3908d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
390993781325SOmar Sandoval 	noreclaim_flag = memalloc_noreclaim_save();
3910d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
39117b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3912d6277db4SRafael J. Wysocki 
39133115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3914d6277db4SRafael J. Wysocki 
39157b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
3916499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
391793781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
3918d6277db4SRafael J. Wysocki 
39197b51755cSKOSAKI Motohiro 	return nr_reclaimed;
39201da177e4SLinus Torvalds }
3921c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
39221da177e4SLinus Torvalds 
39231da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
39241da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
39251da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
39261da177e4SLinus Torvalds    restore their cpu bindings. */
3927517bbed9SSebastian Andrzej Siewior static int kswapd_cpu_online(unsigned int cpu)
39281da177e4SLinus Torvalds {
392958c0a4a7SYasunori Goto 	int nid;
39301da177e4SLinus Torvalds 
393148fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY) {
3932c5f59f08SMike Travis 		pg_data_t *pgdat = NODE_DATA(nid);
3933a70f7302SRusty Russell 		const struct cpumask *mask;
3934a70f7302SRusty Russell 
3935a70f7302SRusty Russell 		mask = cpumask_of_node(pgdat->node_id);
3936c5f59f08SMike Travis 
39373e597945SRusty Russell 		if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
39381da177e4SLinus Torvalds 			/* One of our CPUs online: restore mask */
3939c5f59f08SMike Travis 			set_cpus_allowed_ptr(pgdat->kswapd, mask);
39401da177e4SLinus Torvalds 	}
3941517bbed9SSebastian Andrzej Siewior 	return 0;
39421da177e4SLinus Torvalds }
39431da177e4SLinus Torvalds 
39443218ae14SYasunori Goto /*
39453218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
39463218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
39473218ae14SYasunori Goto  */
39483218ae14SYasunori Goto int kswapd_run(int nid)
39493218ae14SYasunori Goto {
39503218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
39513218ae14SYasunori Goto 	int ret = 0;
39523218ae14SYasunori Goto 
39533218ae14SYasunori Goto 	if (pgdat->kswapd)
39543218ae14SYasunori Goto 		return 0;
39553218ae14SYasunori Goto 
39563218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
39573218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
39583218ae14SYasunori Goto 		/* failure at boot is fatal */
3959c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
3960d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3961d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3962d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
39633218ae14SYasunori Goto 	}
39643218ae14SYasunori Goto 	return ret;
39653218ae14SYasunori Goto }
39663218ae14SYasunori Goto 
39678fe23e05SDavid Rientjes /*
3968d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3969bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
39708fe23e05SDavid Rientjes  */
39718fe23e05SDavid Rientjes void kswapd_stop(int nid)
39728fe23e05SDavid Rientjes {
39738fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
39748fe23e05SDavid Rientjes 
3975d8adde17SJiang Liu 	if (kswapd) {
39768fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3977d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3978d8adde17SJiang Liu 	}
39798fe23e05SDavid Rientjes }
39808fe23e05SDavid Rientjes 
39811da177e4SLinus Torvalds static int __init kswapd_init(void)
39821da177e4SLinus Torvalds {
3983517bbed9SSebastian Andrzej Siewior 	int nid, ret;
398469e05944SAndrew Morton 
39851da177e4SLinus Torvalds 	swap_setup();
398648fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
39873218ae14SYasunori Goto  		kswapd_run(nid);
3988517bbed9SSebastian Andrzej Siewior 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
3989517bbed9SSebastian Andrzej Siewior 					"mm/vmscan:online", kswapd_cpu_online,
3990517bbed9SSebastian Andrzej Siewior 					NULL);
3991517bbed9SSebastian Andrzej Siewior 	WARN_ON(ret < 0);
39921da177e4SLinus Torvalds 	return 0;
39931da177e4SLinus Torvalds }
39941da177e4SLinus Torvalds 
39951da177e4SLinus Torvalds module_init(kswapd_init)
39969eeff239SChristoph Lameter 
39979eeff239SChristoph Lameter #ifdef CONFIG_NUMA
39989eeff239SChristoph Lameter /*
3999a5f5f91dSMel Gorman  * Node reclaim mode
40009eeff239SChristoph Lameter  *
4001a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
40029eeff239SChristoph Lameter  * the watermarks.
40039eeff239SChristoph Lameter  */
4004a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
40059eeff239SChristoph Lameter 
40061b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
40077d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
40081b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
400995bbc0c7SZhihui Zhang #define RECLAIM_UNMAP (1<<2)	/* Unmap pages during reclaim */
40101b2ffb78SChristoph Lameter 
40119eeff239SChristoph Lameter /*
4012a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
4013a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
4014a92f7126SChristoph Lameter  * a zone.
4015a92f7126SChristoph Lameter  */
4016a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
4017a92f7126SChristoph Lameter 
40189eeff239SChristoph Lameter /*
4019a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
40209614634fSChristoph Lameter  * occur.
40219614634fSChristoph Lameter  */
40229614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
40239614634fSChristoph Lameter 
40249614634fSChristoph Lameter /*
40250ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
40260ff38490SChristoph Lameter  * slab reclaim needs to occur.
40270ff38490SChristoph Lameter  */
40280ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
40290ff38490SChristoph Lameter 
403011fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
403190afa5deSMel Gorman {
403211fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
403311fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
403411fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
403590afa5deSMel Gorman 
403690afa5deSMel Gorman 	/*
403790afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
403890afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
403990afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
404090afa5deSMel Gorman 	 */
404190afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
404290afa5deSMel Gorman }
404390afa5deSMel Gorman 
404490afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4045a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
404690afa5deSMel Gorman {
4047d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
4048d031a157SAlexandru Moise 	unsigned long delta = 0;
404990afa5deSMel Gorman 
405090afa5deSMel Gorman 	/*
405195bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
405290afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
405311fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
405490afa5deSMel Gorman 	 * a better estimate
405590afa5deSMel Gorman 	 */
4056a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
4057a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
405890afa5deSMel Gorman 	else
4059a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
406090afa5deSMel Gorman 
406190afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
4062a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
4063a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
406490afa5deSMel Gorman 
406590afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
406690afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
406790afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
406890afa5deSMel Gorman 
406990afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
407090afa5deSMel Gorman }
407190afa5deSMel Gorman 
40720ff38490SChristoph Lameter /*
4073a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
40749eeff239SChristoph Lameter  */
4075a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
40769eeff239SChristoph Lameter {
40777fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
407869e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
40799eeff239SChristoph Lameter 	struct task_struct *p = current;
40809eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
4081499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
4082179e9639SAndrew Morton 	struct scan_control sc = {
408362b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4084f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
4085bd2f6199SJohannes Weiner 		.order = order,
4086a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
4087a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4088a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4089ee814fe2SJohannes Weiner 		.may_swap = 1,
4090f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
4091179e9639SAndrew Morton 	};
40929eeff239SChristoph Lameter 
4093132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4094132bb8cfSYafang Shao 					   sc.gfp_mask);
4095132bb8cfSYafang Shao 
40969eeff239SChristoph Lameter 	cond_resched();
409793781325SOmar Sandoval 	fs_reclaim_acquire(sc.gfp_mask);
4098d4f7796eSChristoph Lameter 	/*
409995bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4100d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
410195bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
4102d4f7796eSChristoph Lameter 	 */
4103499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
4104499118e9SVlastimil Babka 	p->flags |= PF_SWAPWRITE;
41059eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
41069eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
4107c84db23cSChristoph Lameter 
4108a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
4109a92f7126SChristoph Lameter 		/*
4110894befecSAndrey Ryabinin 		 * Free memory by calling shrink node with increasing
41110ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
4112a92f7126SChristoph Lameter 		 */
4113a92f7126SChristoph Lameter 		do {
4114970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
41159e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
41160ff38490SChristoph Lameter 	}
4117a92f7126SChristoph Lameter 
41189eeff239SChristoph Lameter 	p->reclaim_state = NULL;
4119499118e9SVlastimil Babka 	current->flags &= ~PF_SWAPWRITE;
4120499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
412193781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4122132bb8cfSYafang Shao 
4123132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4124132bb8cfSYafang Shao 
4125a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
41269eeff239SChristoph Lameter }
4127179e9639SAndrew Morton 
4128a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4129179e9639SAndrew Morton {
4130d773ed6bSDavid Rientjes 	int ret;
4131179e9639SAndrew Morton 
4132179e9639SAndrew Morton 	/*
4133a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
41340ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
413534aa1330SChristoph Lameter 	 *
41369614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
41379614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
4138a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
4139a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
41409614634fSChristoph Lameter 	 * unmapped file backed pages.
4141179e9639SAndrew Morton 	 */
4142a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4143385386cfSJohannes Weiner 	    node_page_state(pgdat, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
4144a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
4145179e9639SAndrew Morton 
4146179e9639SAndrew Morton 	/*
4147d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
4148179e9639SAndrew Morton 	 */
4149d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4150a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4151179e9639SAndrew Morton 
4152179e9639SAndrew Morton 	/*
4153a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
4154179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
4155179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
4156179e9639SAndrew Morton 	 * as wide as possible.
4157179e9639SAndrew Morton 	 */
4158a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4159a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4160d773ed6bSDavid Rientjes 
4161a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4162a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4163fa5e084eSMel Gorman 
4164a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
4165a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4166d773ed6bSDavid Rientjes 
416724cf7251SMel Gorman 	if (!ret)
416824cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
416924cf7251SMel Gorman 
4170d773ed6bSDavid Rientjes 	return ret;
4171179e9639SAndrew Morton }
41729eeff239SChristoph Lameter #endif
4173894bc310SLee Schermerhorn 
4174894bc310SLee Schermerhorn /*
4175894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
4176894bc310SLee Schermerhorn  * @page: the page to test
4177894bc310SLee Schermerhorn  *
4178894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
417939b5f29aSHugh Dickins  * lists vs unevictable list.
4180894bc310SLee Schermerhorn  *
4181894bc310SLee Schermerhorn  * Reasons page might not be evictable:
4182ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
4183b291f000SNick Piggin  * (2) page is part of an mlocked VMA
4184ba9ddf49SLee Schermerhorn  *
4185894bc310SLee Schermerhorn  */
418639b5f29aSHugh Dickins int page_evictable(struct page *page)
4187894bc310SLee Schermerhorn {
4188e92bb4ddSHuang Ying 	int ret;
4189e92bb4ddSHuang Ying 
4190e92bb4ddSHuang Ying 	/* Prevent address_space of inode and swap cache from being freed */
4191e92bb4ddSHuang Ying 	rcu_read_lock();
4192e92bb4ddSHuang Ying 	ret = !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
4193e92bb4ddSHuang Ying 	rcu_read_unlock();
4194e92bb4ddSHuang Ying 	return ret;
4195894bc310SLee Schermerhorn }
419689e004eaSLee Schermerhorn 
419789e004eaSLee Schermerhorn /**
419864e3d12fSKuo-Hsin Yang  * check_move_unevictable_pages - check pages for evictability and move to
419964e3d12fSKuo-Hsin Yang  * appropriate zone lru list
420064e3d12fSKuo-Hsin Yang  * @pvec: pagevec with lru pages to check
420189e004eaSLee Schermerhorn  *
420264e3d12fSKuo-Hsin Yang  * Checks pages for evictability, if an evictable page is in the unevictable
420364e3d12fSKuo-Hsin Yang  * lru list, moves it to the appropriate evictable lru list. This function
420464e3d12fSKuo-Hsin Yang  * should be only used for lru pages.
420589e004eaSLee Schermerhorn  */
420664e3d12fSKuo-Hsin Yang void check_move_unevictable_pages(struct pagevec *pvec)
420789e004eaSLee Schermerhorn {
4208925b7673SJohannes Weiner 	struct lruvec *lruvec;
4209785b99feSMel Gorman 	struct pglist_data *pgdat = NULL;
421024513264SHugh Dickins 	int pgscanned = 0;
421124513264SHugh Dickins 	int pgrescued = 0;
421289e004eaSLee Schermerhorn 	int i;
421389e004eaSLee Schermerhorn 
421464e3d12fSKuo-Hsin Yang 	for (i = 0; i < pvec->nr; i++) {
421564e3d12fSKuo-Hsin Yang 		struct page *page = pvec->pages[i];
4216785b99feSMel Gorman 		struct pglist_data *pagepgdat = page_pgdat(page);
421789e004eaSLee Schermerhorn 
421824513264SHugh Dickins 		pgscanned++;
4219785b99feSMel Gorman 		if (pagepgdat != pgdat) {
4220785b99feSMel Gorman 			if (pgdat)
4221785b99feSMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
4222785b99feSMel Gorman 			pgdat = pagepgdat;
4223785b99feSMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
422489e004eaSLee Schermerhorn 		}
4225785b99feSMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
422689e004eaSLee Schermerhorn 
422724513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
422824513264SHugh Dickins 			continue;
422989e004eaSLee Schermerhorn 
423039b5f29aSHugh Dickins 		if (page_evictable(page)) {
423124513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
423224513264SHugh Dickins 
4233309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
423424513264SHugh Dickins 			ClearPageUnevictable(page);
4235fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
4236fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
423724513264SHugh Dickins 			pgrescued++;
423889e004eaSLee Schermerhorn 		}
423989e004eaSLee Schermerhorn 	}
424024513264SHugh Dickins 
4241785b99feSMel Gorman 	if (pgdat) {
424224513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
424324513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
4244785b99feSMel Gorman 		spin_unlock_irq(&pgdat->lru_lock);
424524513264SHugh Dickins 	}
424685046579SHugh Dickins }
424764e3d12fSKuo-Hsin Yang EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
4248