xref: /openbmc/linux/mm/vmscan.c (revision 1b05117df78e035afb5f66ef50bf8750d976ef08)
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 
91d6622f63SYisheng Xie 	/*
92d6622f63SYisheng Xie 	 * Cgroups are not reclaimed below their configured memory.low,
93d6622f63SYisheng Xie 	 * unless we threaten to OOM. If any cgroups are skipped due to
94d6622f63SYisheng Xie 	 * memory.low and nothing was reclaimed, go back for memory.low.
95d6622f63SYisheng Xie 	 */
96d6622f63SYisheng Xie 	unsigned int memcg_low_reclaim:1;
97d6622f63SYisheng Xie 	unsigned int memcg_low_skipped:1;
98241994edSJohannes Weiner 
99ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
100ee814fe2SJohannes Weiner 
101ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
102ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
103ee814fe2SJohannes Weiner 
104bb451fdfSGreg Thelen 	/* Allocation order */
105bb451fdfSGreg Thelen 	s8 order;
106bb451fdfSGreg Thelen 
107bb451fdfSGreg Thelen 	/* Scan (total_size >> priority) pages at once */
108bb451fdfSGreg Thelen 	s8 priority;
109bb451fdfSGreg Thelen 
110bb451fdfSGreg Thelen 	/* The highest zone to isolate pages for reclaim from */
111bb451fdfSGreg Thelen 	s8 reclaim_idx;
112bb451fdfSGreg Thelen 
113bb451fdfSGreg Thelen 	/* This context's GFP mask */
114bb451fdfSGreg Thelen 	gfp_t gfp_mask;
115bb451fdfSGreg Thelen 
116ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
117ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
118ee814fe2SJohannes Weiner 
119ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
120ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
121d108c772SAndrey Ryabinin 
122d108c772SAndrey Ryabinin 	struct {
123d108c772SAndrey Ryabinin 		unsigned int dirty;
124d108c772SAndrey Ryabinin 		unsigned int unqueued_dirty;
125d108c772SAndrey Ryabinin 		unsigned int congested;
126d108c772SAndrey Ryabinin 		unsigned int writeback;
127d108c772SAndrey Ryabinin 		unsigned int immediate;
128d108c772SAndrey Ryabinin 		unsigned int file_taken;
129d108c772SAndrey Ryabinin 		unsigned int taken;
130d108c772SAndrey Ryabinin 	} nr;
131e5ca8071SYafang Shao 
132e5ca8071SYafang Shao 	/* for recording the reclaimed slab by now */
133e5ca8071SYafang Shao 	struct reclaim_state reclaim_state;
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 
1740a432dcbSYang Shi static void set_task_reclaim_state(struct task_struct *task,
1750a432dcbSYang Shi 				   struct reclaim_state *rs)
1760a432dcbSYang Shi {
1770a432dcbSYang Shi 	/* Check for an overwrite */
1780a432dcbSYang Shi 	WARN_ON_ONCE(rs && task->reclaim_state);
1790a432dcbSYang Shi 
1800a432dcbSYang Shi 	/* Check for the nulling of an already-nulled member */
1810a432dcbSYang Shi 	WARN_ON_ONCE(!rs && !task->reclaim_state);
1820a432dcbSYang Shi 
1830a432dcbSYang Shi 	task->reclaim_state = rs;
1840a432dcbSYang Shi }
1850a432dcbSYang Shi 
1861da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1871da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1881da177e4SLinus Torvalds 
1890a432dcbSYang Shi #ifdef CONFIG_MEMCG
1907e010df5SKirill Tkhai /*
1917e010df5SKirill Tkhai  * We allow subsystems to populate their shrinker-related
1927e010df5SKirill Tkhai  * LRU lists before register_shrinker_prepared() is called
1937e010df5SKirill Tkhai  * for the shrinker, since we don't want to impose
1947e010df5SKirill Tkhai  * restrictions on their internal registration order.
1957e010df5SKirill Tkhai  * In this case shrink_slab_memcg() may find corresponding
1967e010df5SKirill Tkhai  * bit is set in the shrinkers map.
1977e010df5SKirill Tkhai  *
1987e010df5SKirill Tkhai  * This value is used by the function to detect registering
1997e010df5SKirill Tkhai  * shrinkers and to skip do_shrink_slab() calls for them.
2007e010df5SKirill Tkhai  */
2017e010df5SKirill Tkhai #define SHRINKER_REGISTERING ((struct shrinker *)~0UL)
2027e010df5SKirill Tkhai 
203b4c2b231SKirill Tkhai static DEFINE_IDR(shrinker_idr);
204b4c2b231SKirill Tkhai static int shrinker_nr_max;
205b4c2b231SKirill Tkhai 
206b4c2b231SKirill Tkhai static int prealloc_memcg_shrinker(struct shrinker *shrinker)
207b4c2b231SKirill Tkhai {
208b4c2b231SKirill Tkhai 	int id, ret = -ENOMEM;
209b4c2b231SKirill Tkhai 
210b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
211b4c2b231SKirill Tkhai 	/* This may call shrinker, so it must use down_read_trylock() */
2127e010df5SKirill Tkhai 	id = idr_alloc(&shrinker_idr, SHRINKER_REGISTERING, 0, 0, GFP_KERNEL);
213b4c2b231SKirill Tkhai 	if (id < 0)
214b4c2b231SKirill Tkhai 		goto unlock;
215b4c2b231SKirill Tkhai 
2160a4465d3SKirill Tkhai 	if (id >= shrinker_nr_max) {
2170a4465d3SKirill Tkhai 		if (memcg_expand_shrinker_maps(id)) {
2180a4465d3SKirill Tkhai 			idr_remove(&shrinker_idr, id);
2190a4465d3SKirill Tkhai 			goto unlock;
2200a4465d3SKirill Tkhai 		}
2210a4465d3SKirill Tkhai 
222b4c2b231SKirill Tkhai 		shrinker_nr_max = id + 1;
2230a4465d3SKirill Tkhai 	}
224b4c2b231SKirill Tkhai 	shrinker->id = id;
225b4c2b231SKirill Tkhai 	ret = 0;
226b4c2b231SKirill Tkhai unlock:
227b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
228b4c2b231SKirill Tkhai 	return ret;
229b4c2b231SKirill Tkhai }
230b4c2b231SKirill Tkhai 
231b4c2b231SKirill Tkhai static void unregister_memcg_shrinker(struct shrinker *shrinker)
232b4c2b231SKirill Tkhai {
233b4c2b231SKirill Tkhai 	int id = shrinker->id;
234b4c2b231SKirill Tkhai 
235b4c2b231SKirill Tkhai 	BUG_ON(id < 0);
236b4c2b231SKirill Tkhai 
237b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
238b4c2b231SKirill Tkhai 	idr_remove(&shrinker_idr, id);
239b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
240b4c2b231SKirill Tkhai }
241b4c2b231SKirill Tkhai 
242b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
24389b5fae5SJohannes Weiner {
244b5ead35eSJohannes Weiner 	return sc->target_mem_cgroup;
24589b5fae5SJohannes Weiner }
24697c9341fSTejun Heo 
24797c9341fSTejun Heo /**
248b5ead35eSJohannes Weiner  * writeback_throttling_sane - is the usual dirty throttling mechanism available?
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  */
260b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
26197c9341fSTejun Heo {
262b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
26397c9341fSTejun Heo 		return true;
26497c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
26569234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
26697c9341fSTejun Heo 		return true;
26797c9341fSTejun Heo #endif
26897c9341fSTejun Heo 	return false;
26997c9341fSTejun Heo }
27091a45470SKAMEZAWA Hiroyuki #else
2710a432dcbSYang Shi static int prealloc_memcg_shrinker(struct shrinker *shrinker)
2720a432dcbSYang Shi {
2730a432dcbSYang Shi 	return 0;
2740a432dcbSYang Shi }
2750a432dcbSYang Shi 
2760a432dcbSYang Shi static void unregister_memcg_shrinker(struct shrinker *shrinker)
2770a432dcbSYang Shi {
2780a432dcbSYang Shi }
2790a432dcbSYang Shi 
280b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
28189b5fae5SJohannes Weiner {
282b5ead35eSJohannes Weiner 	return false;
28389b5fae5SJohannes Weiner }
28497c9341fSTejun Heo 
285b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
28697c9341fSTejun Heo {
28797c9341fSTejun Heo 	return true;
28897c9341fSTejun Heo }
28991a45470SKAMEZAWA Hiroyuki #endif
29091a45470SKAMEZAWA Hiroyuki 
2915a1c84b4SMel Gorman /*
2925a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
2935a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
2945a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
2955a1c84b4SMel Gorman  */
2965a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
2975a1c84b4SMel Gorman {
2985a1c84b4SMel Gorman 	unsigned long nr;
2995a1c84b4SMel Gorman 
3005a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
3015a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
3025a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
3035a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
3045a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
3055a1c84b4SMel Gorman 
3065a1c84b4SMel Gorman 	return nr;
3075a1c84b4SMel Gorman }
3085a1c84b4SMel Gorman 
309fd538803SMichal Hocko /**
310fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
311fd538803SMichal Hocko  * @lruvec: lru vector
312fd538803SMichal Hocko  * @lru: lru to use
313fd538803SMichal Hocko  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
314fd538803SMichal Hocko  */
315fd538803SMichal Hocko unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, int zone_idx)
316c9f299d9SKOSAKI Motohiro {
317de3b0150SJohannes Weiner 	unsigned long size = 0;
318fd538803SMichal Hocko 	int zid;
319a3d8e054SKOSAKI Motohiro 
320de3b0150SJohannes Weiner 	for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
321fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
322fd538803SMichal Hocko 
323fd538803SMichal Hocko 		if (!managed_zone(zone))
324fd538803SMichal Hocko 			continue;
325fd538803SMichal Hocko 
326fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
327de3b0150SJohannes Weiner 			size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
328fd538803SMichal Hocko 		else
329de3b0150SJohannes Weiner 			size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
330c9f299d9SKOSAKI Motohiro 	}
331de3b0150SJohannes Weiner 	return size;
332b4536f0cSMichal Hocko }
333b4536f0cSMichal Hocko 
3341da177e4SLinus Torvalds /*
3351d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
3361da177e4SLinus Torvalds  */
3378e04944fSTetsuo Handa int prealloc_shrinker(struct shrinker *shrinker)
3381da177e4SLinus Torvalds {
339b9726c26SAlexey Dobriyan 	unsigned int size = sizeof(*shrinker->nr_deferred);
3401d3d4437SGlauber Costa 
3411d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
3421d3d4437SGlauber Costa 		size *= nr_node_ids;
3431d3d4437SGlauber Costa 
3441d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
3451d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
3461d3d4437SGlauber Costa 		return -ENOMEM;
347b4c2b231SKirill Tkhai 
348b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
349b4c2b231SKirill Tkhai 		if (prealloc_memcg_shrinker(shrinker))
350b4c2b231SKirill Tkhai 			goto free_deferred;
351b4c2b231SKirill Tkhai 	}
352b4c2b231SKirill Tkhai 
3538e04944fSTetsuo Handa 	return 0;
354b4c2b231SKirill Tkhai 
355b4c2b231SKirill Tkhai free_deferred:
356b4c2b231SKirill Tkhai 	kfree(shrinker->nr_deferred);
357b4c2b231SKirill Tkhai 	shrinker->nr_deferred = NULL;
358b4c2b231SKirill Tkhai 	return -ENOMEM;
3598e04944fSTetsuo Handa }
3601d3d4437SGlauber Costa 
3618e04944fSTetsuo Handa void free_prealloced_shrinker(struct shrinker *shrinker)
3628e04944fSTetsuo Handa {
363b4c2b231SKirill Tkhai 	if (!shrinker->nr_deferred)
364b4c2b231SKirill Tkhai 		return;
365b4c2b231SKirill Tkhai 
366b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
367b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
368b4c2b231SKirill Tkhai 
3698e04944fSTetsuo Handa 	kfree(shrinker->nr_deferred);
3708e04944fSTetsuo Handa 	shrinker->nr_deferred = NULL;
3718e04944fSTetsuo Handa }
3728e04944fSTetsuo Handa 
3738e04944fSTetsuo Handa void register_shrinker_prepared(struct shrinker *shrinker)
3748e04944fSTetsuo Handa {
3751da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
3761da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
3777e010df5SKirill Tkhai #ifdef CONFIG_MEMCG_KMEM
3788df4a44cSKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
3797e010df5SKirill Tkhai 		idr_replace(&shrinker_idr, shrinker, shrinker->id);
3807e010df5SKirill Tkhai #endif
3811da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
3828e04944fSTetsuo Handa }
3838e04944fSTetsuo Handa 
3848e04944fSTetsuo Handa int register_shrinker(struct shrinker *shrinker)
3858e04944fSTetsuo Handa {
3868e04944fSTetsuo Handa 	int err = prealloc_shrinker(shrinker);
3878e04944fSTetsuo Handa 
3888e04944fSTetsuo Handa 	if (err)
3898e04944fSTetsuo Handa 		return err;
3908e04944fSTetsuo Handa 	register_shrinker_prepared(shrinker);
3911d3d4437SGlauber Costa 	return 0;
3921da177e4SLinus Torvalds }
3938e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
3941da177e4SLinus Torvalds 
3951da177e4SLinus Torvalds /*
3961da177e4SLinus Torvalds  * Remove one
3971da177e4SLinus Torvalds  */
3988e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
3991da177e4SLinus Torvalds {
400bb422a73STetsuo Handa 	if (!shrinker->nr_deferred)
401bb422a73STetsuo Handa 		return;
402b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
403b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
4041da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
4051da177e4SLinus Torvalds 	list_del(&shrinker->list);
4061da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
407ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
408bb422a73STetsuo Handa 	shrinker->nr_deferred = NULL;
4091da177e4SLinus Torvalds }
4108e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
4111da177e4SLinus Torvalds 
4121da177e4SLinus Torvalds #define SHRINK_BATCH 128
4131d3d4437SGlauber Costa 
414cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
4159092c71bSJosef Bacik 				    struct shrinker *shrinker, int priority)
4161da177e4SLinus Torvalds {
41724f7c6b9SDave Chinner 	unsigned long freed = 0;
4181da177e4SLinus Torvalds 	unsigned long long delta;
419635697c6SKonstantin Khlebnikov 	long total_scan;
420d5bc5fd3SVladimir Davydov 	long freeable;
421acf92b48SDave Chinner 	long nr;
422acf92b48SDave Chinner 	long new_nr;
4231d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
424e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
425e9299f50SDave Chinner 					  : SHRINK_BATCH;
4265f33a080SShaohua Li 	long scanned = 0, next_deferred;
4271da177e4SLinus Torvalds 
428ac7fb3adSKirill Tkhai 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
429ac7fb3adSKirill Tkhai 		nid = 0;
430ac7fb3adSKirill Tkhai 
431d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
4329b996468SKirill Tkhai 	if (freeable == 0 || freeable == SHRINK_EMPTY)
4339b996468SKirill Tkhai 		return freeable;
434635697c6SKonstantin Khlebnikov 
435acf92b48SDave Chinner 	/*
436acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
437acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
438acf92b48SDave Chinner 	 * don't also do this scanning work.
439acf92b48SDave Chinner 	 */
4401d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
441acf92b48SDave Chinner 
442acf92b48SDave Chinner 	total_scan = nr;
4434b85afbdSJohannes Weiner 	if (shrinker->seeks) {
4449092c71bSJosef Bacik 		delta = freeable >> priority;
4459092c71bSJosef Bacik 		delta *= 4;
4469092c71bSJosef Bacik 		do_div(delta, shrinker->seeks);
4474b85afbdSJohannes Weiner 	} else {
4484b85afbdSJohannes Weiner 		/*
4494b85afbdSJohannes Weiner 		 * These objects don't require any IO to create. Trim
4504b85afbdSJohannes Weiner 		 * them aggressively under memory pressure to keep
4514b85afbdSJohannes Weiner 		 * them from causing refetches in the IO caches.
4524b85afbdSJohannes Weiner 		 */
4534b85afbdSJohannes Weiner 		delta = freeable / 2;
4544b85afbdSJohannes Weiner 	}
455172b06c3SRoman Gushchin 
456acf92b48SDave Chinner 	total_scan += delta;
457acf92b48SDave Chinner 	if (total_scan < 0) {
458d75f773cSSakari Ailus 		pr_err("shrink_slab: %pS negative objects to delete nr=%ld\n",
459a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
460d5bc5fd3SVladimir Davydov 		total_scan = freeable;
4615f33a080SShaohua Li 		next_deferred = nr;
4625f33a080SShaohua Li 	} else
4635f33a080SShaohua Li 		next_deferred = total_scan;
464ea164d73SAndrea Arcangeli 
465ea164d73SAndrea Arcangeli 	/*
4663567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
4673567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
4683567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
4693567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
4703567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
471d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
4723567b59aSDave Chinner 	 * memory.
4733567b59aSDave Chinner 	 *
4743567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
4753567b59aSDave Chinner 	 * a large delta change is calculated directly.
4763567b59aSDave Chinner 	 */
477d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
478d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
4793567b59aSDave Chinner 
4803567b59aSDave Chinner 	/*
481ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
482ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
483ea164d73SAndrea Arcangeli 	 * freeable entries.
484ea164d73SAndrea Arcangeli 	 */
485d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
486d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
4871da177e4SLinus Torvalds 
48824f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
4899092c71bSJosef Bacik 				   freeable, delta, total_scan, priority);
49009576073SDave Chinner 
4910b1fb40aSVladimir Davydov 	/*
4920b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
4930b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
4940b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
4950b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
4960b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
4970b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
4980b1fb40aSVladimir Davydov 	 * batch_size.
4990b1fb40aSVladimir Davydov 	 *
5000b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
5010b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
502d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
5030b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
5040b1fb40aSVladimir Davydov 	 * possible.
5050b1fb40aSVladimir Davydov 	 */
5060b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
507d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
50824f7c6b9SDave Chinner 		unsigned long ret;
5090b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
5101da177e4SLinus Torvalds 
5110b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
512d460acb5SChris Wilson 		shrinkctl->nr_scanned = nr_to_scan;
51324f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
51424f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
5151da177e4SLinus Torvalds 			break;
51624f7c6b9SDave Chinner 		freed += ret;
51724f7c6b9SDave Chinner 
518d460acb5SChris Wilson 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
519d460acb5SChris Wilson 		total_scan -= shrinkctl->nr_scanned;
520d460acb5SChris Wilson 		scanned += shrinkctl->nr_scanned;
5211da177e4SLinus Torvalds 
5221da177e4SLinus Torvalds 		cond_resched();
5231da177e4SLinus Torvalds 	}
5241da177e4SLinus Torvalds 
5255f33a080SShaohua Li 	if (next_deferred >= scanned)
5265f33a080SShaohua Li 		next_deferred -= scanned;
5275f33a080SShaohua Li 	else
5285f33a080SShaohua Li 		next_deferred = 0;
529acf92b48SDave Chinner 	/*
530acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
531acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
532acf92b48SDave Chinner 	 * scan, there is no need to do an update.
533acf92b48SDave Chinner 	 */
5345f33a080SShaohua Li 	if (next_deferred > 0)
5355f33a080SShaohua Li 		new_nr = atomic_long_add_return(next_deferred,
5361d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
53783aeeadaSKonstantin Khlebnikov 	else
5381d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
539acf92b48SDave Chinner 
540df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
5411d3d4437SGlauber Costa 	return freed;
5421d3d4437SGlauber Costa }
5431d3d4437SGlauber Costa 
5440a432dcbSYang Shi #ifdef CONFIG_MEMCG
545b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
546b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
547b0dedc49SKirill Tkhai {
548b0dedc49SKirill Tkhai 	struct memcg_shrinker_map *map;
549b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
550b8e57efaSKirill Tkhai 	int i;
551b0dedc49SKirill Tkhai 
5520a432dcbSYang Shi 	if (!mem_cgroup_online(memcg))
553b0dedc49SKirill Tkhai 		return 0;
554b0dedc49SKirill Tkhai 
555b0dedc49SKirill Tkhai 	if (!down_read_trylock(&shrinker_rwsem))
556b0dedc49SKirill Tkhai 		return 0;
557b0dedc49SKirill Tkhai 
558b0dedc49SKirill Tkhai 	map = rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_map,
559b0dedc49SKirill Tkhai 					true);
560b0dedc49SKirill Tkhai 	if (unlikely(!map))
561b0dedc49SKirill Tkhai 		goto unlock;
562b0dedc49SKirill Tkhai 
563b0dedc49SKirill Tkhai 	for_each_set_bit(i, map->map, shrinker_nr_max) {
564b0dedc49SKirill Tkhai 		struct shrink_control sc = {
565b0dedc49SKirill Tkhai 			.gfp_mask = gfp_mask,
566b0dedc49SKirill Tkhai 			.nid = nid,
567b0dedc49SKirill Tkhai 			.memcg = memcg,
568b0dedc49SKirill Tkhai 		};
569b0dedc49SKirill Tkhai 		struct shrinker *shrinker;
570b0dedc49SKirill Tkhai 
571b0dedc49SKirill Tkhai 		shrinker = idr_find(&shrinker_idr, i);
5727e010df5SKirill Tkhai 		if (unlikely(!shrinker || shrinker == SHRINKER_REGISTERING)) {
5737e010df5SKirill Tkhai 			if (!shrinker)
574b0dedc49SKirill Tkhai 				clear_bit(i, map->map);
575b0dedc49SKirill Tkhai 			continue;
576b0dedc49SKirill Tkhai 		}
577b0dedc49SKirill Tkhai 
5780a432dcbSYang Shi 		/* Call non-slab shrinkers even though kmem is disabled */
5790a432dcbSYang Shi 		if (!memcg_kmem_enabled() &&
5800a432dcbSYang Shi 		    !(shrinker->flags & SHRINKER_NONSLAB))
5810a432dcbSYang Shi 			continue;
5820a432dcbSYang Shi 
583b0dedc49SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
584f90280d6SKirill Tkhai 		if (ret == SHRINK_EMPTY) {
585f90280d6SKirill Tkhai 			clear_bit(i, map->map);
586f90280d6SKirill Tkhai 			/*
587f90280d6SKirill Tkhai 			 * After the shrinker reported that it had no objects to
588f90280d6SKirill Tkhai 			 * free, but before we cleared the corresponding bit in
589f90280d6SKirill Tkhai 			 * the memcg shrinker map, a new object might have been
590f90280d6SKirill Tkhai 			 * added. To make sure, we have the bit set in this
591f90280d6SKirill Tkhai 			 * case, we invoke the shrinker one more time and reset
592f90280d6SKirill Tkhai 			 * the bit if it reports that it is not empty anymore.
593f90280d6SKirill Tkhai 			 * The memory barrier here pairs with the barrier in
594f90280d6SKirill Tkhai 			 * memcg_set_shrinker_bit():
595f90280d6SKirill Tkhai 			 *
596f90280d6SKirill Tkhai 			 * list_lru_add()     shrink_slab_memcg()
597f90280d6SKirill Tkhai 			 *   list_add_tail()    clear_bit()
598f90280d6SKirill Tkhai 			 *   <MB>               <MB>
599f90280d6SKirill Tkhai 			 *   set_bit()          do_shrink_slab()
600f90280d6SKirill Tkhai 			 */
601f90280d6SKirill Tkhai 			smp_mb__after_atomic();
602f90280d6SKirill Tkhai 			ret = do_shrink_slab(&sc, shrinker, priority);
6039b996468SKirill Tkhai 			if (ret == SHRINK_EMPTY)
6049b996468SKirill Tkhai 				ret = 0;
605f90280d6SKirill Tkhai 			else
606f90280d6SKirill Tkhai 				memcg_set_shrinker_bit(memcg, nid, i);
607f90280d6SKirill Tkhai 		}
608b0dedc49SKirill Tkhai 		freed += ret;
609b0dedc49SKirill Tkhai 
610b0dedc49SKirill Tkhai 		if (rwsem_is_contended(&shrinker_rwsem)) {
611b0dedc49SKirill Tkhai 			freed = freed ? : 1;
612b0dedc49SKirill Tkhai 			break;
613b0dedc49SKirill Tkhai 		}
614b0dedc49SKirill Tkhai 	}
615b0dedc49SKirill Tkhai unlock:
616b0dedc49SKirill Tkhai 	up_read(&shrinker_rwsem);
617b0dedc49SKirill Tkhai 	return freed;
618b0dedc49SKirill Tkhai }
6190a432dcbSYang Shi #else /* CONFIG_MEMCG */
620b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
621b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
622b0dedc49SKirill Tkhai {
623b0dedc49SKirill Tkhai 	return 0;
624b0dedc49SKirill Tkhai }
6250a432dcbSYang Shi #endif /* CONFIG_MEMCG */
626b0dedc49SKirill Tkhai 
6276b4f7799SJohannes Weiner /**
628cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
6296b4f7799SJohannes Weiner  * @gfp_mask: allocation context
6306b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
631cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
6329092c71bSJosef Bacik  * @priority: the reclaim priority
6331d3d4437SGlauber Costa  *
6346b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
6351d3d4437SGlauber Costa  *
6366b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
6376b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
6381d3d4437SGlauber Costa  *
639aeed1d32SVladimir Davydov  * @memcg specifies the memory cgroup to target. Unaware shrinkers
640aeed1d32SVladimir Davydov  * are called only if it is the root cgroup.
641cb731d6cSVladimir Davydov  *
6429092c71bSJosef Bacik  * @priority is sc->priority, we take the number of objects and >> by priority
6439092c71bSJosef Bacik  * in order to get the scan target.
6441d3d4437SGlauber Costa  *
6456b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
6461d3d4437SGlauber Costa  */
647cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
648cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
6499092c71bSJosef Bacik 				 int priority)
6501d3d4437SGlauber Costa {
651b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
6521d3d4437SGlauber Costa 	struct shrinker *shrinker;
6531d3d4437SGlauber Costa 
654fa1e512fSYang Shi 	/*
655fa1e512fSYang Shi 	 * The root memcg might be allocated even though memcg is disabled
656fa1e512fSYang Shi 	 * via "cgroup_disable=memory" boot parameter.  This could make
657fa1e512fSYang Shi 	 * mem_cgroup_is_root() return false, then just run memcg slab
658fa1e512fSYang Shi 	 * shrink, but skip global shrink.  This may result in premature
659fa1e512fSYang Shi 	 * oom.
660fa1e512fSYang Shi 	 */
661fa1e512fSYang Shi 	if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
662b0dedc49SKirill Tkhai 		return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
663cb731d6cSVladimir Davydov 
664e830c63aSTetsuo Handa 	if (!down_read_trylock(&shrinker_rwsem))
6651d3d4437SGlauber Costa 		goto out;
6661d3d4437SGlauber Costa 
6671d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
6686b4f7799SJohannes Weiner 		struct shrink_control sc = {
6696b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
6706b4f7799SJohannes Weiner 			.nid = nid,
671cb731d6cSVladimir Davydov 			.memcg = memcg,
6726b4f7799SJohannes Weiner 		};
6736b4f7799SJohannes Weiner 
6749b996468SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
6759b996468SKirill Tkhai 		if (ret == SHRINK_EMPTY)
6769b996468SKirill Tkhai 			ret = 0;
6779b996468SKirill Tkhai 		freed += ret;
678e496612cSMinchan Kim 		/*
679e496612cSMinchan Kim 		 * Bail out if someone want to register a new shrinker to
680e496612cSMinchan Kim 		 * prevent the regsitration from being stalled for long periods
681e496612cSMinchan Kim 		 * by parallel ongoing shrinking.
682e496612cSMinchan Kim 		 */
683e496612cSMinchan Kim 		if (rwsem_is_contended(&shrinker_rwsem)) {
684e496612cSMinchan Kim 			freed = freed ? : 1;
685e496612cSMinchan Kim 			break;
686e496612cSMinchan Kim 		}
687ec97097bSVladimir Davydov 	}
6881d3d4437SGlauber Costa 
6891da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
690f06590bdSMinchan Kim out:
691f06590bdSMinchan Kim 	cond_resched();
69224f7c6b9SDave Chinner 	return freed;
6931da177e4SLinus Torvalds }
6941da177e4SLinus Torvalds 
695cb731d6cSVladimir Davydov void drop_slab_node(int nid)
696cb731d6cSVladimir Davydov {
697cb731d6cSVladimir Davydov 	unsigned long freed;
698cb731d6cSVladimir Davydov 
699cb731d6cSVladimir Davydov 	do {
700cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
701cb731d6cSVladimir Davydov 
702cb731d6cSVladimir Davydov 		freed = 0;
703aeed1d32SVladimir Davydov 		memcg = mem_cgroup_iter(NULL, NULL, NULL);
704cb731d6cSVladimir Davydov 		do {
7059092c71bSJosef Bacik 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
706cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
707cb731d6cSVladimir Davydov 	} while (freed > 10);
708cb731d6cSVladimir Davydov }
709cb731d6cSVladimir Davydov 
710cb731d6cSVladimir Davydov void drop_slab(void)
711cb731d6cSVladimir Davydov {
712cb731d6cSVladimir Davydov 	int nid;
713cb731d6cSVladimir Davydov 
714cb731d6cSVladimir Davydov 	for_each_online_node(nid)
715cb731d6cSVladimir Davydov 		drop_slab_node(nid);
716cb731d6cSVladimir Davydov }
717cb731d6cSVladimir Davydov 
7181da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
7191da177e4SLinus Torvalds {
720ceddc3a5SJohannes Weiner 	/*
721ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
72267891fffSMatthew Wilcox 	 * that isolated the page, the page cache and optional buffer
72367891fffSMatthew Wilcox 	 * heads at page->private.
724ceddc3a5SJohannes Weiner 	 */
72567891fffSMatthew Wilcox 	int page_cache_pins = PageTransHuge(page) && PageSwapCache(page) ?
726bd4c82c2SHuang Ying 		HPAGE_PMD_NR : 1;
72767891fffSMatthew Wilcox 	return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
7281da177e4SLinus Torvalds }
7291da177e4SLinus Torvalds 
730cb16556dSYang Shi static int may_write_to_inode(struct inode *inode)
7311da177e4SLinus Torvalds {
732930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
7331da177e4SLinus Torvalds 		return 1;
734703c2708STejun Heo 	if (!inode_write_congested(inode))
7351da177e4SLinus Torvalds 		return 1;
736703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
7371da177e4SLinus Torvalds 		return 1;
7381da177e4SLinus Torvalds 	return 0;
7391da177e4SLinus Torvalds }
7401da177e4SLinus Torvalds 
7411da177e4SLinus Torvalds /*
7421da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
7431da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
7441da177e4SLinus Torvalds  * fsync(), msync() or close().
7451da177e4SLinus Torvalds  *
7461da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
7471da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
7481da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
7491da177e4SLinus Torvalds  *
7501da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
7511da177e4SLinus Torvalds  * __GFP_FS.
7521da177e4SLinus Torvalds  */
7531da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
7541da177e4SLinus Torvalds 				struct page *page, int error)
7551da177e4SLinus Torvalds {
7567eaceaccSJens Axboe 	lock_page(page);
7573e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
7583e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
7591da177e4SLinus Torvalds 	unlock_page(page);
7601da177e4SLinus Torvalds }
7611da177e4SLinus Torvalds 
76204e62a29SChristoph Lameter /* possible outcome of pageout() */
76304e62a29SChristoph Lameter typedef enum {
76404e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
76504e62a29SChristoph Lameter 	PAGE_KEEP,
76604e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
76704e62a29SChristoph Lameter 	PAGE_ACTIVATE,
76804e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
76904e62a29SChristoph Lameter 	PAGE_SUCCESS,
77004e62a29SChristoph Lameter 	/* page is clean and locked */
77104e62a29SChristoph Lameter 	PAGE_CLEAN,
77204e62a29SChristoph Lameter } pageout_t;
77304e62a29SChristoph Lameter 
7741da177e4SLinus Torvalds /*
7751742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
7761742f19fSAndrew Morton  * Calls ->writepage().
7771da177e4SLinus Torvalds  */
778cb16556dSYang Shi static pageout_t pageout(struct page *page, struct address_space *mapping)
7791da177e4SLinus Torvalds {
7801da177e4SLinus Torvalds 	/*
7811da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
7821da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
7831da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
7841da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
7851da177e4SLinus Torvalds 	 * PagePrivate for that.
7861da177e4SLinus Torvalds 	 *
7878174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
7881da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
7891da177e4SLinus Torvalds 	 * will block.
7901da177e4SLinus Torvalds 	 *
7911da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
7921da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
7931da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
7941da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
7951da177e4SLinus Torvalds 	 */
7961da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
7971da177e4SLinus Torvalds 		return PAGE_KEEP;
7981da177e4SLinus Torvalds 	if (!mapping) {
7991da177e4SLinus Torvalds 		/*
8001da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
8011da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
8021da177e4SLinus Torvalds 		 */
803266cf658SDavid Howells 		if (page_has_private(page)) {
8041da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
8051da177e4SLinus Torvalds 				ClearPageDirty(page);
806b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
8071da177e4SLinus Torvalds 				return PAGE_CLEAN;
8081da177e4SLinus Torvalds 			}
8091da177e4SLinus Torvalds 		}
8101da177e4SLinus Torvalds 		return PAGE_KEEP;
8111da177e4SLinus Torvalds 	}
8121da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
8131da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
814cb16556dSYang Shi 	if (!may_write_to_inode(mapping->host))
8151da177e4SLinus Torvalds 		return PAGE_KEEP;
8161da177e4SLinus Torvalds 
8171da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
8181da177e4SLinus Torvalds 		int res;
8191da177e4SLinus Torvalds 		struct writeback_control wbc = {
8201da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
8211da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
822111ebb6eSOGAWA Hirofumi 			.range_start = 0,
823111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
8241da177e4SLinus Torvalds 			.for_reclaim = 1,
8251da177e4SLinus Torvalds 		};
8261da177e4SLinus Torvalds 
8271da177e4SLinus Torvalds 		SetPageReclaim(page);
8281da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
8291da177e4SLinus Torvalds 		if (res < 0)
8301da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
831994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
8321da177e4SLinus Torvalds 			ClearPageReclaim(page);
8331da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
8341da177e4SLinus Torvalds 		}
835c661b078SAndy Whitcroft 
8361da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
8371da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
8381da177e4SLinus Torvalds 			ClearPageReclaim(page);
8391da177e4SLinus Torvalds 		}
8403aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
841c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
8421da177e4SLinus Torvalds 		return PAGE_SUCCESS;
8431da177e4SLinus Torvalds 	}
8441da177e4SLinus Torvalds 
8451da177e4SLinus Torvalds 	return PAGE_CLEAN;
8461da177e4SLinus Torvalds }
8471da177e4SLinus Torvalds 
848a649fd92SAndrew Morton /*
849e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
850e286781dSNick Piggin  * gets returned with a refcount of 0.
851a649fd92SAndrew Morton  */
852a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
853a528910eSJohannes Weiner 			    bool reclaimed)
85449d2e9ccSChristoph Lameter {
855c4843a75SGreg Thelen 	unsigned long flags;
856bd4c82c2SHuang Ying 	int refcount;
857c4843a75SGreg Thelen 
85828e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
85928e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
86049d2e9ccSChristoph Lameter 
861b93b0163SMatthew Wilcox 	xa_lock_irqsave(&mapping->i_pages, flags);
86249d2e9ccSChristoph Lameter 	/*
8630fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
8640fd0e6b0SNick Piggin 	 *
8650fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
8660fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
8670fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
8680fd0e6b0SNick Piggin 	 * here, then the following race may occur:
8690fd0e6b0SNick Piggin 	 *
8700fd0e6b0SNick Piggin 	 * get_user_pages(&page);
8710fd0e6b0SNick Piggin 	 * [user mapping goes away]
8720fd0e6b0SNick Piggin 	 * write_to(page);
8730fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
8740fd0e6b0SNick Piggin 	 * SetPageDirty(page);
8750fd0e6b0SNick Piggin 	 * put_page(page);
8760fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
8770fd0e6b0SNick Piggin 	 *
8780fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
8790fd0e6b0SNick Piggin 	 *
8800fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
8810fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
8820139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
8830fd0e6b0SNick Piggin 	 *
8840fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
885b93b0163SMatthew Wilcox 	 * and thus under the i_pages lock, then this ordering is not required.
88649d2e9ccSChristoph Lameter 	 */
887906d278dSWilliam Kucharski 	refcount = 1 + compound_nr(page);
888bd4c82c2SHuang Ying 	if (!page_ref_freeze(page, refcount))
88949d2e9ccSChristoph Lameter 		goto cannot_free;
8901c4c3b99SJiang Biao 	/* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
891e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
892bd4c82c2SHuang Ying 		page_ref_unfreeze(page, refcount);
89349d2e9ccSChristoph Lameter 		goto cannot_free;
894e286781dSNick Piggin 	}
89549d2e9ccSChristoph Lameter 
89649d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
89749d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
8980a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
8994e17ec25SMatthew Wilcox 		__delete_from_swap_cache(page, swap);
900b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
90175f6d6d2SMinchan Kim 		put_swap_page(page, swap);
902e286781dSNick Piggin 	} else {
9036072d13cSLinus Torvalds 		void (*freepage)(struct page *);
904a528910eSJohannes Weiner 		void *shadow = NULL;
9056072d13cSLinus Torvalds 
9066072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
907a528910eSJohannes Weiner 		/*
908a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
909a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
910a528910eSJohannes Weiner 		 *
911a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
912a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
913a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
914a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
915a528910eSJohannes Weiner 		 * back.
916f9fe48beSRoss Zwisler 		 *
917f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
918f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
919f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
920f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
921b93b0163SMatthew Wilcox 		 * same address_space.
922a528910eSJohannes Weiner 		 */
923a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
924f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
925a7ca12f9SAndrey Ryabinin 			shadow = workingset_eviction(page);
92662cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
927b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
9286072d13cSLinus Torvalds 
9296072d13cSLinus Torvalds 		if (freepage != NULL)
9306072d13cSLinus Torvalds 			freepage(page);
931e286781dSNick Piggin 	}
932e286781dSNick Piggin 
93349d2e9ccSChristoph Lameter 	return 1;
93449d2e9ccSChristoph Lameter 
93549d2e9ccSChristoph Lameter cannot_free:
936b93b0163SMatthew Wilcox 	xa_unlock_irqrestore(&mapping->i_pages, flags);
93749d2e9ccSChristoph Lameter 	return 0;
93849d2e9ccSChristoph Lameter }
93949d2e9ccSChristoph Lameter 
9401da177e4SLinus Torvalds /*
941e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
942e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
943e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
944e286781dSNick Piggin  * this page.
945e286781dSNick Piggin  */
946e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
947e286781dSNick Piggin {
948a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
949e286781dSNick Piggin 		/*
950e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
951e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
952e286781dSNick Piggin 		 * atomic operation.
953e286781dSNick Piggin 		 */
954fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
955e286781dSNick Piggin 		return 1;
956e286781dSNick Piggin 	}
957e286781dSNick Piggin 	return 0;
958e286781dSNick Piggin }
959e286781dSNick Piggin 
960894bc310SLee Schermerhorn /**
961894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
962894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
963894bc310SLee Schermerhorn  *
964894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
965894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
966894bc310SLee Schermerhorn  *
967894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
968894bc310SLee Schermerhorn  */
969894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
970894bc310SLee Schermerhorn {
971c53954a0SMel Gorman 	lru_cache_add(page);
972894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
973894bc310SLee Schermerhorn }
974894bc310SLee Schermerhorn 
975dfc8d636SJohannes Weiner enum page_references {
976dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
977dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
97864574746SJohannes Weiner 	PAGEREF_KEEP,
979dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
980dfc8d636SJohannes Weiner };
981dfc8d636SJohannes Weiner 
982dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
983dfc8d636SJohannes Weiner 						  struct scan_control *sc)
984dfc8d636SJohannes Weiner {
98564574746SJohannes Weiner 	int referenced_ptes, referenced_page;
986dfc8d636SJohannes Weiner 	unsigned long vm_flags;
987dfc8d636SJohannes Weiner 
988c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
989c3ac9a8aSJohannes Weiner 					  &vm_flags);
99064574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
991dfc8d636SJohannes Weiner 
992dfc8d636SJohannes Weiner 	/*
993dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
994dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
995dfc8d636SJohannes Weiner 	 */
996dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
997dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
998dfc8d636SJohannes Weiner 
99964574746SJohannes Weiner 	if (referenced_ptes) {
1000e4898273SMichal Hocko 		if (PageSwapBacked(page))
100164574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
100264574746SJohannes Weiner 		/*
100364574746SJohannes Weiner 		 * All mapped pages start out with page table
100464574746SJohannes Weiner 		 * references from the instantiating fault, so we need
100564574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
100664574746SJohannes Weiner 		 * than once.
100764574746SJohannes Weiner 		 *
100864574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
100964574746SJohannes Weiner 		 * inactive list.  Another page table reference will
101064574746SJohannes Weiner 		 * lead to its activation.
101164574746SJohannes Weiner 		 *
101264574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
101364574746SJohannes Weiner 		 * so that recently deactivated but used pages are
101464574746SJohannes Weiner 		 * quickly recovered.
101564574746SJohannes Weiner 		 */
101664574746SJohannes Weiner 		SetPageReferenced(page);
101764574746SJohannes Weiner 
101834dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
1019dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
1020dfc8d636SJohannes Weiner 
1021c909e993SKonstantin Khlebnikov 		/*
1022c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
1023c909e993SKonstantin Khlebnikov 		 */
1024c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
1025c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
1026c909e993SKonstantin Khlebnikov 
102764574746SJohannes Weiner 		return PAGEREF_KEEP;
102864574746SJohannes Weiner 	}
102964574746SJohannes Weiner 
1030dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
10312e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
1032dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
103364574746SJohannes Weiner 
103464574746SJohannes Weiner 	return PAGEREF_RECLAIM;
1035dfc8d636SJohannes Weiner }
1036dfc8d636SJohannes Weiner 
1037e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
1038e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
1039e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
1040e2be15f6SMel Gorman {
1041b4597226SMel Gorman 	struct address_space *mapping;
1042b4597226SMel Gorman 
1043e2be15f6SMel Gorman 	/*
1044e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
1045e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
1046e2be15f6SMel Gorman 	 */
1047802a3a92SShaohua Li 	if (!page_is_file_cache(page) ||
1048802a3a92SShaohua Li 	    (PageAnon(page) && !PageSwapBacked(page))) {
1049e2be15f6SMel Gorman 		*dirty = false;
1050e2be15f6SMel Gorman 		*writeback = false;
1051e2be15f6SMel Gorman 		return;
1052e2be15f6SMel Gorman 	}
1053e2be15f6SMel Gorman 
1054e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
1055e2be15f6SMel Gorman 	*dirty = PageDirty(page);
1056e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
1057b4597226SMel Gorman 
1058b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
1059b4597226SMel Gorman 	if (!page_has_private(page))
1060b4597226SMel Gorman 		return;
1061b4597226SMel Gorman 
1062b4597226SMel Gorman 	mapping = page_mapping(page);
1063b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
1064b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1065e2be15f6SMel Gorman }
1066e2be15f6SMel Gorman 
1067e286781dSNick Piggin /*
10681742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
10691da177e4SLinus Torvalds  */
10701742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
1071599d0c95SMel Gorman 				      struct pglist_data *pgdat,
1072f84f6e2bSMel Gorman 				      struct scan_control *sc,
107302c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
10743c710c1aSMichal Hocko 				      struct reclaim_stat *stat,
10758940b34aSMinchan Kim 				      bool ignore_references)
10761da177e4SLinus Torvalds {
10771da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
1078abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
10793c710c1aSMichal Hocko 	unsigned nr_reclaimed = 0;
1080886cf190SKirill Tkhai 	unsigned pgactivate = 0;
10811da177e4SLinus Torvalds 
1082060f005fSKirill Tkhai 	memset(stat, 0, sizeof(*stat));
10831da177e4SLinus Torvalds 	cond_resched();
10841da177e4SLinus Torvalds 
10851da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
10861da177e4SLinus Torvalds 		struct address_space *mapping;
10871da177e4SLinus Torvalds 		struct page *page;
10881da177e4SLinus Torvalds 		int may_enter_fs;
10898940b34aSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM;
1090e2be15f6SMel Gorman 		bool dirty, writeback;
109198879b3bSYang Shi 		unsigned int nr_pages;
10921da177e4SLinus Torvalds 
10931da177e4SLinus Torvalds 		cond_resched();
10941da177e4SLinus Torvalds 
10951da177e4SLinus Torvalds 		page = lru_to_page(page_list);
10961da177e4SLinus Torvalds 		list_del(&page->lru);
10971da177e4SLinus Torvalds 
1098529ae9aaSNick Piggin 		if (!trylock_page(page))
10991da177e4SLinus Torvalds 			goto keep;
11001da177e4SLinus Torvalds 
1101309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
11021da177e4SLinus Torvalds 
1103d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
110498879b3bSYang Shi 
110598879b3bSYang Shi 		/* Account the number of base pages even though THP */
110698879b3bSYang Shi 		sc->nr_scanned += nr_pages;
110780e43426SChristoph Lameter 
110839b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
1109ad6b6704SMinchan Kim 			goto activate_locked;
1110894bc310SLee Schermerhorn 
1111a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
111280e43426SChristoph Lameter 			goto keep_locked;
111380e43426SChristoph Lameter 
1114c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1115c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1116c661b078SAndy Whitcroft 
1117e62e384eSMichal Hocko 		/*
1118894befecSAndrey Ryabinin 		 * The number of dirty pages determines if a node is marked
1119e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
1120e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
1121e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
1122e2be15f6SMel Gorman 		 */
1123e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
1124e2be15f6SMel Gorman 		if (dirty || writeback)
1125060f005fSKirill Tkhai 			stat->nr_dirty++;
1126e2be15f6SMel Gorman 
1127e2be15f6SMel Gorman 		if (dirty && !writeback)
1128060f005fSKirill Tkhai 			stat->nr_unqueued_dirty++;
1129e2be15f6SMel Gorman 
1130d04e8acdSMel Gorman 		/*
1131d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
1132d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
1133d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
1134d04e8acdSMel Gorman 		 * end of the LRU a second time.
1135d04e8acdSMel Gorman 		 */
1136e2be15f6SMel Gorman 		mapping = page_mapping(page);
11371da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
1138703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
1139d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
1140060f005fSKirill Tkhai 			stat->nr_congested++;
1141e2be15f6SMel Gorman 
1142e2be15f6SMel Gorman 		/*
1143283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
1144283aba9fSMel Gorman 		 * are three cases to consider.
1145e62e384eSMichal Hocko 		 *
1146283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
1147283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
1148283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
1149283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
1150283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
1151283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
1152283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
1153b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
1154b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
1155c3b94f44SHugh Dickins 		 *
115697c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
1157ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1158ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1159ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
116097c9341fSTejun Heo 		 *    reclaim and continue scanning.
1161283aba9fSMel Gorman 		 *
1162ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1163ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1164283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1165283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1166283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1167283aba9fSMel Gorman 		 *    would probably show more reasons.
1168283aba9fSMel Gorman 		 *
11697fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1170283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1171283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1172283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1173283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1174c55e8d03SJohannes Weiner 		 *
1175c55e8d03SJohannes Weiner 		 * In cases 1) and 2) we activate the pages to get them out of
1176c55e8d03SJohannes Weiner 		 * the way while we continue scanning for clean pages on the
1177c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1178c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1179c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1180c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1181c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1182c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1183e62e384eSMichal Hocko 		 */
1184283aba9fSMel Gorman 		if (PageWriteback(page)) {
1185283aba9fSMel Gorman 			/* Case 1 above */
1186283aba9fSMel Gorman 			if (current_is_kswapd() &&
1187283aba9fSMel Gorman 			    PageReclaim(page) &&
1188599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1189060f005fSKirill Tkhai 				stat->nr_immediate++;
1190c55e8d03SJohannes Weiner 				goto activate_locked;
1191283aba9fSMel Gorman 
1192283aba9fSMel Gorman 			/* Case 2 above */
1193b5ead35eSJohannes Weiner 			} else if (writeback_throttling_sane(sc) ||
1194ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1195c3b94f44SHugh Dickins 				/*
1196c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1197c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1198c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1199c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1200c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1201c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1202c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1203c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1204c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1205c3b94f44SHugh Dickins 				 */
1206c3b94f44SHugh Dickins 				SetPageReclaim(page);
1207060f005fSKirill Tkhai 				stat->nr_writeback++;
1208c55e8d03SJohannes Weiner 				goto activate_locked;
1209283aba9fSMel Gorman 
1210283aba9fSMel Gorman 			/* Case 3 above */
1211283aba9fSMel Gorman 			} else {
12127fadc820SHugh Dickins 				unlock_page(page);
1213c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
12147fadc820SHugh Dickins 				/* then go back and try same page again */
12157fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
12167fadc820SHugh Dickins 				continue;
1217e62e384eSMichal Hocko 			}
1218283aba9fSMel Gorman 		}
12191da177e4SLinus Torvalds 
12208940b34aSMinchan Kim 		if (!ignore_references)
12216a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
122202c6de8dSMinchan Kim 
1223dfc8d636SJohannes Weiner 		switch (references) {
1224dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
12251da177e4SLinus Torvalds 			goto activate_locked;
122664574746SJohannes Weiner 		case PAGEREF_KEEP:
122798879b3bSYang Shi 			stat->nr_ref_keep += nr_pages;
122864574746SJohannes Weiner 			goto keep_locked;
1229dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1230dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1231dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1232dfc8d636SJohannes Weiner 		}
12331da177e4SLinus Torvalds 
12341da177e4SLinus Torvalds 		/*
12351da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
12361da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1237802a3a92SShaohua Li 		 * Lazyfree page could be freed directly
12381da177e4SLinus Torvalds 		 */
1239bd4c82c2SHuang Ying 		if (PageAnon(page) && PageSwapBacked(page)) {
1240bd4c82c2SHuang Ying 			if (!PageSwapCache(page)) {
124163eb6b93SHugh Dickins 				if (!(sc->gfp_mask & __GFP_IO))
124263eb6b93SHugh Dickins 					goto keep_locked;
1243747552b1SHuang Ying 				if (PageTransHuge(page)) {
1244b8f593cdSHuang Ying 					/* cannot split THP, skip it */
1245747552b1SHuang Ying 					if (!can_split_huge_page(page, NULL))
1246b8f593cdSHuang Ying 						goto activate_locked;
1247747552b1SHuang Ying 					/*
1248747552b1SHuang Ying 					 * Split pages without a PMD map right
1249747552b1SHuang Ying 					 * away. Chances are some or all of the
1250747552b1SHuang Ying 					 * tail pages can be freed without IO.
1251747552b1SHuang Ying 					 */
1252747552b1SHuang Ying 					if (!compound_mapcount(page) &&
1253bd4c82c2SHuang Ying 					    split_huge_page_to_list(page,
1254bd4c82c2SHuang Ying 								    page_list))
1255747552b1SHuang Ying 						goto activate_locked;
1256747552b1SHuang Ying 				}
12570f074658SMinchan Kim 				if (!add_to_swap(page)) {
12580f074658SMinchan Kim 					if (!PageTransHuge(page))
125998879b3bSYang Shi 						goto activate_locked_split;
1260bd4c82c2SHuang Ying 					/* Fallback to swap normal pages */
1261bd4c82c2SHuang Ying 					if (split_huge_page_to_list(page,
1262bd4c82c2SHuang Ying 								    page_list))
12630f074658SMinchan Kim 						goto activate_locked;
1264fe490cc0SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1265fe490cc0SHuang Ying 					count_vm_event(THP_SWPOUT_FALLBACK);
1266fe490cc0SHuang Ying #endif
12670f074658SMinchan Kim 					if (!add_to_swap(page))
126898879b3bSYang Shi 						goto activate_locked_split;
12690f074658SMinchan Kim 				}
12700f074658SMinchan Kim 
127163eb6b93SHugh Dickins 				may_enter_fs = 1;
12721da177e4SLinus Torvalds 
1273e2be15f6SMel Gorman 				/* Adding to swap updated mapping */
12741da177e4SLinus Torvalds 				mapping = page_mapping(page);
1275bd4c82c2SHuang Ying 			}
12767751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
12777751b2daSKirill A. Shutemov 			/* Split file THP */
12787751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
12797751b2daSKirill A. Shutemov 				goto keep_locked;
1280e2be15f6SMel Gorman 		}
12811da177e4SLinus Torvalds 
12821da177e4SLinus Torvalds 		/*
128398879b3bSYang Shi 		 * THP may get split above, need minus tail pages and update
128498879b3bSYang Shi 		 * nr_pages to avoid accounting tail pages twice.
128598879b3bSYang Shi 		 *
128698879b3bSYang Shi 		 * The tail pages that are added into swap cache successfully
128798879b3bSYang Shi 		 * reach here.
128898879b3bSYang Shi 		 */
128998879b3bSYang Shi 		if ((nr_pages > 1) && !PageTransHuge(page)) {
129098879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
129198879b3bSYang Shi 			nr_pages = 1;
129298879b3bSYang Shi 		}
129398879b3bSYang Shi 
129498879b3bSYang Shi 		/*
12951da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
12961da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
12971da177e4SLinus Torvalds 		 */
1298802a3a92SShaohua Li 		if (page_mapped(page)) {
1299bd4c82c2SHuang Ying 			enum ttu_flags flags = ttu_flags | TTU_BATCH_FLUSH;
1300bd4c82c2SHuang Ying 
1301bd4c82c2SHuang Ying 			if (unlikely(PageTransHuge(page)))
1302bd4c82c2SHuang Ying 				flags |= TTU_SPLIT_HUGE_PMD;
1303bd4c82c2SHuang Ying 			if (!try_to_unmap(page, flags)) {
130498879b3bSYang Shi 				stat->nr_unmap_fail += nr_pages;
13051da177e4SLinus Torvalds 				goto activate_locked;
13061da177e4SLinus Torvalds 			}
13071da177e4SLinus Torvalds 		}
13081da177e4SLinus Torvalds 
13091da177e4SLinus Torvalds 		if (PageDirty(page)) {
1310ee72886dSMel Gorman 			/*
13114eda4823SJohannes Weiner 			 * Only kswapd can writeback filesystem pages
13124eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
13134eda4823SJohannes Weiner 			 * injecting inefficient single-page IO into
13144eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
13154eda4823SJohannes Weiner 			 * write pages when we've encountered many
13164eda4823SJohannes Weiner 			 * dirty pages, and when we've already scanned
13174eda4823SJohannes Weiner 			 * the rest of the LRU for clean pages and see
13184eda4823SJohannes Weiner 			 * the same dirty pages again (PageReclaim).
1319ee72886dSMel Gorman 			 */
1320f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
13214eda4823SJohannes Weiner 			    (!current_is_kswapd() || !PageReclaim(page) ||
1322599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
132349ea7eb6SMel Gorman 				/*
132449ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
132549ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
132649ea7eb6SMel Gorman 				 * except we already have the page isolated
132749ea7eb6SMel Gorman 				 * and know it's dirty
132849ea7eb6SMel Gorman 				 */
1329c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
133049ea7eb6SMel Gorman 				SetPageReclaim(page);
133149ea7eb6SMel Gorman 
1332c55e8d03SJohannes Weiner 				goto activate_locked;
1333ee72886dSMel Gorman 			}
1334ee72886dSMel Gorman 
1335dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
13361da177e4SLinus Torvalds 				goto keep_locked;
13374dd4b920SAndrew Morton 			if (!may_enter_fs)
13381da177e4SLinus Torvalds 				goto keep_locked;
133952a8363eSChristoph Lameter 			if (!sc->may_writepage)
13401da177e4SLinus Torvalds 				goto keep_locked;
13411da177e4SLinus Torvalds 
1342d950c947SMel Gorman 			/*
1343d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1344d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1345d950c947SMel Gorman 			 * starts and then write it out here.
1346d950c947SMel Gorman 			 */
1347d950c947SMel Gorman 			try_to_unmap_flush_dirty();
1348cb16556dSYang Shi 			switch (pageout(page, mapping)) {
13491da177e4SLinus Torvalds 			case PAGE_KEEP:
13501da177e4SLinus Torvalds 				goto keep_locked;
13511da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
13521da177e4SLinus Torvalds 				goto activate_locked;
13531da177e4SLinus Torvalds 			case PAGE_SUCCESS:
13547d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
135541ac1999SMel Gorman 					goto keep;
13567d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
13571da177e4SLinus Torvalds 					goto keep;
13587d3579e8SKOSAKI Motohiro 
13591da177e4SLinus Torvalds 				/*
13601da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
13611da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
13621da177e4SLinus Torvalds 				 */
1363529ae9aaSNick Piggin 				if (!trylock_page(page))
13641da177e4SLinus Torvalds 					goto keep;
13651da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
13661da177e4SLinus Torvalds 					goto keep_locked;
13671da177e4SLinus Torvalds 				mapping = page_mapping(page);
13681da177e4SLinus Torvalds 			case PAGE_CLEAN:
13691da177e4SLinus Torvalds 				; /* try to free the page below */
13701da177e4SLinus Torvalds 			}
13711da177e4SLinus Torvalds 		}
13721da177e4SLinus Torvalds 
13731da177e4SLinus Torvalds 		/*
13741da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
13751da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
13761da177e4SLinus Torvalds 		 * the page as well.
13771da177e4SLinus Torvalds 		 *
13781da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
13791da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
13801da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
13811da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
13821da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
13831da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
13841da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
13851da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
13861da177e4SLinus Torvalds 		 *
13871da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
13881da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
13891da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
13901da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
13911da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
13921da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
13931da177e4SLinus Torvalds 		 */
1394266cf658SDavid Howells 		if (page_has_private(page)) {
13951da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
13961da177e4SLinus Torvalds 				goto activate_locked;
1397e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1398e286781dSNick Piggin 				unlock_page(page);
1399e286781dSNick Piggin 				if (put_page_testzero(page))
14001da177e4SLinus Torvalds 					goto free_it;
1401e286781dSNick Piggin 				else {
1402e286781dSNick Piggin 					/*
1403e286781dSNick Piggin 					 * rare race with speculative reference.
1404e286781dSNick Piggin 					 * the speculative reference will free
1405e286781dSNick Piggin 					 * this page shortly, so we may
1406e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1407e286781dSNick Piggin 					 * leave it off the LRU).
1408e286781dSNick Piggin 					 */
1409e286781dSNick Piggin 					nr_reclaimed++;
1410e286781dSNick Piggin 					continue;
1411e286781dSNick Piggin 				}
1412e286781dSNick Piggin 			}
14131da177e4SLinus Torvalds 		}
14141da177e4SLinus Torvalds 
1415802a3a92SShaohua Li 		if (PageAnon(page) && !PageSwapBacked(page)) {
1416802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
1417802a3a92SShaohua Li 			if (!page_ref_freeze(page, 1))
141849d2e9ccSChristoph Lameter 				goto keep_locked;
1419802a3a92SShaohua Li 			if (PageDirty(page)) {
1420802a3a92SShaohua Li 				page_ref_unfreeze(page, 1);
1421802a3a92SShaohua Li 				goto keep_locked;
1422802a3a92SShaohua Li 			}
14231da177e4SLinus Torvalds 
1424802a3a92SShaohua Li 			count_vm_event(PGLAZYFREED);
14252262185cSRoman Gushchin 			count_memcg_page_event(page, PGLAZYFREED);
1426802a3a92SShaohua Li 		} else if (!mapping || !__remove_mapping(mapping, page, true))
1427802a3a92SShaohua Li 			goto keep_locked;
14289a1ea439SHugh Dickins 
14299a1ea439SHugh Dickins 		unlock_page(page);
1430e286781dSNick Piggin free_it:
143198879b3bSYang Shi 		/*
143298879b3bSYang Shi 		 * THP may get swapped out in a whole, need account
143398879b3bSYang Shi 		 * all base pages.
143498879b3bSYang Shi 		 */
143598879b3bSYang Shi 		nr_reclaimed += nr_pages;
1436abe4c3b5SMel Gorman 
1437abe4c3b5SMel Gorman 		/*
1438abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1439abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1440abe4c3b5SMel Gorman 		 */
14417ae88534SYang Shi 		if (unlikely(PageTransHuge(page)))
1442bd4c82c2SHuang Ying 			(*get_compound_page_dtor(page))(page);
14437ae88534SYang Shi 		else
1444abe4c3b5SMel Gorman 			list_add(&page->lru, &free_pages);
14451da177e4SLinus Torvalds 		continue;
14461da177e4SLinus Torvalds 
144798879b3bSYang Shi activate_locked_split:
144898879b3bSYang Shi 		/*
144998879b3bSYang Shi 		 * The tail pages that are failed to add into swap cache
145098879b3bSYang Shi 		 * reach here.  Fixup nr_scanned and nr_pages.
145198879b3bSYang Shi 		 */
145298879b3bSYang Shi 		if (nr_pages > 1) {
145398879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
145498879b3bSYang Shi 			nr_pages = 1;
145598879b3bSYang Shi 		}
14561da177e4SLinus Torvalds activate_locked:
145768a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
1458ad6b6704SMinchan Kim 		if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1459ad6b6704SMinchan Kim 						PageMlocked(page)))
1460a2c43eedSHugh Dickins 			try_to_free_swap(page);
1461309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
1462ad6b6704SMinchan Kim 		if (!PageMlocked(page)) {
1463886cf190SKirill Tkhai 			int type = page_is_file_cache(page);
14641da177e4SLinus Torvalds 			SetPageActive(page);
146598879b3bSYang Shi 			stat->nr_activate[type] += nr_pages;
14662262185cSRoman Gushchin 			count_memcg_page_event(page, PGACTIVATE);
1467ad6b6704SMinchan Kim 		}
14681da177e4SLinus Torvalds keep_locked:
14691da177e4SLinus Torvalds 		unlock_page(page);
14701da177e4SLinus Torvalds keep:
14711da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1472309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
14731da177e4SLinus Torvalds 	}
1474abe4c3b5SMel Gorman 
147598879b3bSYang Shi 	pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
147698879b3bSYang Shi 
1477747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
147872b252aeSMel Gorman 	try_to_unmap_flush();
14792d4894b5SMel Gorman 	free_unref_page_list(&free_pages);
1480abe4c3b5SMel Gorman 
14811da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1482886cf190SKirill Tkhai 	count_vm_events(PGACTIVATE, pgactivate);
14830a31bc97SJohannes Weiner 
148405ff5137SAndrew Morton 	return nr_reclaimed;
14851da177e4SLinus Torvalds }
14861da177e4SLinus Torvalds 
148702c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
148802c6de8dSMinchan Kim 					    struct list_head *page_list)
148902c6de8dSMinchan Kim {
149002c6de8dSMinchan Kim 	struct scan_control sc = {
149102c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
149202c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
149302c6de8dSMinchan Kim 		.may_unmap = 1,
149402c6de8dSMinchan Kim 	};
1495060f005fSKirill Tkhai 	struct reclaim_stat dummy_stat;
14963c710c1aSMichal Hocko 	unsigned long ret;
149702c6de8dSMinchan Kim 	struct page *page, *next;
149802c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
149902c6de8dSMinchan Kim 
150002c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1501117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1502a58f2cefSMinchan Kim 		    !__PageMovable(page) && !PageUnevictable(page)) {
150302c6de8dSMinchan Kim 			ClearPageActive(page);
150402c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
150502c6de8dSMinchan Kim 		}
150602c6de8dSMinchan Kim 	}
150702c6de8dSMinchan Kim 
1508599d0c95SMel Gorman 	ret = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1509060f005fSKirill Tkhai 			TTU_IGNORE_ACCESS, &dummy_stat, true);
151002c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
1511599d0c95SMel Gorman 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
151202c6de8dSMinchan Kim 	return ret;
151302c6de8dSMinchan Kim }
151402c6de8dSMinchan Kim 
15155ad333ebSAndy Whitcroft /*
15165ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
15175ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
15185ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
15195ad333ebSAndy Whitcroft  *
15205ad333ebSAndy Whitcroft  * page:	page to consider
15215ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
15225ad333ebSAndy Whitcroft  *
15235ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
15245ad333ebSAndy Whitcroft  */
1525f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
15265ad333ebSAndy Whitcroft {
15275ad333ebSAndy Whitcroft 	int ret = -EINVAL;
15285ad333ebSAndy Whitcroft 
15295ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
15305ad333ebSAndy Whitcroft 	if (!PageLRU(page))
15315ad333ebSAndy Whitcroft 		return ret;
15325ad333ebSAndy Whitcroft 
1533e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1534e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1535894bc310SLee Schermerhorn 		return ret;
1536894bc310SLee Schermerhorn 
15375ad333ebSAndy Whitcroft 	ret = -EBUSY;
153808e552c6SKAMEZAWA Hiroyuki 
1539c8244935SMel Gorman 	/*
1540c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1541c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1542c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1543c8244935SMel Gorman 	 *
1544c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1545c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1546c8244935SMel Gorman 	 */
15471276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1548c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1549c8244935SMel Gorman 		if (PageWriteback(page))
155039deaf85SMinchan Kim 			return ret;
155139deaf85SMinchan Kim 
1552c8244935SMel Gorman 		if (PageDirty(page)) {
1553c8244935SMel Gorman 			struct address_space *mapping;
155469d763fcSMel Gorman 			bool migrate_dirty;
1555c8244935SMel Gorman 
1556c8244935SMel Gorman 			/*
1557c8244935SMel Gorman 			 * Only pages without mappings or that have a
1558c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
155969d763fcSMel Gorman 			 * without blocking. However, we can be racing with
156069d763fcSMel Gorman 			 * truncation so it's necessary to lock the page
156169d763fcSMel Gorman 			 * to stabilise the mapping as truncation holds
156269d763fcSMel Gorman 			 * the page lock until after the page is removed
156369d763fcSMel Gorman 			 * from the page cache.
1564c8244935SMel Gorman 			 */
156569d763fcSMel Gorman 			if (!trylock_page(page))
156669d763fcSMel Gorman 				return ret;
156769d763fcSMel Gorman 
1568c8244935SMel Gorman 			mapping = page_mapping(page);
1569145e1a71SHugh Dickins 			migrate_dirty = !mapping || mapping->a_ops->migratepage;
157069d763fcSMel Gorman 			unlock_page(page);
157169d763fcSMel Gorman 			if (!migrate_dirty)
1572c8244935SMel Gorman 				return ret;
1573c8244935SMel Gorman 		}
1574c8244935SMel Gorman 	}
1575c8244935SMel Gorman 
1576f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1577f80c0673SMinchan Kim 		return ret;
1578f80c0673SMinchan Kim 
15795ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
15805ad333ebSAndy Whitcroft 		/*
15815ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
15825ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
15835ad333ebSAndy Whitcroft 		 * page release code relies on it.
15845ad333ebSAndy Whitcroft 		 */
15855ad333ebSAndy Whitcroft 		ClearPageLRU(page);
15865ad333ebSAndy Whitcroft 		ret = 0;
15875ad333ebSAndy Whitcroft 	}
15885ad333ebSAndy Whitcroft 
15895ad333ebSAndy Whitcroft 	return ret;
15905ad333ebSAndy Whitcroft }
15915ad333ebSAndy Whitcroft 
15927ee36a14SMel Gorman 
15937ee36a14SMel Gorman /*
15947ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
15957ee36a14SMel Gorman  * be complete before mem_cgroup_update_lru_size due to a santity check.
15967ee36a14SMel Gorman  */
15977ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1598b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
15997ee36a14SMel Gorman {
16007ee36a14SMel Gorman 	int zid;
16017ee36a14SMel Gorman 
16027ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
16037ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
16047ee36a14SMel Gorman 			continue;
16057ee36a14SMel Gorman 
16067ee36a14SMel Gorman 		__update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1607b4536f0cSMichal Hocko #ifdef CONFIG_MEMCG
1608b4536f0cSMichal Hocko 		mem_cgroup_update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1609b4536f0cSMichal Hocko #endif
16107ee36a14SMel Gorman 	}
16117ee36a14SMel Gorman 
16127ee36a14SMel Gorman }
16137ee36a14SMel Gorman 
1614f4b7e272SAndrey Ryabinin /**
1615f4b7e272SAndrey Ryabinin  * pgdat->lru_lock is heavily contended.  Some of the functions that
16161da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
16171da177e4SLinus Torvalds  * and working on them outside the LRU lock.
16181da177e4SLinus Torvalds  *
16191da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
16201da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
16211da177e4SLinus Torvalds  *
16221da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
16231da177e4SLinus Torvalds  *
1624791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
16255dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
16261da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1627f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1628fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
16295ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
16303cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
16311da177e4SLinus Torvalds  *
16321da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
16331da177e4SLinus Torvalds  */
163469e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
16355dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1636fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
1637a9e7c39fSKirill Tkhai 		enum lru_list lru)
16381da177e4SLinus Torvalds {
163975b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
164069e05944SAndrew Morton 	unsigned long nr_taken = 0;
1641599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
16427cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
16433db65812SJohannes Weiner 	unsigned long skipped = 0;
1644791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
1645b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
1646a9e7c39fSKirill Tkhai 	isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
16471da177e4SLinus Torvalds 
164898879b3bSYang Shi 	total_scan = 0;
1649791b48b6SMinchan Kim 	scan = 0;
165098879b3bSYang Shi 	while (scan < nr_to_scan && !list_empty(src)) {
16515ad333ebSAndy Whitcroft 		struct page *page;
16525ad333ebSAndy Whitcroft 
16531da177e4SLinus Torvalds 		page = lru_to_page(src);
16541da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
16551da177e4SLinus Torvalds 
1656309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
16578d438f96SNick Piggin 
1658d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
165998879b3bSYang Shi 		total_scan += nr_pages;
166098879b3bSYang Shi 
1661b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1662b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
166398879b3bSYang Shi 			nr_skipped[page_zonenum(page)] += nr_pages;
1664b2e18757SMel Gorman 			continue;
1665b2e18757SMel Gorman 		}
1666b2e18757SMel Gorman 
1667791b48b6SMinchan Kim 		/*
1668791b48b6SMinchan Kim 		 * Do not count skipped pages because that makes the function
1669791b48b6SMinchan Kim 		 * return with no isolated pages if the LRU mostly contains
1670791b48b6SMinchan Kim 		 * ineligible pages.  This causes the VM to not reclaim any
1671791b48b6SMinchan Kim 		 * pages, triggering a premature OOM.
167298879b3bSYang Shi 		 *
167398879b3bSYang Shi 		 * Account all tail pages of THP.  This would not cause
167498879b3bSYang Shi 		 * premature OOM since __isolate_lru_page() returns -EBUSY
167598879b3bSYang Shi 		 * only when the page is being freed somewhere else.
1676791b48b6SMinchan Kim 		 */
167798879b3bSYang Shi 		scan += nr_pages;
1678f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
16795ad333ebSAndy Whitcroft 		case 0:
1680599d0c95SMel Gorman 			nr_taken += nr_pages;
1681599d0c95SMel Gorman 			nr_zone_taken[page_zonenum(page)] += nr_pages;
16825ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
16835ad333ebSAndy Whitcroft 			break;
16847c8ee9a8SNick Piggin 
16855ad333ebSAndy Whitcroft 		case -EBUSY:
16865ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
16875ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
16885ad333ebSAndy Whitcroft 			continue;
16895ad333ebSAndy Whitcroft 
16905ad333ebSAndy Whitcroft 		default:
16915ad333ebSAndy Whitcroft 			BUG();
16925ad333ebSAndy Whitcroft 		}
16935ad333ebSAndy Whitcroft 	}
16941da177e4SLinus Torvalds 
1695b2e18757SMel Gorman 	/*
1696b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1697b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1698b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1699b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1700b2e18757SMel Gorman 	 * system at risk of premature OOM.
1701b2e18757SMel Gorman 	 */
17027cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
17037cc30fcfSMel Gorman 		int zid;
17047cc30fcfSMel Gorman 
17053db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
17067cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
17077cc30fcfSMel Gorman 			if (!nr_skipped[zid])
17087cc30fcfSMel Gorman 				continue;
17097cc30fcfSMel Gorman 
17107cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
17111265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
17127cc30fcfSMel Gorman 		}
17137cc30fcfSMel Gorman 	}
1714791b48b6SMinchan Kim 	*nr_scanned = total_scan;
17151265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1716791b48b6SMinchan Kim 				    total_scan, skipped, nr_taken, mode, lru);
1717b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
17181da177e4SLinus Torvalds 	return nr_taken;
17191da177e4SLinus Torvalds }
17201da177e4SLinus Torvalds 
172162695a84SNick Piggin /**
172262695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
172362695a84SNick Piggin  * @page: page to isolate from its LRU list
172462695a84SNick Piggin  *
172562695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
172662695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
172762695a84SNick Piggin  *
172862695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
172962695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
173062695a84SNick Piggin  *
173162695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1732894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1733894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1734894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
173562695a84SNick Piggin  *
173662695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
173762695a84SNick Piggin  * found will be decremented.
173862695a84SNick Piggin  *
173962695a84SNick Piggin  * Restrictions:
1740a5d09bedSMike Rapoport  *
174162695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
174262695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
174362695a84SNick Piggin  *     without a stable reference).
174462695a84SNick Piggin  * (2) the lru_lock must not be held.
174562695a84SNick Piggin  * (3) interrupts must be enabled.
174662695a84SNick Piggin  */
174762695a84SNick Piggin int isolate_lru_page(struct page *page)
174862695a84SNick Piggin {
174962695a84SNick Piggin 	int ret = -EBUSY;
175062695a84SNick Piggin 
1751309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1752cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
17530c917313SKonstantin Khlebnikov 
175462695a84SNick Piggin 	if (PageLRU(page)) {
1755f4b7e272SAndrey Ryabinin 		pg_data_t *pgdat = page_pgdat(page);
1756fa9add64SHugh Dickins 		struct lruvec *lruvec;
175762695a84SNick Piggin 
1758f4b7e272SAndrey Ryabinin 		spin_lock_irq(&pgdat->lru_lock);
1759f4b7e272SAndrey Ryabinin 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
17600c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1761894bc310SLee Schermerhorn 			int lru = page_lru(page);
17620c917313SKonstantin Khlebnikov 			get_page(page);
176362695a84SNick Piggin 			ClearPageLRU(page);
1764fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1765fa9add64SHugh Dickins 			ret = 0;
176662695a84SNick Piggin 		}
1767f4b7e272SAndrey Ryabinin 		spin_unlock_irq(&pgdat->lru_lock);
176862695a84SNick Piggin 	}
176962695a84SNick Piggin 	return ret;
177062695a84SNick Piggin }
177162695a84SNick Piggin 
17725ad333ebSAndy Whitcroft /*
1773d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1774d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1775d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1776d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1777d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
177835cd7815SRik van Riel  */
1779599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
178035cd7815SRik van Riel 		struct scan_control *sc)
178135cd7815SRik van Riel {
178235cd7815SRik van Riel 	unsigned long inactive, isolated;
178335cd7815SRik van Riel 
178435cd7815SRik van Riel 	if (current_is_kswapd())
178535cd7815SRik van Riel 		return 0;
178635cd7815SRik van Riel 
1787b5ead35eSJohannes Weiner 	if (!writeback_throttling_sane(sc))
178835cd7815SRik van Riel 		return 0;
178935cd7815SRik van Riel 
179035cd7815SRik van Riel 	if (file) {
1791599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1792599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
179335cd7815SRik van Riel 	} else {
1794599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1795599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
179635cd7815SRik van Riel 	}
179735cd7815SRik van Riel 
17983cf23841SFengguang Wu 	/*
17993cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
18003cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
18013cf23841SFengguang Wu 	 * deadlock.
18023cf23841SFengguang Wu 	 */
1803d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
18043cf23841SFengguang Wu 		inactive >>= 3;
18053cf23841SFengguang Wu 
180635cd7815SRik van Riel 	return isolated > inactive;
180735cd7815SRik van Riel }
180835cd7815SRik van Riel 
1809a222f341SKirill Tkhai /*
1810a222f341SKirill Tkhai  * This moves pages from @list to corresponding LRU list.
1811a222f341SKirill Tkhai  *
1812a222f341SKirill Tkhai  * We move them the other way if the page is referenced by one or more
1813a222f341SKirill Tkhai  * processes, from rmap.
1814a222f341SKirill Tkhai  *
1815a222f341SKirill Tkhai  * If the pages are mostly unmapped, the processing is fast and it is
1816a222f341SKirill Tkhai  * appropriate to hold zone_lru_lock across the whole operation.  But if
1817a222f341SKirill Tkhai  * the pages are mapped, the processing is slow (page_referenced()) so we
1818a222f341SKirill Tkhai  * should drop zone_lru_lock around each page.  It's impossible to balance
1819a222f341SKirill Tkhai  * this, so instead we remove the pages from the LRU while processing them.
1820a222f341SKirill Tkhai  * It is safe to rely on PG_active against the non-LRU pages in here because
1821a222f341SKirill Tkhai  * nobody will play with that bit on a non-LRU page.
1822a222f341SKirill Tkhai  *
1823a222f341SKirill Tkhai  * The downside is that we have to touch page->_refcount against each page.
1824a222f341SKirill Tkhai  * But we had to alter page->flags anyway.
1825a222f341SKirill Tkhai  *
1826a222f341SKirill Tkhai  * Returns the number of pages moved to the given lruvec.
1827a222f341SKirill Tkhai  */
1828a222f341SKirill Tkhai 
1829a222f341SKirill Tkhai static unsigned noinline_for_stack move_pages_to_lru(struct lruvec *lruvec,
1830a222f341SKirill Tkhai 						     struct list_head *list)
183166635629SMel Gorman {
1832599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
1833a222f341SKirill Tkhai 	int nr_pages, nr_moved = 0;
18343f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
1835a222f341SKirill Tkhai 	struct page *page;
1836a222f341SKirill Tkhai 	enum lru_list lru;
183766635629SMel Gorman 
1838a222f341SKirill Tkhai 	while (!list_empty(list)) {
1839a222f341SKirill Tkhai 		page = lru_to_page(list);
1840309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
184139b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1842a222f341SKirill Tkhai 			list_del(&page->lru);
1843599d0c95SMel Gorman 			spin_unlock_irq(&pgdat->lru_lock);
184466635629SMel Gorman 			putback_lru_page(page);
1845599d0c95SMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
184666635629SMel Gorman 			continue;
184766635629SMel Gorman 		}
1848599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
1849fa9add64SHugh Dickins 
18507a608572SLinus Torvalds 		SetPageLRU(page);
185166635629SMel Gorman 		lru = page_lru(page);
1852a222f341SKirill Tkhai 
1853a222f341SKirill Tkhai 		nr_pages = hpage_nr_pages(page);
1854a222f341SKirill Tkhai 		update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
1855a222f341SKirill Tkhai 		list_move(&page->lru, &lruvec->lists[lru]);
1856fa9add64SHugh Dickins 
18572bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
18582bcf8879SHugh Dickins 			__ClearPageLRU(page);
18592bcf8879SHugh Dickins 			__ClearPageActive(page);
1860fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
18612bcf8879SHugh Dickins 
18622bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1863599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
18642bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1865599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
18662bcf8879SHugh Dickins 			} else
18672bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
1868a222f341SKirill Tkhai 		} else {
1869a222f341SKirill Tkhai 			nr_moved += nr_pages;
187066635629SMel Gorman 		}
187166635629SMel Gorman 	}
187266635629SMel Gorman 
18733f79768fSHugh Dickins 	/*
18743f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
18753f79768fSHugh Dickins 	 */
1876a222f341SKirill Tkhai 	list_splice(&pages_to_free, list);
1877a222f341SKirill Tkhai 
1878a222f341SKirill Tkhai 	return nr_moved;
187966635629SMel Gorman }
188066635629SMel Gorman 
188166635629SMel Gorman /*
1882399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1883399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1884399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1885399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1886399ba0b9SNeilBrown  */
1887399ba0b9SNeilBrown static int current_may_throttle(void)
1888399ba0b9SNeilBrown {
1889399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1890399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1891399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1892399ba0b9SNeilBrown }
1893399ba0b9SNeilBrown 
1894399ba0b9SNeilBrown /*
1895b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
18961742f19fSAndrew Morton  * of reclaimed pages
18971da177e4SLinus Torvalds  */
189866635629SMel Gorman static noinline_for_stack unsigned long
18991a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
19009e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
19011da177e4SLinus Torvalds {
19021da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1903e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
190405ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1905e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
1906060f005fSKirill Tkhai 	struct reclaim_stat stat;
19073cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1908f46b7912SKirill Tkhai 	enum vm_event_item item;
1909599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
19101a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1911db73ee0dSMichal Hocko 	bool stalled = false;
191278dc583dSKOSAKI Motohiro 
1913599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
1914db73ee0dSMichal Hocko 		if (stalled)
1915db73ee0dSMichal Hocko 			return 0;
1916db73ee0dSMichal Hocko 
1917db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
1918db73ee0dSMichal Hocko 		msleep(100);
1919db73ee0dSMichal Hocko 		stalled = true;
192035cd7815SRik van Riel 
192135cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
192235cd7815SRik van Riel 		if (fatal_signal_pending(current))
192335cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
192435cd7815SRik van Riel 	}
192535cd7815SRik van Riel 
19261da177e4SLinus Torvalds 	lru_add_drain();
1927f80c0673SMinchan Kim 
1928599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19291da177e4SLinus Torvalds 
19305dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
1931a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
193295d918fcSKonstantin Khlebnikov 
1933599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
19349d5e6a9fSHugh Dickins 	reclaim_stat->recent_scanned[file] += nr_taken;
193595d918fcSKonstantin Khlebnikov 
1936f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
1937b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
1938f46b7912SKirill Tkhai 		__count_vm_events(item, nr_scanned);
1939f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
1940599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
1941d563c050SHillf Danton 
1942d563c050SHillf Danton 	if (nr_taken == 0)
194366635629SMel Gorman 		return 0;
1944b35ea17bSKOSAKI Motohiro 
1945a128ca71SShaohua Li 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, 0,
19463c710c1aSMichal Hocko 				&stat, false);
1947c661b078SAndy Whitcroft 
1948599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19493f79768fSHugh Dickins 
1950f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
1951b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
1952f46b7912SKirill Tkhai 		__count_vm_events(item, nr_reclaimed);
1953f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
1954b17f18afSKirill Tkhai 	reclaim_stat->recent_rotated[0] += stat.nr_activate[0];
1955b17f18afSKirill Tkhai 	reclaim_stat->recent_rotated[1] += stat.nr_activate[1];
1956a74609faSNick Piggin 
1957a222f341SKirill Tkhai 	move_pages_to_lru(lruvec, &page_list);
19583f79768fSHugh Dickins 
1959599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
19603f79768fSHugh Dickins 
1961599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19623f79768fSHugh Dickins 
1963747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
19642d4894b5SMel Gorman 	free_unref_page_list(&page_list);
1965e11da5b4SMel Gorman 
196692df3a72SMel Gorman 	/*
19671c610d5fSAndrey Ryabinin 	 * If dirty pages are scanned that are not queued for IO, it
19681c610d5fSAndrey Ryabinin 	 * implies that flushers are not doing their job. This can
19691c610d5fSAndrey Ryabinin 	 * happen when memory pressure pushes dirty pages to the end of
19701c610d5fSAndrey Ryabinin 	 * the LRU before the dirty limits are breached and the dirty
19711c610d5fSAndrey Ryabinin 	 * data has expired. It can also happen when the proportion of
19721c610d5fSAndrey Ryabinin 	 * dirty pages grows not through writes but through memory
19731c610d5fSAndrey Ryabinin 	 * pressure reclaiming all the clean cache. And in some cases,
19741c610d5fSAndrey Ryabinin 	 * the flushers simply cannot keep up with the allocation
19751c610d5fSAndrey Ryabinin 	 * rate. Nudge the flusher threads in case they are asleep.
19761c610d5fSAndrey Ryabinin 	 */
19771c610d5fSAndrey Ryabinin 	if (stat.nr_unqueued_dirty == nr_taken)
19781c610d5fSAndrey Ryabinin 		wakeup_flusher_threads(WB_REASON_VMSCAN);
19791c610d5fSAndrey Ryabinin 
1980d108c772SAndrey Ryabinin 	sc->nr.dirty += stat.nr_dirty;
1981d108c772SAndrey Ryabinin 	sc->nr.congested += stat.nr_congested;
1982d108c772SAndrey Ryabinin 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
1983d108c772SAndrey Ryabinin 	sc->nr.writeback += stat.nr_writeback;
1984d108c772SAndrey Ryabinin 	sc->nr.immediate += stat.nr_immediate;
1985d108c772SAndrey Ryabinin 	sc->nr.taken += nr_taken;
1986d108c772SAndrey Ryabinin 	if (file)
1987d108c772SAndrey Ryabinin 		sc->nr.file_taken += nr_taken;
19888e950282SMel Gorman 
1989599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
1990d51d1e64SSteven Rostedt 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
199105ff5137SAndrew Morton 	return nr_reclaimed;
19921da177e4SLinus Torvalds }
19931da177e4SLinus Torvalds 
1994f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
19951a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1996f16015fbSJohannes Weiner 			       struct scan_control *sc,
19979e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
19981cfb419bSKAMEZAWA Hiroyuki {
199944c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
2000f626012dSHugh Dickins 	unsigned long nr_scanned;
20016fe6b7e3SWu Fengguang 	unsigned long vm_flags;
20021cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
20038cab4754SWu Fengguang 	LIST_HEAD(l_active);
2004b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
20051cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
20061a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
20079d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
20089d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
20093cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
2010599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
20111cfb419bSKAMEZAWA Hiroyuki 
20121da177e4SLinus Torvalds 	lru_add_drain();
2013f80c0673SMinchan Kim 
2014599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
2015925b7673SJohannes Weiner 
20165dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2017a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
201889b5fae5SJohannes Weiner 
2019599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2020b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
20211cfb419bSKAMEZAWA Hiroyuki 
2022599d0c95SMel Gorman 	__count_vm_events(PGREFILL, nr_scanned);
20232fa2690cSYafang Shao 	__count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
20249d5e6a9fSHugh Dickins 
2025599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
20261da177e4SLinus Torvalds 
20271da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
20281da177e4SLinus Torvalds 		cond_resched();
20291da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
20301da177e4SLinus Torvalds 		list_del(&page->lru);
20317e9cd484SRik van Riel 
203239b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
2033894bc310SLee Schermerhorn 			putback_lru_page(page);
2034894bc310SLee Schermerhorn 			continue;
2035894bc310SLee Schermerhorn 		}
2036894bc310SLee Schermerhorn 
2037cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
2038cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
2039cc715d99SMel Gorman 				if (page_has_private(page))
2040cc715d99SMel Gorman 					try_to_release_page(page, 0);
2041cc715d99SMel Gorman 				unlock_page(page);
2042cc715d99SMel Gorman 			}
2043cc715d99SMel Gorman 		}
2044cc715d99SMel Gorman 
2045c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
2046c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
20479992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
20488cab4754SWu Fengguang 			/*
20498cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
20508cab4754SWu Fengguang 			 * give them one more trip around the active list. So
20518cab4754SWu Fengguang 			 * that executable code get better chances to stay in
20528cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
20538cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
20548cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
20558cab4754SWu Fengguang 			 * so we ignore them here.
20568cab4754SWu Fengguang 			 */
205741e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
20588cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
20598cab4754SWu Fengguang 				continue;
20608cab4754SWu Fengguang 			}
20618cab4754SWu Fengguang 		}
20627e9cd484SRik van Riel 
20635205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
20641899ad18SJohannes Weiner 		SetPageWorkingset(page);
20651da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
20661da177e4SLinus Torvalds 	}
20671da177e4SLinus Torvalds 
2068b555749aSAndrew Morton 	/*
20698cab4754SWu Fengguang 	 * Move pages back to the lru list.
2070b555749aSAndrew Morton 	 */
2071599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
20724f98a2feSRik van Riel 	/*
20738cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
20748cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
20758cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
20767c0db9e9SJerome Marchand 	 * get_scan_count.
2077556adecbSRik van Riel 	 */
2078b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
2079556adecbSRik van Riel 
2080a222f341SKirill Tkhai 	nr_activate = move_pages_to_lru(lruvec, &l_active);
2081a222f341SKirill Tkhai 	nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2082f372d89eSKirill Tkhai 	/* Keep all free pages in l_active list */
2083f372d89eSKirill Tkhai 	list_splice(&l_inactive, &l_active);
20849851ac13SKirill Tkhai 
20859851ac13SKirill Tkhai 	__count_vm_events(PGDEACTIVATE, nr_deactivate);
20869851ac13SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
20879851ac13SKirill Tkhai 
2088599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2089599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
20902bcf8879SHugh Dickins 
2091f372d89eSKirill Tkhai 	mem_cgroup_uncharge_list(&l_active);
2092f372d89eSKirill Tkhai 	free_unref_page_list(&l_active);
20939d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
20949d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
20951da177e4SLinus Torvalds }
20961da177e4SLinus Torvalds 
20971a4e58ccSMinchan Kim unsigned long reclaim_pages(struct list_head *page_list)
20981a4e58ccSMinchan Kim {
20991a4e58ccSMinchan Kim 	int nid = -1;
21001a4e58ccSMinchan Kim 	unsigned long nr_reclaimed = 0;
21011a4e58ccSMinchan Kim 	LIST_HEAD(node_page_list);
21021a4e58ccSMinchan Kim 	struct reclaim_stat dummy_stat;
21031a4e58ccSMinchan Kim 	struct page *page;
21041a4e58ccSMinchan Kim 	struct scan_control sc = {
21051a4e58ccSMinchan Kim 		.gfp_mask = GFP_KERNEL,
21061a4e58ccSMinchan Kim 		.priority = DEF_PRIORITY,
21071a4e58ccSMinchan Kim 		.may_writepage = 1,
21081a4e58ccSMinchan Kim 		.may_unmap = 1,
21091a4e58ccSMinchan Kim 		.may_swap = 1,
21101a4e58ccSMinchan Kim 	};
21111a4e58ccSMinchan Kim 
21121a4e58ccSMinchan Kim 	while (!list_empty(page_list)) {
21131a4e58ccSMinchan Kim 		page = lru_to_page(page_list);
21141a4e58ccSMinchan Kim 		if (nid == -1) {
21151a4e58ccSMinchan Kim 			nid = page_to_nid(page);
21161a4e58ccSMinchan Kim 			INIT_LIST_HEAD(&node_page_list);
21171a4e58ccSMinchan Kim 		}
21181a4e58ccSMinchan Kim 
21191a4e58ccSMinchan Kim 		if (nid == page_to_nid(page)) {
21201a4e58ccSMinchan Kim 			ClearPageActive(page);
21211a4e58ccSMinchan Kim 			list_move(&page->lru, &node_page_list);
21221a4e58ccSMinchan Kim 			continue;
21231a4e58ccSMinchan Kim 		}
21241a4e58ccSMinchan Kim 
21251a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
21261a4e58ccSMinchan Kim 						NODE_DATA(nid),
21271a4e58ccSMinchan Kim 						&sc, 0,
21281a4e58ccSMinchan Kim 						&dummy_stat, false);
21291a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
21301a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
21311a4e58ccSMinchan Kim 			list_del(&page->lru);
21321a4e58ccSMinchan Kim 			putback_lru_page(page);
21331a4e58ccSMinchan Kim 		}
21341a4e58ccSMinchan Kim 
21351a4e58ccSMinchan Kim 		nid = -1;
21361a4e58ccSMinchan Kim 	}
21371a4e58ccSMinchan Kim 
21381a4e58ccSMinchan Kim 	if (!list_empty(&node_page_list)) {
21391a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
21401a4e58ccSMinchan Kim 						NODE_DATA(nid),
21411a4e58ccSMinchan Kim 						&sc, 0,
21421a4e58ccSMinchan Kim 						&dummy_stat, false);
21431a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
21441a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
21451a4e58ccSMinchan Kim 			list_del(&page->lru);
21461a4e58ccSMinchan Kim 			putback_lru_page(page);
21471a4e58ccSMinchan Kim 		}
21481a4e58ccSMinchan Kim 	}
21491a4e58ccSMinchan Kim 
21501a4e58ccSMinchan Kim 	return nr_reclaimed;
21511a4e58ccSMinchan Kim }
21521a4e58ccSMinchan Kim 
215359dc76b0SRik van Riel /*
215459dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
215559dc76b0SRik van Riel  * to do too much work.
215614797e23SKOSAKI Motohiro  *
215759dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
215859dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
215959dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
216059dc76b0SRik van Riel  *
216159dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
216259dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
216359dc76b0SRik van Riel  *
21642a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
21652a2e4885SJohannes Weiner  *
216659dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
21673a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
216859dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
216959dc76b0SRik van Riel  *
217059dc76b0SRik van Riel  * total     target    max
217159dc76b0SRik van Riel  * memory    ratio     inactive
217259dc76b0SRik van Riel  * -------------------------------------
217359dc76b0SRik van Riel  *   10MB       1         5MB
217459dc76b0SRik van Riel  *  100MB       1        50MB
217559dc76b0SRik van Riel  *    1GB       3       250MB
217659dc76b0SRik van Riel  *   10GB      10       0.9GB
217759dc76b0SRik van Riel  *  100GB      31         3GB
217859dc76b0SRik van Riel  *    1TB     101        10GB
217959dc76b0SRik van Riel  *   10TB     320        32GB
218014797e23SKOSAKI Motohiro  */
2181f8d1a311SMel Gorman static bool inactive_list_is_low(struct lruvec *lruvec, bool file,
21822c012a4aSKuo-Hsin Yang 				 struct scan_control *sc, bool trace)
218314797e23SKOSAKI Motohiro {
2184fd538803SMichal Hocko 	enum lru_list active_lru = file * LRU_FILE + LRU_ACTIVE;
21852a2e4885SJohannes Weiner 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
21862a2e4885SJohannes Weiner 	enum lru_list inactive_lru = file * LRU_FILE;
21872a2e4885SJohannes Weiner 	unsigned long inactive, active;
21882a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
21892a2e4885SJohannes Weiner 	unsigned long refaults;
219059dc76b0SRik van Riel 	unsigned long gb;
219159dc76b0SRik van Riel 
2192fd538803SMichal Hocko 	inactive = lruvec_lru_size(lruvec, inactive_lru, sc->reclaim_idx);
2193fd538803SMichal Hocko 	active = lruvec_lru_size(lruvec, active_lru, sc->reclaim_idx);
2194f8d1a311SMel Gorman 
21952a2e4885SJohannes Weiner 	/*
21962a2e4885SJohannes Weiner 	 * When refaults are being observed, it means a new workingset
21972a2e4885SJohannes Weiner 	 * is being established. Disable active list protection to get
21982a2e4885SJohannes Weiner 	 * rid of the stale workingset quickly.
21992a2e4885SJohannes Weiner 	 */
2200205b20ccSJohannes Weiner 	refaults = lruvec_page_state_local(lruvec, WORKINGSET_ACTIVATE);
22012c012a4aSKuo-Hsin Yang 	if (file && lruvec->refaults != refaults) {
22022a2e4885SJohannes Weiner 		inactive_ratio = 0;
22032a2e4885SJohannes Weiner 	} else {
220459dc76b0SRik van Riel 		gb = (inactive + active) >> (30 - PAGE_SHIFT);
220559dc76b0SRik van Riel 		if (gb)
220659dc76b0SRik van Riel 			inactive_ratio = int_sqrt(10 * gb);
2207b39415b2SRik van Riel 		else
220859dc76b0SRik van Riel 			inactive_ratio = 1;
22092a2e4885SJohannes Weiner 	}
221059dc76b0SRik van Riel 
22112c012a4aSKuo-Hsin Yang 	if (trace)
22122a2e4885SJohannes Weiner 		trace_mm_vmscan_inactive_list_is_low(pgdat->node_id, sc->reclaim_idx,
2213fd538803SMichal Hocko 			lruvec_lru_size(lruvec, inactive_lru, MAX_NR_ZONES), inactive,
2214fd538803SMichal Hocko 			lruvec_lru_size(lruvec, active_lru, MAX_NR_ZONES), active,
2215fd538803SMichal Hocko 			inactive_ratio, file);
2216fd538803SMichal Hocko 
221759dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2218b39415b2SRik van Riel }
2219b39415b2SRik van Riel 
22204f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
22213b991208SJohannes Weiner 				 struct lruvec *lruvec, struct scan_control *sc)
2222b69408e8SChristoph Lameter {
2223b39415b2SRik van Riel 	if (is_active_lru(lru)) {
22243b991208SJohannes Weiner 		if (inactive_list_is_low(lruvec, is_file_lru(lru), sc, true))
22251a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2226556adecbSRik van Riel 		return 0;
2227556adecbSRik van Riel 	}
2228556adecbSRik van Riel 
22291a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2230b69408e8SChristoph Lameter }
2231b69408e8SChristoph Lameter 
22329a265114SJohannes Weiner enum scan_balance {
22339a265114SJohannes Weiner 	SCAN_EQUAL,
22349a265114SJohannes Weiner 	SCAN_FRACT,
22359a265114SJohannes Weiner 	SCAN_ANON,
22369a265114SJohannes Weiner 	SCAN_FILE,
22379a265114SJohannes Weiner };
22389a265114SJohannes Weiner 
22391da177e4SLinus Torvalds /*
22404f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
22414f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
22424f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
22434f98a2feSRik van Riel  * onto the active list instead of evict.
22444f98a2feSRik van Riel  *
2245be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2246be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
22474f98a2feSRik van Riel  */
2248afaf07a6SJohannes Weiner static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2249afaf07a6SJohannes Weiner 			   unsigned long *nr)
22504f98a2feSRik van Riel {
2251afaf07a6SJohannes Weiner 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
225233377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
225390126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
22549a265114SJohannes Weiner 	u64 fraction[2];
22559a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
2256599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
22579a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
22589a265114SJohannes Weiner 	enum scan_balance scan_balance;
22590bf1457fSJohannes Weiner 	unsigned long anon, file;
22609a265114SJohannes Weiner 	unsigned long ap, fp;
22619a265114SJohannes Weiner 	enum lru_list lru;
226276a33fc3SShaohua Li 
226376a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2264d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
22659a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
226676a33fc3SShaohua Li 		goto out;
226776a33fc3SShaohua Li 	}
22684f98a2feSRik van Riel 
226910316b31SJohannes Weiner 	/*
227010316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
227110316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
227210316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
227310316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
227410316b31SJohannes Weiner 	 * too expensive.
227510316b31SJohannes Weiner 	 */
2276b5ead35eSJohannes Weiner 	if (cgroup_reclaim(sc) && !swappiness) {
22779a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
227810316b31SJohannes Weiner 		goto out;
227910316b31SJohannes Weiner 	}
228010316b31SJohannes Weiner 
228110316b31SJohannes Weiner 	/*
228210316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
228310316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
228410316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
228510316b31SJohannes Weiner 	 */
228602695175SJohannes Weiner 	if (!sc->priority && swappiness) {
22879a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
228810316b31SJohannes Weiner 		goto out;
228910316b31SJohannes Weiner 	}
229010316b31SJohannes Weiner 
229111d16c25SJohannes Weiner 	/*
229262376251SJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
229362376251SJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
229462376251SJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
229562376251SJohannes Weiner 	 * shrinks, so does the window for rotation from references.
229662376251SJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
229762376251SJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
229862376251SJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
229962376251SJohannes Weiner 	 */
2300b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc)) {
2301599d0c95SMel Gorman 		unsigned long pgdatfile;
2302599d0c95SMel Gorman 		unsigned long pgdatfree;
2303599d0c95SMel Gorman 		int z;
2304599d0c95SMel Gorman 		unsigned long total_high_wmark = 0;
230562376251SJohannes Weiner 
2306599d0c95SMel Gorman 		pgdatfree = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2307599d0c95SMel Gorman 		pgdatfile = node_page_state(pgdat, NR_ACTIVE_FILE) +
2308599d0c95SMel Gorman 			   node_page_state(pgdat, NR_INACTIVE_FILE);
23092ab051e1SJerome Marchand 
2310599d0c95SMel Gorman 		for (z = 0; z < MAX_NR_ZONES; z++) {
2311599d0c95SMel Gorman 			struct zone *zone = &pgdat->node_zones[z];
23126aa303deSMel Gorman 			if (!managed_zone(zone))
2313599d0c95SMel Gorman 				continue;
2314599d0c95SMel Gorman 
2315599d0c95SMel Gorman 			total_high_wmark += high_wmark_pages(zone);
2316599d0c95SMel Gorman 		}
2317599d0c95SMel Gorman 
2318599d0c95SMel Gorman 		if (unlikely(pgdatfile + pgdatfree <= total_high_wmark)) {
231906226226SDavid Rientjes 			/*
232006226226SDavid Rientjes 			 * Force SCAN_ANON if there are enough inactive
232106226226SDavid Rientjes 			 * anonymous pages on the LRU in eligible zones.
232206226226SDavid Rientjes 			 * Otherwise, the small LRU gets thrashed.
232306226226SDavid Rientjes 			 */
23243b991208SJohannes Weiner 			if (!inactive_list_is_low(lruvec, false, sc, false) &&
232506226226SDavid Rientjes 			    lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, sc->reclaim_idx)
232606226226SDavid Rientjes 					>> sc->priority) {
232762376251SJohannes Weiner 				scan_balance = SCAN_ANON;
232862376251SJohannes Weiner 				goto out;
232962376251SJohannes Weiner 			}
233062376251SJohannes Weiner 		}
233106226226SDavid Rientjes 	}
233262376251SJohannes Weiner 
233362376251SJohannes Weiner 	/*
2334316bda0eSVladimir Davydov 	 * If there is enough inactive page cache, i.e. if the size of the
2335316bda0eSVladimir Davydov 	 * inactive list is greater than that of the active list *and* the
2336316bda0eSVladimir Davydov 	 * inactive list actually has some pages to scan on this priority, we
2337316bda0eSVladimir Davydov 	 * do not reclaim anything from the anonymous working set right now.
2338316bda0eSVladimir Davydov 	 * Without the second condition we could end up never scanning an
2339316bda0eSVladimir Davydov 	 * lruvec even if it has plenty of old anonymous pages unless the
2340316bda0eSVladimir Davydov 	 * system is under heavy pressure.
2341e9868505SRik van Riel 	 */
23423b991208SJohannes Weiner 	if (!inactive_list_is_low(lruvec, true, sc, false) &&
234371ab6cfeSMichal Hocko 	    lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, sc->reclaim_idx) >> sc->priority) {
23449a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2345e9868505SRik van Riel 		goto out;
23464f98a2feSRik van Riel 	}
23474f98a2feSRik van Riel 
23489a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
23499a265114SJohannes Weiner 
23504f98a2feSRik van Riel 	/*
235158c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
235258c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
235358c37f6eSKOSAKI Motohiro 	 */
235402695175SJohannes Weiner 	anon_prio = swappiness;
235575b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
235658c37f6eSKOSAKI Motohiro 
235758c37f6eSKOSAKI Motohiro 	/*
23584f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
23594f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
23604f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
23614f98a2feSRik van Riel 	 *
23624f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
23634f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
23644f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
23654f98a2feSRik van Riel 	 *
23664f98a2feSRik van Riel 	 * anon in [0], file in [1]
23674f98a2feSRik van Riel 	 */
23682ab051e1SJerome Marchand 
2369fd538803SMichal Hocko 	anon  = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON, MAX_NR_ZONES) +
2370fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, MAX_NR_ZONES);
2371fd538803SMichal Hocko 	file  = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE, MAX_NR_ZONES) +
2372fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, MAX_NR_ZONES);
23732ab051e1SJerome Marchand 
2374599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
237558c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
23766e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
23776e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
23784f98a2feSRik van Riel 	}
23794f98a2feSRik van Riel 
23806e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
23816e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
23826e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
23834f98a2feSRik van Riel 	}
23844f98a2feSRik van Riel 
23854f98a2feSRik van Riel 	/*
238600d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
238700d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
238800d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
23894f98a2feSRik van Riel 	 */
2390fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
23916e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
23924f98a2feSRik van Riel 
2393fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
23946e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
2395599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
23964f98a2feSRik van Riel 
239776a33fc3SShaohua Li 	fraction[0] = ap;
239876a33fc3SShaohua Li 	fraction[1] = fp;
239976a33fc3SShaohua Li 	denominator = ap + fp + 1;
240076a33fc3SShaohua Li out:
24014111304dSHugh Dickins 	for_each_evictable_lru(lru) {
24024111304dSHugh Dickins 		int file = is_file_lru(lru);
24039783aa99SChris Down 		unsigned long lruvec_size;
240476a33fc3SShaohua Li 		unsigned long scan;
24051bc63fb1SChris Down 		unsigned long protection;
240676a33fc3SShaohua Li 
24079783aa99SChris Down 		lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
24081bc63fb1SChris Down 		protection = mem_cgroup_protection(memcg,
24091bc63fb1SChris Down 						   sc->memcg_low_reclaim);
24109783aa99SChris Down 
24111bc63fb1SChris Down 		if (protection) {
24129783aa99SChris Down 			/*
24139783aa99SChris Down 			 * Scale a cgroup's reclaim pressure by proportioning
24149783aa99SChris Down 			 * its current usage to its memory.low or memory.min
24159783aa99SChris Down 			 * setting.
24169783aa99SChris Down 			 *
24179783aa99SChris Down 			 * This is important, as otherwise scanning aggression
24189783aa99SChris Down 			 * becomes extremely binary -- from nothing as we
24199783aa99SChris Down 			 * approach the memory protection threshold, to totally
24209783aa99SChris Down 			 * nominal as we exceed it.  This results in requiring
24219783aa99SChris Down 			 * setting extremely liberal protection thresholds. It
24229783aa99SChris Down 			 * also means we simply get no protection at all if we
24239783aa99SChris Down 			 * set it too low, which is not ideal.
24241bc63fb1SChris Down 			 *
24251bc63fb1SChris Down 			 * If there is any protection in place, we reduce scan
24261bc63fb1SChris Down 			 * pressure by how much of the total memory used is
24271bc63fb1SChris Down 			 * within protection thresholds.
24289783aa99SChris Down 			 *
24299de7ca46SChris Down 			 * There is one special case: in the first reclaim pass,
24309de7ca46SChris Down 			 * we skip over all groups that are within their low
24319de7ca46SChris Down 			 * protection. If that fails to reclaim enough pages to
24329de7ca46SChris Down 			 * satisfy the reclaim goal, we come back and override
24339de7ca46SChris Down 			 * the best-effort low protection. However, we still
24349de7ca46SChris Down 			 * ideally want to honor how well-behaved groups are in
24359de7ca46SChris Down 			 * that case instead of simply punishing them all
24369de7ca46SChris Down 			 * equally. As such, we reclaim them based on how much
24371bc63fb1SChris Down 			 * memory they are using, reducing the scan pressure
24381bc63fb1SChris Down 			 * again by how much of the total memory used is under
24391bc63fb1SChris Down 			 * hard protection.
24409783aa99SChris Down 			 */
24411bc63fb1SChris Down 			unsigned long cgroup_size = mem_cgroup_size(memcg);
24421bc63fb1SChris Down 
24431bc63fb1SChris Down 			/* Avoid TOCTOU with earlier protection check */
24441bc63fb1SChris Down 			cgroup_size = max(cgroup_size, protection);
24451bc63fb1SChris Down 
24461bc63fb1SChris Down 			scan = lruvec_size - lruvec_size * protection /
24471bc63fb1SChris Down 				cgroup_size;
24489783aa99SChris Down 
24499783aa99SChris Down 			/*
24501bc63fb1SChris Down 			 * Minimally target SWAP_CLUSTER_MAX pages to keep
24519de7ca46SChris Down 			 * reclaim moving forwards, avoiding decremeting
24529de7ca46SChris Down 			 * sc->priority further than desirable.
24539783aa99SChris Down 			 */
24541bc63fb1SChris Down 			scan = max(scan, SWAP_CLUSTER_MAX);
24559783aa99SChris Down 		} else {
24569783aa99SChris Down 			scan = lruvec_size;
24579783aa99SChris Down 		}
24589783aa99SChris Down 
24599783aa99SChris Down 		scan >>= sc->priority;
24609783aa99SChris Down 
2461688035f7SJohannes Weiner 		/*
2462688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2463688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2464688035f7SJohannes Weiner 		 */
2465688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
24669783aa99SChris Down 			scan = min(lruvec_size, SWAP_CLUSTER_MAX);
24679a265114SJohannes Weiner 
24689a265114SJohannes Weiner 		switch (scan_balance) {
24699a265114SJohannes Weiner 		case SCAN_EQUAL:
24709a265114SJohannes Weiner 			/* Scan lists relative to size */
24719a265114SJohannes Weiner 			break;
24729a265114SJohannes Weiner 		case SCAN_FRACT:
24739a265114SJohannes Weiner 			/*
24749a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
24759a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
247668600f62SRoman Gushchin 			 * Make sure we don't miss the last page
247768600f62SRoman Gushchin 			 * because of a round-off error.
24789a265114SJohannes Weiner 			 */
247968600f62SRoman Gushchin 			scan = DIV64_U64_ROUND_UP(scan * fraction[file],
24806f04f48dSSuleiman Souhlal 						  denominator);
24819a265114SJohannes Weiner 			break;
24829a265114SJohannes Weiner 		case SCAN_FILE:
24839a265114SJohannes Weiner 		case SCAN_ANON:
24849a265114SJohannes Weiner 			/* Scan one type exclusively */
24856b4f7799SJohannes Weiner 			if ((scan_balance == SCAN_FILE) != file) {
24869783aa99SChris Down 				lruvec_size = 0;
24879a265114SJohannes Weiner 				scan = 0;
24886b4f7799SJohannes Weiner 			}
24899a265114SJohannes Weiner 			break;
24909a265114SJohannes Weiner 		default:
24919a265114SJohannes Weiner 			/* Look ma, no brain */
24929a265114SJohannes Weiner 			BUG();
24939a265114SJohannes Weiner 		}
24946b4f7799SJohannes Weiner 
24954111304dSHugh Dickins 		nr[lru] = scan;
249676a33fc3SShaohua Li 	}
24976e08a369SWu Fengguang }
24984f98a2feSRik van Riel 
2499afaf07a6SJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
25009b4f98cdSJohannes Weiner {
25019b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2502e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
25039b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
25049b4f98cdSJohannes Weiner 	enum lru_list lru;
25059b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
25069b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
25079b4f98cdSJohannes Weiner 	struct blk_plug plug;
25081a501907SMel Gorman 	bool scan_adjusted;
25099b4f98cdSJohannes Weiner 
2510afaf07a6SJohannes Weiner 	get_scan_count(lruvec, sc, nr);
25119b4f98cdSJohannes Weiner 
2512e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2513e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2514e82e0561SMel Gorman 
25151a501907SMel Gorman 	/*
25161a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
25171a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
25181a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
25191a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
25201a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
25211a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
25221a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
25231a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
25241a501907SMel Gorman 	 * dropped to zero at the first pass.
25251a501907SMel Gorman 	 */
2526b5ead35eSJohannes Weiner 	scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
25271a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
25281a501907SMel Gorman 
25299b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
25309b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
25319b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2532e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2533e82e0561SMel Gorman 		unsigned long nr_scanned;
2534e82e0561SMel Gorman 
25359b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
25369b4f98cdSJohannes Weiner 			if (nr[lru]) {
25379b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
25389b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
25399b4f98cdSJohannes Weiner 
25409b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
25413b991208SJohannes Weiner 							    lruvec, sc);
25429b4f98cdSJohannes Weiner 			}
25439b4f98cdSJohannes Weiner 		}
2544e82e0561SMel Gorman 
2545bd041733SMichal Hocko 		cond_resched();
2546bd041733SMichal Hocko 
2547e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2548e82e0561SMel Gorman 			continue;
2549e82e0561SMel Gorman 
25509b4f98cdSJohannes Weiner 		/*
2551e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
25521a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2553e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2554e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2555e82e0561SMel Gorman 		 * proportional to the original scan target.
2556e82e0561SMel Gorman 		 */
2557e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2558e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2559e82e0561SMel Gorman 
25601a501907SMel Gorman 		/*
25611a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
25621a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
25631a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
25641a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
25651a501907SMel Gorman 		 */
25661a501907SMel Gorman 		if (!nr_file || !nr_anon)
25671a501907SMel Gorman 			break;
25681a501907SMel Gorman 
2569e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2570e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2571e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2572e82e0561SMel Gorman 			lru = LRU_BASE;
2573e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2574e82e0561SMel Gorman 		} else {
2575e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2576e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2577e82e0561SMel Gorman 			lru = LRU_FILE;
2578e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2579e82e0561SMel Gorman 		}
2580e82e0561SMel Gorman 
2581e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2582e82e0561SMel Gorman 		nr[lru] = 0;
2583e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2584e82e0561SMel Gorman 
2585e82e0561SMel Gorman 		/*
2586e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2587e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2588e82e0561SMel Gorman 		 */
2589e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2590e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2591e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2592e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2593e82e0561SMel Gorman 
2594e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2595e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2596e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2597e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2598e82e0561SMel Gorman 
2599e82e0561SMel Gorman 		scan_adjusted = true;
26009b4f98cdSJohannes Weiner 	}
26019b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
26029b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
26039b4f98cdSJohannes Weiner 
26049b4f98cdSJohannes Weiner 	/*
26059b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
26069b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
26079b4f98cdSJohannes Weiner 	 */
2608a1086291SJohannes Weiner 	if (total_swap_pages && inactive_list_is_low(lruvec, false, sc, true))
26099b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
26109b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
26119b4f98cdSJohannes Weiner }
26129b4f98cdSJohannes Weiner 
261323b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
26149e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
261523b9da55SMel Gorman {
2616d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
261723b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
26189e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
261923b9da55SMel Gorman 		return true;
262023b9da55SMel Gorman 
262123b9da55SMel Gorman 	return false;
262223b9da55SMel Gorman }
262323b9da55SMel Gorman 
26244f98a2feSRik van Riel /*
262523b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
262623b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
262723b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
262823b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
262923b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
26303e7d3449SMel Gorman  */
2631a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
26323e7d3449SMel Gorman 					unsigned long nr_reclaimed,
26333e7d3449SMel Gorman 					struct scan_control *sc)
26343e7d3449SMel Gorman {
26353e7d3449SMel Gorman 	unsigned long pages_for_compaction;
26363e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2637a9dd0a83SMel Gorman 	int z;
26383e7d3449SMel Gorman 
26393e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
26409e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
26413e7d3449SMel Gorman 		return false;
26423e7d3449SMel Gorman 
26433e7d3449SMel Gorman 	/*
26445ee04716SVlastimil Babka 	 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
26455ee04716SVlastimil Babka 	 * number of pages that were scanned. This will return to the caller
26465ee04716SVlastimil Babka 	 * with the risk reclaim/compaction and the resulting allocation attempt
26475ee04716SVlastimil Babka 	 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
26485ee04716SVlastimil Babka 	 * allocations through requiring that the full LRU list has been scanned
26495ee04716SVlastimil Babka 	 * first, by assuming that zero delta of sc->nr_scanned means full LRU
26505ee04716SVlastimil Babka 	 * scan, but that approximation was wrong, and there were corner cases
26515ee04716SVlastimil Babka 	 * where always a non-zero amount of pages were scanned.
26522876592fSMel Gorman 	 */
26532876592fSMel Gorman 	if (!nr_reclaimed)
26542876592fSMel Gorman 		return false;
26553e7d3449SMel Gorman 
26563e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2657a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2658a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
26596aa303deSMel Gorman 		if (!managed_zone(zone))
2660a9dd0a83SMel Gorman 			continue;
2661a9dd0a83SMel Gorman 
2662a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2663cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
26643e7d3449SMel Gorman 		case COMPACT_CONTINUE:
26653e7d3449SMel Gorman 			return false;
26663e7d3449SMel Gorman 		default:
2667a9dd0a83SMel Gorman 			/* check next zone */
2668a9dd0a83SMel Gorman 			;
26693e7d3449SMel Gorman 		}
26703e7d3449SMel Gorman 	}
26711c6c1597SHillf Danton 
26721c6c1597SHillf Danton 	/*
26731c6c1597SHillf Danton 	 * If we have not reclaimed enough pages for compaction and the
26741c6c1597SHillf Danton 	 * inactive lists are large enough, continue reclaiming
26751c6c1597SHillf Danton 	 */
26761c6c1597SHillf Danton 	pages_for_compaction = compact_gap(sc->order);
26771c6c1597SHillf Danton 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
26781c6c1597SHillf Danton 	if (get_nr_swap_pages() > 0)
26791c6c1597SHillf Danton 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
26801c6c1597SHillf Danton 
26815ee04716SVlastimil Babka 	return inactive_lru_pages > pages_for_compaction;
2682a9dd0a83SMel Gorman }
26833e7d3449SMel Gorman 
26840f6a5cffSJohannes Weiner static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
2685f16015fbSJohannes Weiner {
26860f6a5cffSJohannes Weiner 	struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
2687694fbc0fSAndrew Morton 	struct mem_cgroup *memcg;
2688d108c772SAndrey Ryabinin 
26890f6a5cffSJohannes Weiner 	memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
2690694fbc0fSAndrew Morton 	do {
2691afaf07a6SJohannes Weiner 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
26928e8ae645SJohannes Weiner 		unsigned long reclaimed;
2693cb731d6cSVladimir Davydov 		unsigned long scanned;
26949b4f98cdSJohannes Weiner 
26950f6a5cffSJohannes Weiner 		switch (mem_cgroup_protected(target_memcg, memcg)) {
2696bf8d5d52SRoman Gushchin 		case MEMCG_PROT_MIN:
2697bf8d5d52SRoman Gushchin 			/*
2698bf8d5d52SRoman Gushchin 			 * Hard protection.
2699bf8d5d52SRoman Gushchin 			 * If there is no reclaimable memory, OOM.
2700bf8d5d52SRoman Gushchin 			 */
2701bf8d5d52SRoman Gushchin 			continue;
2702bf8d5d52SRoman Gushchin 		case MEMCG_PROT_LOW:
2703bf8d5d52SRoman Gushchin 			/*
2704bf8d5d52SRoman Gushchin 			 * Soft protection.
2705bf8d5d52SRoman Gushchin 			 * Respect the protection only as long as
2706bf8d5d52SRoman Gushchin 			 * there is an unprotected supply
2707bf8d5d52SRoman Gushchin 			 * of reclaimable memory from other cgroups.
2708bf8d5d52SRoman Gushchin 			 */
2709d6622f63SYisheng Xie 			if (!sc->memcg_low_reclaim) {
2710d6622f63SYisheng Xie 				sc->memcg_low_skipped = 1;
2711241994edSJohannes Weiner 				continue;
2712d6622f63SYisheng Xie 			}
2713e27be240SJohannes Weiner 			memcg_memory_event(memcg, MEMCG_LOW);
2714bf8d5d52SRoman Gushchin 			break;
2715bf8d5d52SRoman Gushchin 		case MEMCG_PROT_NONE:
27169783aa99SChris Down 			/*
27179783aa99SChris Down 			 * All protection thresholds breached. We may
27189783aa99SChris Down 			 * still choose to vary the scan pressure
27199783aa99SChris Down 			 * applied based on by how much the cgroup in
27209783aa99SChris Down 			 * question has exceeded its protection
27219783aa99SChris Down 			 * thresholds (see get_scan_count).
27229783aa99SChris Down 			 */
2723bf8d5d52SRoman Gushchin 			break;
2724241994edSJohannes Weiner 		}
2725241994edSJohannes Weiner 
27268e8ae645SJohannes Weiner 		reclaimed = sc->nr_reclaimed;
2727cb731d6cSVladimir Davydov 		scanned = sc->nr_scanned;
2728afaf07a6SJohannes Weiner 
2729afaf07a6SJohannes Weiner 		shrink_lruvec(lruvec, sc);
2730f9be23d6SKonstantin Khlebnikov 
273128360f39SMel Gorman 		shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
273228360f39SMel Gorman 			    sc->priority);
2733cb731d6cSVladimir Davydov 
27348e8ae645SJohannes Weiner 		/* Record the group's reclaim efficiency */
27358e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, memcg, false,
27368e8ae645SJohannes Weiner 			   sc->nr_scanned - scanned,
27378e8ae645SJohannes Weiner 			   sc->nr_reclaimed - reclaimed);
27388e8ae645SJohannes Weiner 
27390f6a5cffSJohannes Weiner 	} while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
27400f6a5cffSJohannes Weiner }
27410f6a5cffSJohannes Weiner 
27420f6a5cffSJohannes Weiner static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc)
27430f6a5cffSJohannes Weiner {
27440f6a5cffSJohannes Weiner 	struct reclaim_state *reclaim_state = current->reclaim_state;
27450f6a5cffSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
2746*1b05117dSJohannes Weiner 	struct lruvec *target_lruvec;
27470f6a5cffSJohannes Weiner 	bool reclaimable = false;
27480f6a5cffSJohannes Weiner 
2749*1b05117dSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2750*1b05117dSJohannes Weiner 
27510f6a5cffSJohannes Weiner again:
27520f6a5cffSJohannes Weiner 	memset(&sc->nr, 0, sizeof(sc->nr));
27530f6a5cffSJohannes Weiner 
27540f6a5cffSJohannes Weiner 	nr_reclaimed = sc->nr_reclaimed;
27550f6a5cffSJohannes Weiner 	nr_scanned = sc->nr_scanned;
27560f6a5cffSJohannes Weiner 
27570f6a5cffSJohannes Weiner 	shrink_node_memcgs(pgdat, sc);
275870ddf637SAnton Vorontsov 
27596b4f7799SJohannes Weiner 	if (reclaim_state) {
2760cb731d6cSVladimir Davydov 		sc->nr_reclaimed += reclaim_state->reclaimed_slab;
27616b4f7799SJohannes Weiner 		reclaim_state->reclaimed_slab = 0;
27626b4f7799SJohannes Weiner 	}
27636b4f7799SJohannes Weiner 
27648e8ae645SJohannes Weiner 	/* Record the subtree's reclaim efficiency */
2765*1b05117dSJohannes Weiner 	vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
276670ddf637SAnton Vorontsov 		   sc->nr_scanned - nr_scanned,
276770ddf637SAnton Vorontsov 		   sc->nr_reclaimed - nr_reclaimed);
276870ddf637SAnton Vorontsov 
27692344d7e4SJohannes Weiner 	if (sc->nr_reclaimed - nr_reclaimed)
27702344d7e4SJohannes Weiner 		reclaimable = true;
27712344d7e4SJohannes Weiner 
2772e3c1ac58SAndrey Ryabinin 	if (current_is_kswapd()) {
2773d108c772SAndrey Ryabinin 		/*
2774e3c1ac58SAndrey Ryabinin 		 * If reclaim is isolating dirty pages under writeback,
2775e3c1ac58SAndrey Ryabinin 		 * it implies that the long-lived page allocation rate
2776e3c1ac58SAndrey Ryabinin 		 * is exceeding the page laundering rate. Either the
2777e3c1ac58SAndrey Ryabinin 		 * global limits are not being effective at throttling
2778e3c1ac58SAndrey Ryabinin 		 * processes due to the page distribution throughout
2779e3c1ac58SAndrey Ryabinin 		 * zones or there is heavy usage of a slow backing
2780e3c1ac58SAndrey Ryabinin 		 * device. The only option is to throttle from reclaim
2781e3c1ac58SAndrey Ryabinin 		 * context which is not ideal as there is no guarantee
2782d108c772SAndrey Ryabinin 		 * the dirtying process is throttled in the same way
2783d108c772SAndrey Ryabinin 		 * balance_dirty_pages() manages.
2784d108c772SAndrey Ryabinin 		 *
2785e3c1ac58SAndrey Ryabinin 		 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
2786e3c1ac58SAndrey Ryabinin 		 * count the number of pages under pages flagged for
2787e3c1ac58SAndrey Ryabinin 		 * immediate reclaim and stall if any are encountered
2788e3c1ac58SAndrey Ryabinin 		 * in the nr_immediate check below.
2789d108c772SAndrey Ryabinin 		 */
2790d108c772SAndrey Ryabinin 		if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
2791d108c772SAndrey Ryabinin 			set_bit(PGDAT_WRITEBACK, &pgdat->flags);
2792d108c772SAndrey Ryabinin 
2793d108c772SAndrey Ryabinin 		/* Allow kswapd to start writing pages during reclaim.*/
2794d108c772SAndrey Ryabinin 		if (sc->nr.unqueued_dirty == sc->nr.file_taken)
2795d108c772SAndrey Ryabinin 			set_bit(PGDAT_DIRTY, &pgdat->flags);
2796d108c772SAndrey Ryabinin 
2797d108c772SAndrey Ryabinin 		/*
2798d108c772SAndrey Ryabinin 		 * If kswapd scans pages marked marked for immediate
2799d108c772SAndrey Ryabinin 		 * reclaim and under writeback (nr_immediate), it
2800d108c772SAndrey Ryabinin 		 * implies that pages are cycling through the LRU
2801d108c772SAndrey Ryabinin 		 * faster than they are written so also forcibly stall.
2802d108c772SAndrey Ryabinin 		 */
2803d108c772SAndrey Ryabinin 		if (sc->nr.immediate)
2804d108c772SAndrey Ryabinin 			congestion_wait(BLK_RW_ASYNC, HZ/10);
2805d108c772SAndrey Ryabinin 	}
2806d108c772SAndrey Ryabinin 
2807d108c772SAndrey Ryabinin 	/*
2808*1b05117dSJohannes Weiner 	 * Tag a node/memcg as congested if all the dirty pages
2809*1b05117dSJohannes Weiner 	 * scanned were backed by a congested BDI and
2810*1b05117dSJohannes Weiner 	 * wait_iff_congested will stall.
2811*1b05117dSJohannes Weiner 	 *
2812e3c1ac58SAndrey Ryabinin 	 * Legacy memcg will stall in page writeback so avoid forcibly
2813e3c1ac58SAndrey Ryabinin 	 * stalling in wait_iff_congested().
2814e3c1ac58SAndrey Ryabinin 	 */
2815*1b05117dSJohannes Weiner 	if ((current_is_kswapd() ||
2816*1b05117dSJohannes Weiner 	     (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
2817e3c1ac58SAndrey Ryabinin 	    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
2818*1b05117dSJohannes Weiner 		set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
2819e3c1ac58SAndrey Ryabinin 
2820e3c1ac58SAndrey Ryabinin 	/*
2821d108c772SAndrey Ryabinin 	 * Stall direct reclaim for IO completions if underlying BDIs
2822d108c772SAndrey Ryabinin 	 * and node is congested. Allow kswapd to continue until it
2823d108c772SAndrey Ryabinin 	 * starts encountering unqueued dirty pages or cycling through
2824d108c772SAndrey Ryabinin 	 * the LRU too quickly.
2825d108c772SAndrey Ryabinin 	 */
2826*1b05117dSJohannes Weiner 	if (!current_is_kswapd() && current_may_throttle() &&
2827*1b05117dSJohannes Weiner 	    !sc->hibernation_mode &&
2828*1b05117dSJohannes Weiner 	    test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
2829e3c1ac58SAndrey Ryabinin 		wait_iff_congested(BLK_RW_ASYNC, HZ/10);
2830d108c772SAndrey Ryabinin 
2831d2af3397SJohannes Weiner 	if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
2832d2af3397SJohannes Weiner 				    sc))
2833d2af3397SJohannes Weiner 		goto again;
28342344d7e4SJohannes Weiner 
2835c73322d0SJohannes Weiner 	/*
2836c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
2837c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
2838c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
2839c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
2840c73322d0SJohannes Weiner 	 */
2841c73322d0SJohannes Weiner 	if (reclaimable)
2842c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
2843c73322d0SJohannes Weiner 
28442344d7e4SJohannes Weiner 	return reclaimable;
2845f16015fbSJohannes Weiner }
2846f16015fbSJohannes Weiner 
284753853e2dSVlastimil Babka /*
2848fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
2849fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
2850fdd4c614SVlastimil Babka  * should reclaim first.
285153853e2dSVlastimil Babka  */
28524f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2853fe4b1b24SMel Gorman {
285431483b6aSMel Gorman 	unsigned long watermark;
2855fdd4c614SVlastimil Babka 	enum compact_result suitable;
2856fe4b1b24SMel Gorman 
2857fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2858fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
2859fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
2860fdd4c614SVlastimil Babka 		return true;
2861fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
2862fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
2863fe4b1b24SMel Gorman 		return false;
2864fe4b1b24SMel Gorman 
2865fdd4c614SVlastimil Babka 	/*
2866fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
2867fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
2868fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
2869fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
2870fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
2871fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
2872fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
2873fdd4c614SVlastimil Babka 	 */
2874fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
2875fdd4c614SVlastimil Babka 
2876fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
2877fe4b1b24SMel Gorman }
2878fe4b1b24SMel Gorman 
28791da177e4SLinus Torvalds /*
28801da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
28811da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
28821da177e4SLinus Torvalds  * request.
28831da177e4SLinus Torvalds  *
28841da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
28851da177e4SLinus Torvalds  * scan then give up on it.
28861da177e4SLinus Torvalds  */
28870a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
28881da177e4SLinus Torvalds {
2889dd1a239fSMel Gorman 	struct zoneref *z;
289054a6eb5cSMel Gorman 	struct zone *zone;
28910608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
28920608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2893619d0d76SWeijie Yang 	gfp_t orig_mask;
289479dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
28951cfb419bSKAMEZAWA Hiroyuki 
2896cc715d99SMel Gorman 	/*
2897cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2898cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2899cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2900cc715d99SMel Gorman 	 */
2901619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2902b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
2903cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
29044f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
2905b2e18757SMel Gorman 	}
2906cc715d99SMel Gorman 
2907d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2908b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
2909b2e18757SMel Gorman 		/*
29101cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
29111cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
29121cfb419bSKAMEZAWA Hiroyuki 		 */
2913b5ead35eSJohannes Weiner 		if (!cgroup_reclaim(sc)) {
2914344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2915344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
29161da177e4SLinus Torvalds 				continue;
291765ec02cbSVladimir Davydov 
2918e0887c19SRik van Riel 			/*
2919e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2920e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2921e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2922e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2923e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2924c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2925c7cfa37bSCopot Alexandru 			 * page allocations.
2926e0887c19SRik van Riel 			 */
29270b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
29280b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
29294f588331SMel Gorman 			    compaction_ready(zone, sc)) {
29300b06496aSJohannes Weiner 				sc->compaction_ready = true;
2931e0887c19SRik van Riel 				continue;
2932e0887c19SRik van Riel 			}
29330b06496aSJohannes Weiner 
29340608f43dSAndrew Morton 			/*
293579dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
293679dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
293779dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
293879dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
293979dafcdcSMel Gorman 			 */
294079dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
294179dafcdcSMel Gorman 				continue;
294279dafcdcSMel Gorman 
294379dafcdcSMel Gorman 			/*
29440608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
29450608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
29460608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
29470608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
29480608f43dSAndrew Morton 			 */
29490608f43dSAndrew Morton 			nr_soft_scanned = 0;
2950ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
29510608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
29520608f43dSAndrew Morton 						&nr_soft_scanned);
29530608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
29540608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
2955ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2956ac34a1a3SKAMEZAWA Hiroyuki 		}
2957d149e3b2SYing Han 
295879dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
295979dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
296079dafcdcSMel Gorman 			continue;
296179dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
2962970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
29631da177e4SLinus Torvalds 	}
2964e0c23279SMel Gorman 
296565ec02cbSVladimir Davydov 	/*
2966619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2967619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
2968619d0d76SWeijie Yang 	 */
2969619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
29701da177e4SLinus Torvalds }
29711da177e4SLinus Torvalds 
29722a2e4885SJohannes Weiner static void snapshot_refaults(struct mem_cgroup *root_memcg, pg_data_t *pgdat)
29732a2e4885SJohannes Weiner {
29742a2e4885SJohannes Weiner 	struct mem_cgroup *memcg;
29752a2e4885SJohannes Weiner 
29762a2e4885SJohannes Weiner 	memcg = mem_cgroup_iter(root_memcg, NULL, NULL);
29772a2e4885SJohannes Weiner 	do {
29782a2e4885SJohannes Weiner 		unsigned long refaults;
29792a2e4885SJohannes Weiner 		struct lruvec *lruvec;
29802a2e4885SJohannes Weiner 
2981867e5e1dSJohannes Weiner 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
2982205b20ccSJohannes Weiner 		refaults = lruvec_page_state_local(lruvec, WORKINGSET_ACTIVATE);
29832a2e4885SJohannes Weiner 		lruvec->refaults = refaults;
29842a2e4885SJohannes Weiner 	} while ((memcg = mem_cgroup_iter(root_memcg, memcg, NULL)));
29852a2e4885SJohannes Weiner }
29862a2e4885SJohannes Weiner 
29871da177e4SLinus Torvalds /*
29881da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
29891da177e4SLinus Torvalds  *
29901da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
29911da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
29921da177e4SLinus Torvalds  *
29931da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
29941da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
29955b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
29965b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
29975b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
29985b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2999a41f24eaSNishanth Aravamudan  *
3000a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
3001a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
30021da177e4SLinus Torvalds  */
3003dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
30043115cd91SVladimir Davydov 					  struct scan_control *sc)
30051da177e4SLinus Torvalds {
3006241994edSJohannes Weiner 	int initial_priority = sc->priority;
30072a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
30082a2e4885SJohannes Weiner 	struct zoneref *z;
30092a2e4885SJohannes Weiner 	struct zone *zone;
3010241994edSJohannes Weiner retry:
3011873b4771SKeika Kobayashi 	delayacct_freepages_start();
3012873b4771SKeika Kobayashi 
3013b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
30147cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
30151da177e4SLinus Torvalds 
30169e3b2f8cSKonstantin Khlebnikov 	do {
301770ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
301870ddf637SAnton Vorontsov 				sc->priority);
301966e1707bSBalbir Singh 		sc->nr_scanned = 0;
30200a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
3021e0c23279SMel Gorman 
3022bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
30230b06496aSJohannes Weiner 			break;
30240b06496aSJohannes Weiner 
30250b06496aSJohannes Weiner 		if (sc->compaction_ready)
30260b06496aSJohannes Weiner 			break;
30271da177e4SLinus Torvalds 
30281da177e4SLinus Torvalds 		/*
30290e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
30300e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
30310e50ce3bSMinchan Kim 		 */
30320e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
30330e50ce3bSMinchan Kim 			sc->may_writepage = 1;
30340b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
3035bb21c7ceSKOSAKI Motohiro 
30362a2e4885SJohannes Weiner 	last_pgdat = NULL;
30372a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
30382a2e4885SJohannes Weiner 					sc->nodemask) {
30392a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
30402a2e4885SJohannes Weiner 			continue;
30412a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
3042*1b05117dSJohannes Weiner 
30432a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
3044*1b05117dSJohannes Weiner 
3045*1b05117dSJohannes Weiner 		if (cgroup_reclaim(sc)) {
3046*1b05117dSJohannes Weiner 			struct lruvec *lruvec;
3047*1b05117dSJohannes Weiner 
3048*1b05117dSJohannes Weiner 			lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
3049*1b05117dSJohannes Weiner 						   zone->zone_pgdat);
3050*1b05117dSJohannes Weiner 			clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3051*1b05117dSJohannes Weiner 		}
30522a2e4885SJohannes Weiner 	}
30532a2e4885SJohannes Weiner 
3054873b4771SKeika Kobayashi 	delayacct_freepages_end();
3055873b4771SKeika Kobayashi 
3056bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
3057bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
3058bb21c7ceSKOSAKI Motohiro 
30590cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
30600b06496aSJohannes Weiner 	if (sc->compaction_ready)
30617335084dSMel Gorman 		return 1;
30627335084dSMel Gorman 
3063241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
3064d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
3065241994edSJohannes Weiner 		sc->priority = initial_priority;
3066d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
3067d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
3068241994edSJohannes Weiner 		goto retry;
3069241994edSJohannes Weiner 	}
3070241994edSJohannes Weiner 
3071bb21c7ceSKOSAKI Motohiro 	return 0;
30721da177e4SLinus Torvalds }
30731da177e4SLinus Torvalds 
3074c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
30755515061dSMel Gorman {
30765515061dSMel Gorman 	struct zone *zone;
30775515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
30785515061dSMel Gorman 	unsigned long free_pages = 0;
30795515061dSMel Gorman 	int i;
30805515061dSMel Gorman 	bool wmark_ok;
30815515061dSMel Gorman 
3082c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3083c73322d0SJohannes Weiner 		return true;
3084c73322d0SJohannes Weiner 
30855515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
30865515061dSMel Gorman 		zone = &pgdat->node_zones[i];
3087d450abd8SJohannes Weiner 		if (!managed_zone(zone))
3088d450abd8SJohannes Weiner 			continue;
3089d450abd8SJohannes Weiner 
3090d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
3091675becceSMel Gorman 			continue;
3092675becceSMel Gorman 
30935515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
30945515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
30955515061dSMel Gorman 	}
30965515061dSMel Gorman 
3097675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
3098675becceSMel Gorman 	if (!pfmemalloc_reserve)
3099675becceSMel Gorman 		return true;
3100675becceSMel Gorman 
31015515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
31025515061dSMel Gorman 
31035515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
31045515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
310538087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
31065515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
31075515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
31085515061dSMel Gorman 	}
31095515061dSMel Gorman 
31105515061dSMel Gorman 	return wmark_ok;
31115515061dSMel Gorman }
31125515061dSMel Gorman 
31135515061dSMel Gorman /*
31145515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
31155515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
31165515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
311750694c28SMel Gorman  * when the low watermark is reached.
311850694c28SMel Gorman  *
311950694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
312050694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
31215515061dSMel Gorman  */
312250694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
31235515061dSMel Gorman 					nodemask_t *nodemask)
31245515061dSMel Gorman {
3125675becceSMel Gorman 	struct zoneref *z;
31265515061dSMel Gorman 	struct zone *zone;
3127675becceSMel Gorman 	pg_data_t *pgdat = NULL;
31285515061dSMel Gorman 
31295515061dSMel Gorman 	/*
31305515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
31315515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
31325515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
31335515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
31345515061dSMel Gorman 	 * processes to block on log_wait_commit().
31355515061dSMel Gorman 	 */
31365515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
313750694c28SMel Gorman 		goto out;
313850694c28SMel Gorman 
313950694c28SMel Gorman 	/*
314050694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
314150694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
314250694c28SMel Gorman 	 */
314350694c28SMel Gorman 	if (fatal_signal_pending(current))
314450694c28SMel Gorman 		goto out;
31455515061dSMel Gorman 
3146675becceSMel Gorman 	/*
3147675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
3148675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3149675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
3150675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
3151675becceSMel Gorman 	 *
3152675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
3153675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
3154675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
3155675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
3156675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
3157675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
3158675becceSMel Gorman 	 * should make reasonable progress.
3159675becceSMel Gorman 	 */
3160675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
316117636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
3162675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
3163675becceSMel Gorman 			continue;
3164675becceSMel Gorman 
3165675becceSMel Gorman 		/* Throttle based on the first usable node */
31665515061dSMel Gorman 		pgdat = zone->zone_pgdat;
3167c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
316850694c28SMel Gorman 			goto out;
3169675becceSMel Gorman 		break;
3170675becceSMel Gorman 	}
3171675becceSMel Gorman 
3172675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
3173675becceSMel Gorman 	if (!pgdat)
3174675becceSMel Gorman 		goto out;
31755515061dSMel Gorman 
317668243e76SMel Gorman 	/* Account for the throttling */
317768243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
317868243e76SMel Gorman 
31795515061dSMel Gorman 	/*
31805515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
31815515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
31825515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
31835515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
31845515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
31855515061dSMel Gorman 	 * second before continuing.
31865515061dSMel Gorman 	 */
31875515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
31885515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3189c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
319050694c28SMel Gorman 
319150694c28SMel Gorman 		goto check_pending;
31925515061dSMel Gorman 	}
31935515061dSMel Gorman 
31945515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
31955515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3196c73322d0SJohannes Weiner 		allow_direct_reclaim(pgdat));
319750694c28SMel Gorman 
319850694c28SMel Gorman check_pending:
319950694c28SMel Gorman 	if (fatal_signal_pending(current))
320050694c28SMel Gorman 		return true;
320150694c28SMel Gorman 
320250694c28SMel Gorman out:
320350694c28SMel Gorman 	return false;
32045515061dSMel Gorman }
32055515061dSMel Gorman 
3206dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3207327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
320866e1707bSBalbir Singh {
320933906bc5SMel Gorman 	unsigned long nr_reclaimed;
321066e1707bSBalbir Singh 	struct scan_control sc = {
321122fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3212f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3213b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
3214ee814fe2SJohannes Weiner 		.order = order,
3215ee814fe2SJohannes Weiner 		.nodemask = nodemask,
3216ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
3217ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3218a6dc60f8SJohannes Weiner 		.may_unmap = 1,
32192e2e4259SKOSAKI Motohiro 		.may_swap = 1,
322066e1707bSBalbir Singh 	};
322166e1707bSBalbir Singh 
32225515061dSMel Gorman 	/*
3223bb451fdfSGreg Thelen 	 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3224bb451fdfSGreg Thelen 	 * Confirm they are large enough for max values.
3225bb451fdfSGreg Thelen 	 */
3226bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3227bb451fdfSGreg Thelen 	BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3228bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3229bb451fdfSGreg Thelen 
3230bb451fdfSGreg Thelen 	/*
323150694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
323250694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
323350694c28SMel Gorman 	 * point.
32345515061dSMel Gorman 	 */
3235f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
32365515061dSMel Gorman 		return 1;
32375515061dSMel Gorman 
32381732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
32393481c37fSYafang Shao 	trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
324033906bc5SMel Gorman 
32413115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
324233906bc5SMel Gorman 
324333906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
32441732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
324533906bc5SMel Gorman 
324633906bc5SMel Gorman 	return nr_reclaimed;
324766e1707bSBalbir Singh }
324866e1707bSBalbir Singh 
3249c255a458SAndrew Morton #ifdef CONFIG_MEMCG
325066e1707bSBalbir Singh 
3251d2e5fb92SMichal Hocko /* Only used by soft limit reclaim. Do not reuse for anything else. */
3252a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
32534e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
3254ef8f2327SMel Gorman 						pg_data_t *pgdat,
32550ae5e89cSYing Han 						unsigned long *nr_scanned)
32564e416953SBalbir Singh {
3257afaf07a6SJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
32584e416953SBalbir Singh 	struct scan_control sc = {
3259b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3260ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
32614e416953SBalbir Singh 		.may_writepage = !laptop_mode,
32624e416953SBalbir Singh 		.may_unmap = 1,
3263b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
32644e416953SBalbir Singh 		.may_swap = !noswap,
32654e416953SBalbir Singh 	};
32660ae5e89cSYing Han 
3267d2e5fb92SMichal Hocko 	WARN_ON_ONCE(!current->reclaim_state);
3268d2e5fb92SMichal Hocko 
32694e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
32704e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3271bdce6d9eSKOSAKI Motohiro 
32729e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
32733481c37fSYafang Shao 						      sc.gfp_mask);
3274bdce6d9eSKOSAKI Motohiro 
32754e416953SBalbir Singh 	/*
32764e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
32774e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3278a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
32794e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
32804e416953SBalbir Singh 	 * the priority and make it zero.
32814e416953SBalbir Singh 	 */
3282afaf07a6SJohannes Weiner 	shrink_lruvec(lruvec, &sc);
3283bdce6d9eSKOSAKI Motohiro 
3284bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3285bdce6d9eSKOSAKI Motohiro 
32860ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
32870308f7cfSYafang Shao 
32884e416953SBalbir Singh 	return sc.nr_reclaimed;
32894e416953SBalbir Singh }
32904e416953SBalbir Singh 
329172835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3292b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
32938c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3294b70a2a21SJohannes Weiner 					   bool may_swap)
329566e1707bSBalbir Singh {
3296bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3297eb414681SJohannes Weiner 	unsigned long pflags;
3298499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
329966e1707bSBalbir Singh 	struct scan_control sc = {
3300b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
33017dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3302ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3303b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3304ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3305ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
330666e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3307a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3308b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3309a09ed5e0SYing Han 	};
3310fa40d1eeSShakeel Butt 	/*
3311fa40d1eeSShakeel Butt 	 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
3312fa40d1eeSShakeel Butt 	 * equal pressure on all the nodes. This is based on the assumption that
3313fa40d1eeSShakeel Butt 	 * the reclaim does not bail out early.
3314fa40d1eeSShakeel Butt 	 */
3315fa40d1eeSShakeel Butt 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
331666e1707bSBalbir Singh 
33171732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
3318bdce6d9eSKOSAKI Motohiro 
33193481c37fSYafang Shao 	trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
3320bdce6d9eSKOSAKI Motohiro 
3321eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
3322499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3323eb414681SJohannes Weiner 
33243115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3325eb414681SJohannes Weiner 
3326499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3327eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
3328bdce6d9eSKOSAKI Motohiro 
3329bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
33301732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3331bdce6d9eSKOSAKI Motohiro 
3332bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
333366e1707bSBalbir Singh }
333466e1707bSBalbir Singh #endif
333566e1707bSBalbir Singh 
33361d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3337ef8f2327SMel Gorman 				struct scan_control *sc)
3338f16015fbSJohannes Weiner {
3339b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3340b95a2f2dSJohannes Weiner 
3341b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3342b95a2f2dSJohannes Weiner 		return;
3343b95a2f2dSJohannes Weiner 
3344b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3345b95a2f2dSJohannes Weiner 	do {
3346867e5e1dSJohannes Weiner 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3347f16015fbSJohannes Weiner 
33483b991208SJohannes Weiner 		if (inactive_list_is_low(lruvec, false, sc, true))
33491a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
33509e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
3351b95a2f2dSJohannes Weiner 
3352b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3353b95a2f2dSJohannes Weiner 	} while (memcg);
3354f16015fbSJohannes Weiner }
3355f16015fbSJohannes Weiner 
33561c30844dSMel Gorman static bool pgdat_watermark_boosted(pg_data_t *pgdat, int classzone_idx)
33571c30844dSMel Gorman {
33581c30844dSMel Gorman 	int i;
33591c30844dSMel Gorman 	struct zone *zone;
33601c30844dSMel Gorman 
33611c30844dSMel Gorman 	/*
33621c30844dSMel Gorman 	 * Check for watermark boosts top-down as the higher zones
33631c30844dSMel Gorman 	 * are more likely to be boosted. Both watermarks and boosts
33641c30844dSMel Gorman 	 * should not be checked at the time time as reclaim would
33651c30844dSMel Gorman 	 * start prematurely when there is no boosting and a lower
33661c30844dSMel Gorman 	 * zone is balanced.
33671c30844dSMel Gorman 	 */
33681c30844dSMel Gorman 	for (i = classzone_idx; i >= 0; i--) {
33691c30844dSMel Gorman 		zone = pgdat->node_zones + i;
33701c30844dSMel Gorman 		if (!managed_zone(zone))
33711c30844dSMel Gorman 			continue;
33721c30844dSMel Gorman 
33731c30844dSMel Gorman 		if (zone->watermark_boost)
33741c30844dSMel Gorman 			return true;
33751c30844dSMel Gorman 	}
33761c30844dSMel Gorman 
33771c30844dSMel Gorman 	return false;
33781c30844dSMel Gorman }
33791c30844dSMel Gorman 
3380e716f2ebSMel Gorman /*
3381e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
3382e716f2ebSMel Gorman  * and classzone_idx
3383e716f2ebSMel Gorman  */
3384e716f2ebSMel Gorman static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
338560cefed4SJohannes Weiner {
3386e716f2ebSMel Gorman 	int i;
3387e716f2ebSMel Gorman 	unsigned long mark = -1;
3388e716f2ebSMel Gorman 	struct zone *zone;
338960cefed4SJohannes Weiner 
33901c30844dSMel Gorman 	/*
33911c30844dSMel Gorman 	 * Check watermarks bottom-up as lower zones are more likely to
33921c30844dSMel Gorman 	 * meet watermarks.
33931c30844dSMel Gorman 	 */
3394e716f2ebSMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
3395e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
33966256c6b4SMel Gorman 
3397e716f2ebSMel Gorman 		if (!managed_zone(zone))
3398e716f2ebSMel Gorman 			continue;
3399e716f2ebSMel Gorman 
3400e716f2ebSMel Gorman 		mark = high_wmark_pages(zone);
3401e716f2ebSMel Gorman 		if (zone_watermark_ok_safe(zone, order, mark, classzone_idx))
34026256c6b4SMel Gorman 			return true;
340360cefed4SJohannes Weiner 	}
340460cefed4SJohannes Weiner 
3405e716f2ebSMel Gorman 	/*
3406e716f2ebSMel Gorman 	 * If a node has no populated zone within classzone_idx, it does not
3407e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3408e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3409e716f2ebSMel Gorman 	 */
3410e716f2ebSMel Gorman 	if (mark == -1)
3411e716f2ebSMel Gorman 		return true;
3412e716f2ebSMel Gorman 
3413e716f2ebSMel Gorman 	return false;
3414e716f2ebSMel Gorman }
3415e716f2ebSMel Gorman 
3416631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
3417631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
3418631b6e08SMel Gorman {
3419*1b05117dSJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
3420*1b05117dSJohannes Weiner 
3421*1b05117dSJohannes Weiner 	clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3422631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
3423631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3424631b6e08SMel Gorman }
3425631b6e08SMel Gorman 
34261741c877SMel Gorman /*
34275515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
34285515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
34295515061dSMel Gorman  *
34305515061dSMel Gorman  * Returns true if kswapd is ready to sleep
34315515061dSMel Gorman  */
3432d9f21d42SMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3433f50de2d3SMel Gorman {
34345515061dSMel Gorman 	/*
34359e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3436c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
34379e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
34389e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
34399e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
34409e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
34419e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
34429e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
34439e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
34449e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
34459e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
34465515061dSMel Gorman 	 */
34479e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
34489e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3449f50de2d3SMel Gorman 
3450c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3451c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3452c73322d0SJohannes Weiner 		return true;
3453c73322d0SJohannes Weiner 
3454e716f2ebSMel Gorman 	if (pgdat_balanced(pgdat, order, classzone_idx)) {
3455631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
3456333b0a45SShantanu Goel 		return true;
34571d82de61SMel Gorman 	}
34581d82de61SMel Gorman 
3459333b0a45SShantanu Goel 	return false;
3460f50de2d3SMel Gorman }
3461f50de2d3SMel Gorman 
34621da177e4SLinus Torvalds /*
34631d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
34641d82de61SMel Gorman  * zone that is currently unbalanced.
3465b8e83b94SMel Gorman  *
3466b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3467283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3468283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
346975485363SMel Gorman  */
34701d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3471accf6242SVlastimil Babka 			       struct scan_control *sc)
347275485363SMel Gorman {
34731d82de61SMel Gorman 	struct zone *zone;
34741d82de61SMel Gorman 	int z;
347575485363SMel Gorman 
34761d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
34771d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3478970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
34791d82de61SMel Gorman 		zone = pgdat->node_zones + z;
34806aa303deSMel Gorman 		if (!managed_zone(zone))
34811d82de61SMel Gorman 			continue;
34827c954f6dSMel Gorman 
34831d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
34847c954f6dSMel Gorman 	}
34857c954f6dSMel Gorman 
34861d82de61SMel Gorman 	/*
34871d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
34881d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
34891d82de61SMel Gorman 	 */
3490970a39a3SMel Gorman 	shrink_node(pgdat, sc);
34911d82de61SMel Gorman 
34921d82de61SMel Gorman 	/*
34931d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
34941d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
34951d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
34961d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
34971d82de61SMel Gorman 	 * can direct reclaim/compact.
34981d82de61SMel Gorman 	 */
34999861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
35001d82de61SMel Gorman 		sc->order = 0;
35011d82de61SMel Gorman 
3502b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
350375485363SMel Gorman }
350475485363SMel Gorman 
350575485363SMel Gorman /*
35061d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
35071d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
35081d82de61SMel Gorman  * balanced.
35091da177e4SLinus Torvalds  *
35101d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
35111da177e4SLinus Torvalds  *
35121da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
351341858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
35148bb4e7a2SWei Yang  * found to have free_pages <= high_wmark_pages(zone), any page in that zone
35151d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
35161d82de61SMel Gorman  * balanced.
35171da177e4SLinus Torvalds  */
3518accf6242SVlastimil Babka static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
35191da177e4SLinus Torvalds {
35201da177e4SLinus Torvalds 	int i;
35210608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
35220608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3523eb414681SJohannes Weiner 	unsigned long pflags;
35241c30844dSMel Gorman 	unsigned long nr_boost_reclaim;
35251c30844dSMel Gorman 	unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
35261c30844dSMel Gorman 	bool boosted;
35271d82de61SMel Gorman 	struct zone *zone;
3528179e9639SAndrew Morton 	struct scan_control sc = {
3529179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3530ee814fe2SJohannes Weiner 		.order = order,
3531a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3532179e9639SAndrew Morton 	};
353393781325SOmar Sandoval 
35341732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
3535eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
353693781325SOmar Sandoval 	__fs_reclaim_acquire();
353793781325SOmar Sandoval 
3538f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
35391da177e4SLinus Torvalds 
35401c30844dSMel Gorman 	/*
35411c30844dSMel Gorman 	 * Account for the reclaim boost. Note that the zone boost is left in
35421c30844dSMel Gorman 	 * place so that parallel allocations that are near the watermark will
35431c30844dSMel Gorman 	 * stall or direct reclaim until kswapd is finished.
35441c30844dSMel Gorman 	 */
35451c30844dSMel Gorman 	nr_boost_reclaim = 0;
35461c30844dSMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
35471c30844dSMel Gorman 		zone = pgdat->node_zones + i;
35481c30844dSMel Gorman 		if (!managed_zone(zone))
35491c30844dSMel Gorman 			continue;
35501c30844dSMel Gorman 
35511c30844dSMel Gorman 		nr_boost_reclaim += zone->watermark_boost;
35521c30844dSMel Gorman 		zone_boosts[i] = zone->watermark_boost;
35531c30844dSMel Gorman 	}
35541c30844dSMel Gorman 	boosted = nr_boost_reclaim;
35551c30844dSMel Gorman 
35561c30844dSMel Gorman restart:
35571c30844dSMel Gorman 	sc.priority = DEF_PRIORITY;
35589e3b2f8cSKonstantin Khlebnikov 	do {
3559c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
3560b8e83b94SMel Gorman 		bool raise_priority = true;
35611c30844dSMel Gorman 		bool balanced;
356293781325SOmar Sandoval 		bool ret;
3563b8e83b94SMel Gorman 
356484c7a777SMel Gorman 		sc.reclaim_idx = classzone_idx;
35651da177e4SLinus Torvalds 
356686c79f6bSMel Gorman 		/*
356784c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
356884c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
356984c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
357084c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
357184c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
357284c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
357384c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
357484c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
357586c79f6bSMel Gorman 		 */
357686c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
357786c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
357886c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
35796aa303deSMel Gorman 				if (!managed_zone(zone))
358086c79f6bSMel Gorman 					continue;
358186c79f6bSMel Gorman 
3582970a39a3SMel Gorman 				sc.reclaim_idx = i;
358386c79f6bSMel Gorman 				break;
358486c79f6bSMel Gorman 			}
358586c79f6bSMel Gorman 		}
358686c79f6bSMel Gorman 
358786c79f6bSMel Gorman 		/*
35881c30844dSMel Gorman 		 * If the pgdat is imbalanced then ignore boosting and preserve
35891c30844dSMel Gorman 		 * the watermarks for a later time and restart. Note that the
35901c30844dSMel Gorman 		 * zone watermarks will be still reset at the end of balancing
35911c30844dSMel Gorman 		 * on the grounds that the normal reclaim should be enough to
35921c30844dSMel Gorman 		 * re-evaluate if boosting is required when kswapd next wakes.
359386c79f6bSMel Gorman 		 */
35941c30844dSMel Gorman 		balanced = pgdat_balanced(pgdat, sc.order, classzone_idx);
35951c30844dSMel Gorman 		if (!balanced && nr_boost_reclaim) {
35961c30844dSMel Gorman 			nr_boost_reclaim = 0;
35971c30844dSMel Gorman 			goto restart;
35981c30844dSMel Gorman 		}
35991c30844dSMel Gorman 
36001c30844dSMel Gorman 		/*
36011c30844dSMel Gorman 		 * If boosting is not active then only reclaim if there are no
36021c30844dSMel Gorman 		 * eligible zones. Note that sc.reclaim_idx is not used as
36031c30844dSMel Gorman 		 * buffer_heads_over_limit may have adjusted it.
36041c30844dSMel Gorman 		 */
36051c30844dSMel Gorman 		if (!nr_boost_reclaim && balanced)
36061da177e4SLinus Torvalds 			goto out;
3607e1dbeda6SAndrew Morton 
36081c30844dSMel Gorman 		/* Limit the priority of boosting to avoid reclaim writeback */
36091c30844dSMel Gorman 		if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
36101c30844dSMel Gorman 			raise_priority = false;
36111c30844dSMel Gorman 
36121c30844dSMel Gorman 		/*
36131c30844dSMel Gorman 		 * Do not writeback or swap pages for boosted reclaim. The
36141c30844dSMel Gorman 		 * intent is to relieve pressure not issue sub-optimal IO
36151c30844dSMel Gorman 		 * from reclaim context. If no pages are reclaimed, the
36161c30844dSMel Gorman 		 * reclaim will be aborted.
36171c30844dSMel Gorman 		 */
36181c30844dSMel Gorman 		sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
36191c30844dSMel Gorman 		sc.may_swap = !nr_boost_reclaim;
36201c30844dSMel Gorman 
36211da177e4SLinus Torvalds 		/*
36221d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
36231d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
36241d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
36251d82de61SMel Gorman 		 * about consistent aging.
36261d82de61SMel Gorman 		 */
3627ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
36281d82de61SMel Gorman 
36291d82de61SMel Gorman 		/*
3630b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3631b7ea3c41SMel Gorman 		 * even in laptop mode.
3632b7ea3c41SMel Gorman 		 */
3633047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
3634b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3635b7ea3c41SMel Gorman 
36361d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
36371da177e4SLinus Torvalds 		sc.nr_scanned = 0;
36380608f43dSAndrew Morton 		nr_soft_scanned = 0;
3639ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
36401d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
36410608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
36420608f43dSAndrew Morton 
364332a4330dSRik van Riel 		/*
36441d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
36451d82de61SMel Gorman 		 * enough pages are already being scanned that that high
36461d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
364732a4330dSRik van Riel 		 */
3648970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3649b8e83b94SMel Gorman 			raise_priority = false;
3650d7868daeSMel Gorman 
36515515061dSMel Gorman 		/*
36525515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
36535515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
36545515061dSMel Gorman 		 * able to safely make forward progress. Wake them
36555515061dSMel Gorman 		 */
36565515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3657c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
3658cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
36595515061dSMel Gorman 
3660b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
366193781325SOmar Sandoval 		__fs_reclaim_release();
366293781325SOmar Sandoval 		ret = try_to_freeze();
366393781325SOmar Sandoval 		__fs_reclaim_acquire();
366493781325SOmar Sandoval 		if (ret || kthread_should_stop())
3665b8e83b94SMel Gorman 			break;
3666b8e83b94SMel Gorman 
3667b8e83b94SMel Gorman 		/*
3668b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3669b8e83b94SMel Gorman 		 * progress in reclaiming pages
3670b8e83b94SMel Gorman 		 */
3671c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
36721c30844dSMel Gorman 		nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
36731c30844dSMel Gorman 
36741c30844dSMel Gorman 		/*
36751c30844dSMel Gorman 		 * If reclaim made no progress for a boost, stop reclaim as
36761c30844dSMel Gorman 		 * IO cannot be queued and it could be an infinite loop in
36771c30844dSMel Gorman 		 * extreme circumstances.
36781c30844dSMel Gorman 		 */
36791c30844dSMel Gorman 		if (nr_boost_reclaim && !nr_reclaimed)
36801c30844dSMel Gorman 			break;
36811c30844dSMel Gorman 
3682c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
3683b8e83b94SMel Gorman 			sc.priority--;
36841d82de61SMel Gorman 	} while (sc.priority >= 1);
36851da177e4SLinus Torvalds 
3686c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
3687c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
3688c73322d0SJohannes Weiner 
3689b8e83b94SMel Gorman out:
36901c30844dSMel Gorman 	/* If reclaim was boosted, account for the reclaim done in this pass */
36911c30844dSMel Gorman 	if (boosted) {
36921c30844dSMel Gorman 		unsigned long flags;
36931c30844dSMel Gorman 
36941c30844dSMel Gorman 		for (i = 0; i <= classzone_idx; i++) {
36951c30844dSMel Gorman 			if (!zone_boosts[i])
36961c30844dSMel Gorman 				continue;
36971c30844dSMel Gorman 
36981c30844dSMel Gorman 			/* Increments are under the zone lock */
36991c30844dSMel Gorman 			zone = pgdat->node_zones + i;
37001c30844dSMel Gorman 			spin_lock_irqsave(&zone->lock, flags);
37011c30844dSMel Gorman 			zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
37021c30844dSMel Gorman 			spin_unlock_irqrestore(&zone->lock, flags);
37031c30844dSMel Gorman 		}
37041c30844dSMel Gorman 
37051c30844dSMel Gorman 		/*
37061c30844dSMel Gorman 		 * As there is now likely space, wakeup kcompact to defragment
37071c30844dSMel Gorman 		 * pageblocks.
37081c30844dSMel Gorman 		 */
37091c30844dSMel Gorman 		wakeup_kcompactd(pgdat, pageblock_order, classzone_idx);
37101c30844dSMel Gorman 	}
37111c30844dSMel Gorman 
37122a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
371393781325SOmar Sandoval 	__fs_reclaim_release();
3714eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
37151732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3716e5ca8071SYafang Shao 
37170abdee2bSMel Gorman 	/*
37181d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
37191d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
37201d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
37211d82de61SMel Gorman 	 * remain at the higher level.
37220abdee2bSMel Gorman 	 */
37231d82de61SMel Gorman 	return sc.order;
37241da177e4SLinus Torvalds }
37251da177e4SLinus Torvalds 
3726e716f2ebSMel Gorman /*
3727dffcac2cSShakeel Butt  * The pgdat->kswapd_classzone_idx is used to pass the highest zone index to be
3728dffcac2cSShakeel Butt  * reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is not
3729dffcac2cSShakeel Butt  * a valid index then either kswapd runs for first time or kswapd couldn't sleep
3730dffcac2cSShakeel Butt  * after previous reclaim attempt (node is still unbalanced). In that case
3731dffcac2cSShakeel Butt  * return the zone index of the previous kswapd reclaim cycle.
3732e716f2ebSMel Gorman  */
3733e716f2ebSMel Gorman static enum zone_type kswapd_classzone_idx(pg_data_t *pgdat,
3734dffcac2cSShakeel Butt 					   enum zone_type prev_classzone_idx)
3735e716f2ebSMel Gorman {
3736e716f2ebSMel Gorman 	if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3737dffcac2cSShakeel Butt 		return prev_classzone_idx;
3738dffcac2cSShakeel Butt 	return pgdat->kswapd_classzone_idx;
3739e716f2ebSMel Gorman }
3740e716f2ebSMel Gorman 
374138087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
374238087d9bSMel Gorman 				unsigned int classzone_idx)
3743f0bc0a60SKOSAKI Motohiro {
3744f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3745f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3746f0bc0a60SKOSAKI Motohiro 
3747f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3748f0bc0a60SKOSAKI Motohiro 		return;
3749f0bc0a60SKOSAKI Motohiro 
3750f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3751f0bc0a60SKOSAKI Motohiro 
3752333b0a45SShantanu Goel 	/*
3753333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
3754333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
3755333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
3756333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
3757333b0a45SShantanu Goel 	 * succeed.
3758333b0a45SShantanu Goel 	 */
3759d9f21d42SMel Gorman 	if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3760fd901c95SVlastimil Babka 		/*
3761fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3762fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3763fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3764fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3765fd901c95SVlastimil Babka 		 */
3766fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3767fd901c95SVlastimil Babka 
3768fd901c95SVlastimil Babka 		/*
3769fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3770fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3771fd901c95SVlastimil Babka 		 */
377238087d9bSMel Gorman 		wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
3773fd901c95SVlastimil Babka 
3774f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
377538087d9bSMel Gorman 
377638087d9bSMel Gorman 		/*
377738087d9bSMel Gorman 		 * If woken prematurely then reset kswapd_classzone_idx and
377838087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
377938087d9bSMel Gorman 		 * the previous request that slept prematurely.
378038087d9bSMel Gorman 		 */
378138087d9bSMel Gorman 		if (remaining) {
3782e716f2ebSMel Gorman 			pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
378338087d9bSMel Gorman 			pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
378438087d9bSMel Gorman 		}
378538087d9bSMel Gorman 
3786f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3787f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3788f0bc0a60SKOSAKI Motohiro 	}
3789f0bc0a60SKOSAKI Motohiro 
3790f0bc0a60SKOSAKI Motohiro 	/*
3791f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3792f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3793f0bc0a60SKOSAKI Motohiro 	 */
3794d9f21d42SMel Gorman 	if (!remaining &&
3795d9f21d42SMel Gorman 	    prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3796f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3797f0bc0a60SKOSAKI Motohiro 
3798f0bc0a60SKOSAKI Motohiro 		/*
3799f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3800f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3801f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3802f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3803f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3804f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3805f0bc0a60SKOSAKI Motohiro 		 */
3806f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
38071c7e7f6cSAaditya Kumar 
38081c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3809f0bc0a60SKOSAKI Motohiro 			schedule();
38101c7e7f6cSAaditya Kumar 
3811f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3812f0bc0a60SKOSAKI Motohiro 	} else {
3813f0bc0a60SKOSAKI Motohiro 		if (remaining)
3814f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3815f0bc0a60SKOSAKI Motohiro 		else
3816f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3817f0bc0a60SKOSAKI Motohiro 	}
3818f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3819f0bc0a60SKOSAKI Motohiro }
3820f0bc0a60SKOSAKI Motohiro 
38211da177e4SLinus Torvalds /*
38221da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
38231da177e4SLinus Torvalds  * from the init process.
38241da177e4SLinus Torvalds  *
38251da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
38261da177e4SLinus Torvalds  * free memory available even if there is no other activity
38271da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
38281da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
38291da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
38301da177e4SLinus Torvalds  *
38311da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
38321da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
38331da177e4SLinus Torvalds  */
38341da177e4SLinus Torvalds static int kswapd(void *p)
38351da177e4SLinus Torvalds {
3836e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
3837e716f2ebSMel Gorman 	unsigned int classzone_idx = MAX_NR_ZONES - 1;
38381da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
38391da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3840a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
38411da177e4SLinus Torvalds 
3842174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3843c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
38441da177e4SLinus Torvalds 
38451da177e4SLinus Torvalds 	/*
38461da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
38471da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
38481da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
38491da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
38501da177e4SLinus Torvalds 	 *
38511da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
38521da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
38531da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
38541da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
38551da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
38561da177e4SLinus Torvalds 	 */
3857930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
385883144186SRafael J. Wysocki 	set_freezable();
38591da177e4SLinus Torvalds 
3860e716f2ebSMel Gorman 	pgdat->kswapd_order = 0;
3861e716f2ebSMel Gorman 	pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
38621da177e4SLinus Torvalds 	for ( ; ; ) {
38636f6313d4SJeff Liu 		bool ret;
38643e1d1d28SChristoph Lameter 
3865e716f2ebSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3866e716f2ebSMel Gorman 		classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
3867e716f2ebSMel Gorman 
386838087d9bSMel Gorman kswapd_try_sleep:
386938087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
387038087d9bSMel Gorman 					classzone_idx);
3871215ddd66SMel Gorman 
387238087d9bSMel Gorman 		/* Read the new order and classzone_idx */
387338087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3874dffcac2cSShakeel Butt 		classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
387538087d9bSMel Gorman 		pgdat->kswapd_order = 0;
3876e716f2ebSMel Gorman 		pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
38771da177e4SLinus Torvalds 
38788fe23e05SDavid Rientjes 		ret = try_to_freeze();
38798fe23e05SDavid Rientjes 		if (kthread_should_stop())
38808fe23e05SDavid Rientjes 			break;
38818fe23e05SDavid Rientjes 
38828fe23e05SDavid Rientjes 		/*
38838fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
38848fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3885b1296cc4SRafael J. Wysocki 		 */
388638087d9bSMel Gorman 		if (ret)
388738087d9bSMel Gorman 			continue;
38881d82de61SMel Gorman 
388938087d9bSMel Gorman 		/*
389038087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
389138087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
389238087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
389338087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
389438087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
389538087d9bSMel Gorman 		 * request (alloc_order).
389638087d9bSMel Gorman 		 */
3897e5146b12SMel Gorman 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
3898e5146b12SMel Gorman 						alloc_order);
389938087d9bSMel Gorman 		reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
390038087d9bSMel Gorman 		if (reclaim_order < alloc_order)
390138087d9bSMel Gorman 			goto kswapd_try_sleep;
390233906bc5SMel Gorman 	}
3903b0a8cc58STakamori Yamaguchi 
390471abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
390571abdc15SJohannes Weiner 
39061da177e4SLinus Torvalds 	return 0;
39071da177e4SLinus Torvalds }
39081da177e4SLinus Torvalds 
39091da177e4SLinus Torvalds /*
39105ecd9d40SDavid Rientjes  * A zone is low on free memory or too fragmented for high-order memory.  If
39115ecd9d40SDavid Rientjes  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
39125ecd9d40SDavid Rientjes  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
39135ecd9d40SDavid Rientjes  * has failed or is not needed, still wake up kcompactd if only compaction is
39145ecd9d40SDavid Rientjes  * needed.
39151da177e4SLinus Torvalds  */
39165ecd9d40SDavid Rientjes void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
39175ecd9d40SDavid Rientjes 		   enum zone_type classzone_idx)
39181da177e4SLinus Torvalds {
39191da177e4SLinus Torvalds 	pg_data_t *pgdat;
39201da177e4SLinus Torvalds 
39216aa303deSMel Gorman 	if (!managed_zone(zone))
39221da177e4SLinus Torvalds 		return;
39231da177e4SLinus Torvalds 
39245ecd9d40SDavid Rientjes 	if (!cpuset_zone_allowed(zone, gfp_flags))
39251da177e4SLinus Torvalds 		return;
392688f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
3927dffcac2cSShakeel Butt 
3928dffcac2cSShakeel Butt 	if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3929dffcac2cSShakeel Butt 		pgdat->kswapd_classzone_idx = classzone_idx;
3930dffcac2cSShakeel Butt 	else
3931dffcac2cSShakeel Butt 		pgdat->kswapd_classzone_idx = max(pgdat->kswapd_classzone_idx,
3932e716f2ebSMel Gorman 						  classzone_idx);
393338087d9bSMel Gorman 	pgdat->kswapd_order = max(pgdat->kswapd_order, order);
39348d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
39351da177e4SLinus Torvalds 		return;
3936e1a55637SMel Gorman 
39375ecd9d40SDavid Rientjes 	/* Hopeless node, leave it to direct reclaim if possible */
39385ecd9d40SDavid Rientjes 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
39391c30844dSMel Gorman 	    (pgdat_balanced(pgdat, order, classzone_idx) &&
39401c30844dSMel Gorman 	     !pgdat_watermark_boosted(pgdat, classzone_idx))) {
39415ecd9d40SDavid Rientjes 		/*
39425ecd9d40SDavid Rientjes 		 * There may be plenty of free memory available, but it's too
39435ecd9d40SDavid Rientjes 		 * fragmented for high-order allocations.  Wake up kcompactd
39445ecd9d40SDavid Rientjes 		 * and rely on compaction_suitable() to determine if it's
39455ecd9d40SDavid Rientjes 		 * needed.  If it fails, it will defer subsequent attempts to
39465ecd9d40SDavid Rientjes 		 * ratelimit its work.
39475ecd9d40SDavid Rientjes 		 */
39485ecd9d40SDavid Rientjes 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
39495ecd9d40SDavid Rientjes 			wakeup_kcompactd(pgdat, order, classzone_idx);
3950c73322d0SJohannes Weiner 		return;
39515ecd9d40SDavid Rientjes 	}
3952c73322d0SJohannes Weiner 
39535ecd9d40SDavid Rientjes 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, classzone_idx, order,
39545ecd9d40SDavid Rientjes 				      gfp_flags);
39558d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
39561da177e4SLinus Torvalds }
39571da177e4SLinus Torvalds 
3958c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
39591da177e4SLinus Torvalds /*
39607b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3961d6277db4SRafael J. Wysocki  * freed pages.
3962d6277db4SRafael J. Wysocki  *
3963d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3964d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3965d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
39661da177e4SLinus Torvalds  */
39677b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
39681da177e4SLinus Torvalds {
3969d6277db4SRafael J. Wysocki 	struct scan_control sc = {
39707b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
3971ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
3972b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
39739e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
3974ee814fe2SJohannes Weiner 		.may_writepage = 1,
3975ee814fe2SJohannes Weiner 		.may_unmap = 1,
3976ee814fe2SJohannes Weiner 		.may_swap = 1,
3977ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
39781da177e4SLinus Torvalds 	};
39797b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
39807b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3981499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
39821da177e4SLinus Torvalds 
3983d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
398493781325SOmar Sandoval 	noreclaim_flag = memalloc_noreclaim_save();
39851732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
3986d6277db4SRafael J. Wysocki 
39873115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3988d6277db4SRafael J. Wysocki 
39891732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3990499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
399193781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
3992d6277db4SRafael J. Wysocki 
39937b51755cSKOSAKI Motohiro 	return nr_reclaimed;
39941da177e4SLinus Torvalds }
3995c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
39961da177e4SLinus Torvalds 
39971da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
39981da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
39991da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
40001da177e4SLinus Torvalds    restore their cpu bindings. */
4001517bbed9SSebastian Andrzej Siewior static int kswapd_cpu_online(unsigned int cpu)
40021da177e4SLinus Torvalds {
400358c0a4a7SYasunori Goto 	int nid;
40041da177e4SLinus Torvalds 
400548fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY) {
4006c5f59f08SMike Travis 		pg_data_t *pgdat = NODE_DATA(nid);
4007a70f7302SRusty Russell 		const struct cpumask *mask;
4008a70f7302SRusty Russell 
4009a70f7302SRusty Russell 		mask = cpumask_of_node(pgdat->node_id);
4010c5f59f08SMike Travis 
40113e597945SRusty Russell 		if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
40121da177e4SLinus Torvalds 			/* One of our CPUs online: restore mask */
4013c5f59f08SMike Travis 			set_cpus_allowed_ptr(pgdat->kswapd, mask);
40141da177e4SLinus Torvalds 	}
4015517bbed9SSebastian Andrzej Siewior 	return 0;
40161da177e4SLinus Torvalds }
40171da177e4SLinus Torvalds 
40183218ae14SYasunori Goto /*
40193218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
40203218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
40213218ae14SYasunori Goto  */
40223218ae14SYasunori Goto int kswapd_run(int nid)
40233218ae14SYasunori Goto {
40243218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
40253218ae14SYasunori Goto 	int ret = 0;
40263218ae14SYasunori Goto 
40273218ae14SYasunori Goto 	if (pgdat->kswapd)
40283218ae14SYasunori Goto 		return 0;
40293218ae14SYasunori Goto 
40303218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
40313218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
40323218ae14SYasunori Goto 		/* failure at boot is fatal */
4033c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
4034d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
4035d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
4036d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
40373218ae14SYasunori Goto 	}
40383218ae14SYasunori Goto 	return ret;
40393218ae14SYasunori Goto }
40403218ae14SYasunori Goto 
40418fe23e05SDavid Rientjes /*
4042d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
4043bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
40448fe23e05SDavid Rientjes  */
40458fe23e05SDavid Rientjes void kswapd_stop(int nid)
40468fe23e05SDavid Rientjes {
40478fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
40488fe23e05SDavid Rientjes 
4049d8adde17SJiang Liu 	if (kswapd) {
40508fe23e05SDavid Rientjes 		kthread_stop(kswapd);
4051d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
4052d8adde17SJiang Liu 	}
40538fe23e05SDavid Rientjes }
40548fe23e05SDavid Rientjes 
40551da177e4SLinus Torvalds static int __init kswapd_init(void)
40561da177e4SLinus Torvalds {
4057517bbed9SSebastian Andrzej Siewior 	int nid, ret;
405869e05944SAndrew Morton 
40591da177e4SLinus Torvalds 	swap_setup();
406048fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
40613218ae14SYasunori Goto  		kswapd_run(nid);
4062517bbed9SSebastian Andrzej Siewior 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
4063517bbed9SSebastian Andrzej Siewior 					"mm/vmscan:online", kswapd_cpu_online,
4064517bbed9SSebastian Andrzej Siewior 					NULL);
4065517bbed9SSebastian Andrzej Siewior 	WARN_ON(ret < 0);
40661da177e4SLinus Torvalds 	return 0;
40671da177e4SLinus Torvalds }
40681da177e4SLinus Torvalds 
40691da177e4SLinus Torvalds module_init(kswapd_init)
40709eeff239SChristoph Lameter 
40719eeff239SChristoph Lameter #ifdef CONFIG_NUMA
40729eeff239SChristoph Lameter /*
4073a5f5f91dSMel Gorman  * Node reclaim mode
40749eeff239SChristoph Lameter  *
4075a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
40769eeff239SChristoph Lameter  * the watermarks.
40779eeff239SChristoph Lameter  */
4078a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
40799eeff239SChristoph Lameter 
40801b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
40817d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
40821b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
408395bbc0c7SZhihui Zhang #define RECLAIM_UNMAP (1<<2)	/* Unmap pages during reclaim */
40841b2ffb78SChristoph Lameter 
40859eeff239SChristoph Lameter /*
4086a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
4087a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
4088a92f7126SChristoph Lameter  * a zone.
4089a92f7126SChristoph Lameter  */
4090a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
4091a92f7126SChristoph Lameter 
40929eeff239SChristoph Lameter /*
4093a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
40949614634fSChristoph Lameter  * occur.
40959614634fSChristoph Lameter  */
40969614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
40979614634fSChristoph Lameter 
40989614634fSChristoph Lameter /*
40990ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
41000ff38490SChristoph Lameter  * slab reclaim needs to occur.
41010ff38490SChristoph Lameter  */
41020ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
41030ff38490SChristoph Lameter 
410411fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
410590afa5deSMel Gorman {
410611fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
410711fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
410811fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
410990afa5deSMel Gorman 
411090afa5deSMel Gorman 	/*
411190afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
411290afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
411390afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
411490afa5deSMel Gorman 	 */
411590afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
411690afa5deSMel Gorman }
411790afa5deSMel Gorman 
411890afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4119a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
412090afa5deSMel Gorman {
4121d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
4122d031a157SAlexandru Moise 	unsigned long delta = 0;
412390afa5deSMel Gorman 
412490afa5deSMel Gorman 	/*
412595bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
412690afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
412711fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
412890afa5deSMel Gorman 	 * a better estimate
412990afa5deSMel Gorman 	 */
4130a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
4131a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
413290afa5deSMel Gorman 	else
4133a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
413490afa5deSMel Gorman 
413590afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
4136a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
4137a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
413890afa5deSMel Gorman 
413990afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
414090afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
414190afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
414290afa5deSMel Gorman 
414390afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
414490afa5deSMel Gorman }
414590afa5deSMel Gorman 
41460ff38490SChristoph Lameter /*
4147a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
41489eeff239SChristoph Lameter  */
4149a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
41509eeff239SChristoph Lameter {
41517fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
415269e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
41539eeff239SChristoph Lameter 	struct task_struct *p = current;
4154499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
4155179e9639SAndrew Morton 	struct scan_control sc = {
415662b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4157f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
4158bd2f6199SJohannes Weiner 		.order = order,
4159a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
4160a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4161a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4162ee814fe2SJohannes Weiner 		.may_swap = 1,
4163f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
4164179e9639SAndrew Morton 	};
41659eeff239SChristoph Lameter 
4166132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4167132bb8cfSYafang Shao 					   sc.gfp_mask);
4168132bb8cfSYafang Shao 
41699eeff239SChristoph Lameter 	cond_resched();
417093781325SOmar Sandoval 	fs_reclaim_acquire(sc.gfp_mask);
4171d4f7796eSChristoph Lameter 	/*
417295bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4173d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
417495bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
4175d4f7796eSChristoph Lameter 	 */
4176499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
4177499118e9SVlastimil Babka 	p->flags |= PF_SWAPWRITE;
41781732d2b0SAndrew Morton 	set_task_reclaim_state(p, &sc.reclaim_state);
4179c84db23cSChristoph Lameter 
4180a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
4181a92f7126SChristoph Lameter 		/*
4182894befecSAndrey Ryabinin 		 * Free memory by calling shrink node with increasing
41830ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
4184a92f7126SChristoph Lameter 		 */
4185a92f7126SChristoph Lameter 		do {
4186970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
41879e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
41880ff38490SChristoph Lameter 	}
4189a92f7126SChristoph Lameter 
41901732d2b0SAndrew Morton 	set_task_reclaim_state(p, NULL);
4191499118e9SVlastimil Babka 	current->flags &= ~PF_SWAPWRITE;
4192499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
419393781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4194132bb8cfSYafang Shao 
4195132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4196132bb8cfSYafang Shao 
4197a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
41989eeff239SChristoph Lameter }
4199179e9639SAndrew Morton 
4200a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4201179e9639SAndrew Morton {
4202d773ed6bSDavid Rientjes 	int ret;
4203179e9639SAndrew Morton 
4204179e9639SAndrew Morton 	/*
4205a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
42060ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
420734aa1330SChristoph Lameter 	 *
42089614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
42099614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
4210a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
4211a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
42129614634fSChristoph Lameter 	 * unmapped file backed pages.
4213179e9639SAndrew Morton 	 */
4214a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4215385386cfSJohannes Weiner 	    node_page_state(pgdat, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
4216a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
4217179e9639SAndrew Morton 
4218179e9639SAndrew Morton 	/*
4219d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
4220179e9639SAndrew Morton 	 */
4221d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4222a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4223179e9639SAndrew Morton 
4224179e9639SAndrew Morton 	/*
4225a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
4226179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
4227179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
4228179e9639SAndrew Morton 	 * as wide as possible.
4229179e9639SAndrew Morton 	 */
4230a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4231a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4232d773ed6bSDavid Rientjes 
4233a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4234a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4235fa5e084eSMel Gorman 
4236a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
4237a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4238d773ed6bSDavid Rientjes 
423924cf7251SMel Gorman 	if (!ret)
424024cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
424124cf7251SMel Gorman 
4242d773ed6bSDavid Rientjes 	return ret;
4243179e9639SAndrew Morton }
42449eeff239SChristoph Lameter #endif
4245894bc310SLee Schermerhorn 
4246894bc310SLee Schermerhorn /*
4247894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
4248894bc310SLee Schermerhorn  * @page: the page to test
4249894bc310SLee Schermerhorn  *
4250894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
425139b5f29aSHugh Dickins  * lists vs unevictable list.
4252894bc310SLee Schermerhorn  *
4253894bc310SLee Schermerhorn  * Reasons page might not be evictable:
4254ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
4255b291f000SNick Piggin  * (2) page is part of an mlocked VMA
4256ba9ddf49SLee Schermerhorn  *
4257894bc310SLee Schermerhorn  */
425839b5f29aSHugh Dickins int page_evictable(struct page *page)
4259894bc310SLee Schermerhorn {
4260e92bb4ddSHuang Ying 	int ret;
4261e92bb4ddSHuang Ying 
4262e92bb4ddSHuang Ying 	/* Prevent address_space of inode and swap cache from being freed */
4263e92bb4ddSHuang Ying 	rcu_read_lock();
4264e92bb4ddSHuang Ying 	ret = !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
4265e92bb4ddSHuang Ying 	rcu_read_unlock();
4266e92bb4ddSHuang Ying 	return ret;
4267894bc310SLee Schermerhorn }
426889e004eaSLee Schermerhorn 
426989e004eaSLee Schermerhorn /**
427064e3d12fSKuo-Hsin Yang  * check_move_unevictable_pages - check pages for evictability and move to
427164e3d12fSKuo-Hsin Yang  * appropriate zone lru list
427264e3d12fSKuo-Hsin Yang  * @pvec: pagevec with lru pages to check
427389e004eaSLee Schermerhorn  *
427464e3d12fSKuo-Hsin Yang  * Checks pages for evictability, if an evictable page is in the unevictable
427564e3d12fSKuo-Hsin Yang  * lru list, moves it to the appropriate evictable lru list. This function
427664e3d12fSKuo-Hsin Yang  * should be only used for lru pages.
427789e004eaSLee Schermerhorn  */
427864e3d12fSKuo-Hsin Yang void check_move_unevictable_pages(struct pagevec *pvec)
427989e004eaSLee Schermerhorn {
4280925b7673SJohannes Weiner 	struct lruvec *lruvec;
4281785b99feSMel Gorman 	struct pglist_data *pgdat = NULL;
428224513264SHugh Dickins 	int pgscanned = 0;
428324513264SHugh Dickins 	int pgrescued = 0;
428489e004eaSLee Schermerhorn 	int i;
428589e004eaSLee Schermerhorn 
428664e3d12fSKuo-Hsin Yang 	for (i = 0; i < pvec->nr; i++) {
428764e3d12fSKuo-Hsin Yang 		struct page *page = pvec->pages[i];
4288785b99feSMel Gorman 		struct pglist_data *pagepgdat = page_pgdat(page);
428989e004eaSLee Schermerhorn 
429024513264SHugh Dickins 		pgscanned++;
4291785b99feSMel Gorman 		if (pagepgdat != pgdat) {
4292785b99feSMel Gorman 			if (pgdat)
4293785b99feSMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
4294785b99feSMel Gorman 			pgdat = pagepgdat;
4295785b99feSMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
429689e004eaSLee Schermerhorn 		}
4297785b99feSMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
429889e004eaSLee Schermerhorn 
429924513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
430024513264SHugh Dickins 			continue;
430189e004eaSLee Schermerhorn 
430239b5f29aSHugh Dickins 		if (page_evictable(page)) {
430324513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
430424513264SHugh Dickins 
4305309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
430624513264SHugh Dickins 			ClearPageUnevictable(page);
4307fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
4308fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
430924513264SHugh Dickins 			pgrescued++;
431089e004eaSLee Schermerhorn 		}
431189e004eaSLee Schermerhorn 	}
431224513264SHugh Dickins 
4313785b99feSMel Gorman 	if (pgdat) {
431424513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
431524513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
4316785b99feSMel Gorman 		spin_unlock_irq(&pgdat->lru_lock);
431724513264SHugh Dickins 	}
431885046579SHugh Dickins }
431964e3d12fSKuo-Hsin Yang EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
4320