xref: /openbmc/linux/mm/vmscan.c (revision ecf5fc6e9654cd7a268c782a523f072b2f1959f9)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  *  linux/mm/vmscan.c
31da177e4SLinus Torvalds  *
41da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
51da177e4SLinus Torvalds  *
61da177e4SLinus Torvalds  *  Swap reorganised 29.12.95, Stephen Tweedie.
71da177e4SLinus Torvalds  *  kswapd added: 7.1.96  sct
81da177e4SLinus Torvalds  *  Removed kswapd_ctl limits, and swap out as many pages as needed
91da177e4SLinus Torvalds  *  to bring the system back to freepages.high: 2.4.97, Rik van Riel.
101da177e4SLinus Torvalds  *  Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
111da177e4SLinus Torvalds  *  Multiqueue VM started 5.8.00, Rik van Riel.
121da177e4SLinus Torvalds  */
131da177e4SLinus Torvalds 
14b1de0d13SMitchel Humpherys #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
15b1de0d13SMitchel Humpherys 
161da177e4SLinus Torvalds #include <linux/mm.h>
171da177e4SLinus Torvalds #include <linux/module.h>
185a0e3ad6STejun Heo #include <linux/gfp.h>
191da177e4SLinus Torvalds #include <linux/kernel_stat.h>
201da177e4SLinus Torvalds #include <linux/swap.h>
211da177e4SLinus Torvalds #include <linux/pagemap.h>
221da177e4SLinus Torvalds #include <linux/init.h>
231da177e4SLinus Torvalds #include <linux/highmem.h>
2470ddf637SAnton Vorontsov #include <linux/vmpressure.h>
25e129b5c2SAndrew Morton #include <linux/vmstat.h>
261da177e4SLinus Torvalds #include <linux/file.h>
271da177e4SLinus Torvalds #include <linux/writeback.h>
281da177e4SLinus Torvalds #include <linux/blkdev.h>
291da177e4SLinus Torvalds #include <linux/buffer_head.h>	/* for try_to_release_page(),
301da177e4SLinus Torvalds 					buffer_heads_over_limit */
311da177e4SLinus Torvalds #include <linux/mm_inline.h>
321da177e4SLinus Torvalds #include <linux/backing-dev.h>
331da177e4SLinus Torvalds #include <linux/rmap.h>
341da177e4SLinus Torvalds #include <linux/topology.h>
351da177e4SLinus Torvalds #include <linux/cpu.h>
361da177e4SLinus Torvalds #include <linux/cpuset.h>
373e7d3449SMel Gorman #include <linux/compaction.h>
381da177e4SLinus Torvalds #include <linux/notifier.h>
391da177e4SLinus Torvalds #include <linux/rwsem.h>
40248a0301SRafael J. Wysocki #include <linux/delay.h>
413218ae14SYasunori Goto #include <linux/kthread.h>
427dfb7103SNigel Cunningham #include <linux/freezer.h>
4366e1707bSBalbir Singh #include <linux/memcontrol.h>
44873b4771SKeika Kobayashi #include <linux/delayacct.h>
45af936a16SLee Schermerhorn #include <linux/sysctl.h>
46929bea7cSKOSAKI Motohiro #include <linux/oom.h>
47268bb0ceSLinus Torvalds #include <linux/prefetch.h>
48b1de0d13SMitchel Humpherys #include <linux/printk.h>
491da177e4SLinus Torvalds 
501da177e4SLinus Torvalds #include <asm/tlbflush.h>
511da177e4SLinus Torvalds #include <asm/div64.h>
521da177e4SLinus Torvalds 
531da177e4SLinus Torvalds #include <linux/swapops.h>
54117aad1eSRafael Aquini #include <linux/balloon_compaction.h>
551da177e4SLinus Torvalds 
560f8053a5SNick Piggin #include "internal.h"
570f8053a5SNick Piggin 
5833906bc5SMel Gorman #define CREATE_TRACE_POINTS
5933906bc5SMel Gorman #include <trace/events/vmscan.h>
6033906bc5SMel Gorman 
611da177e4SLinus Torvalds struct scan_control {
6222fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6322fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
6422fba335SKOSAKI Motohiro 
651da177e4SLinus Torvalds 	/* This context's GFP mask */
666daa0e28SAl Viro 	gfp_t gfp_mask;
671da177e4SLinus Torvalds 
68ee814fe2SJohannes Weiner 	/* Allocation order */
695ad333ebSAndy Whitcroft 	int order;
7066e1707bSBalbir Singh 
71ee814fe2SJohannes Weiner 	/*
72ee814fe2SJohannes Weiner 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
73ee814fe2SJohannes Weiner 	 * are scanned.
74ee814fe2SJohannes Weiner 	 */
75ee814fe2SJohannes Weiner 	nodemask_t	*nodemask;
769e3b2f8cSKonstantin Khlebnikov 
775f53e762SKOSAKI Motohiro 	/*
78f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
79f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
80f16015fbSJohannes Weiner 	 */
81f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
8266e1707bSBalbir Singh 
83ee814fe2SJohannes Weiner 	/* Scan (total_size >> priority) pages at once */
84ee814fe2SJohannes Weiner 	int priority;
85ee814fe2SJohannes Weiner 
86ee814fe2SJohannes Weiner 	unsigned int may_writepage:1;
87ee814fe2SJohannes Weiner 
88ee814fe2SJohannes Weiner 	/* Can mapped pages be reclaimed? */
89ee814fe2SJohannes Weiner 	unsigned int may_unmap:1;
90ee814fe2SJohannes Weiner 
91ee814fe2SJohannes Weiner 	/* Can pages be swapped as part of reclaim? */
92ee814fe2SJohannes Weiner 	unsigned int may_swap:1;
93ee814fe2SJohannes Weiner 
94241994edSJohannes Weiner 	/* Can cgroups be reclaimed below their normal consumption range? */
95241994edSJohannes Weiner 	unsigned int may_thrash:1;
96241994edSJohannes Weiner 
97ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
98ee814fe2SJohannes Weiner 
99ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
100ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
101ee814fe2SJohannes Weiner 
102ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
103ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
104ee814fe2SJohannes Weiner 
105ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
106ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
1071da177e4SLinus Torvalds };
1081da177e4SLinus Torvalds 
1091da177e4SLinus Torvalds #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
1101da177e4SLinus Torvalds 
1111da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCH
1121da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field)			\
1131da177e4SLinus Torvalds 	do {								\
1141da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1151da177e4SLinus Torvalds 			struct page *prev;				\
1161da177e4SLinus Torvalds 									\
1171da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1181da177e4SLinus Torvalds 			prefetch(&prev->_field);			\
1191da177e4SLinus Torvalds 		}							\
1201da177e4SLinus Torvalds 	} while (0)
1211da177e4SLinus Torvalds #else
1221da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
1231da177e4SLinus Torvalds #endif
1241da177e4SLinus Torvalds 
1251da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1261da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1271da177e4SLinus Torvalds 	do {								\
1281da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1291da177e4SLinus Torvalds 			struct page *prev;				\
1301da177e4SLinus Torvalds 									\
1311da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1321da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1331da177e4SLinus Torvalds 		}							\
1341da177e4SLinus Torvalds 	} while (0)
1351da177e4SLinus Torvalds #else
1361da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1371da177e4SLinus Torvalds #endif
1381da177e4SLinus Torvalds 
1391da177e4SLinus Torvalds /*
1401da177e4SLinus Torvalds  * From 0 .. 100.  Higher means more swappy.
1411da177e4SLinus Torvalds  */
1421da177e4SLinus Torvalds int vm_swappiness = 60;
143d0480be4SWang Sheng-Hui /*
144d0480be4SWang Sheng-Hui  * The total number of pages which are beyond the high watermark within all
145d0480be4SWang Sheng-Hui  * zones.
146d0480be4SWang Sheng-Hui  */
147d0480be4SWang Sheng-Hui unsigned long vm_total_pages;
1481da177e4SLinus Torvalds 
1491da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1501da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1511da177e4SLinus Torvalds 
152c255a458SAndrew Morton #ifdef CONFIG_MEMCG
15389b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
15489b5fae5SJohannes Weiner {
155f16015fbSJohannes Weiner 	return !sc->target_mem_cgroup;
15689b5fae5SJohannes Weiner }
15797c9341fSTejun Heo 
15897c9341fSTejun Heo /**
15997c9341fSTejun Heo  * sane_reclaim - is the usual dirty throttling mechanism operational?
16097c9341fSTejun Heo  * @sc: scan_control in question
16197c9341fSTejun Heo  *
16297c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
16397c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
16497c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
16597c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
16697c9341fSTejun Heo  * allocation and configurability.
16797c9341fSTejun Heo  *
16897c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
16997c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
17097c9341fSTejun Heo  */
17197c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
17297c9341fSTejun Heo {
17397c9341fSTejun Heo 	struct mem_cgroup *memcg = sc->target_mem_cgroup;
17497c9341fSTejun Heo 
17597c9341fSTejun Heo 	if (!memcg)
17697c9341fSTejun Heo 		return true;
17797c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
17897c9341fSTejun Heo 	if (cgroup_on_dfl(mem_cgroup_css(memcg)->cgroup))
17997c9341fSTejun Heo 		return true;
18097c9341fSTejun Heo #endif
18197c9341fSTejun Heo 	return false;
18297c9341fSTejun Heo }
18391a45470SKAMEZAWA Hiroyuki #else
18489b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
18589b5fae5SJohannes Weiner {
18689b5fae5SJohannes Weiner 	return true;
18789b5fae5SJohannes Weiner }
18897c9341fSTejun Heo 
18997c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
19097c9341fSTejun Heo {
19197c9341fSTejun Heo 	return true;
19297c9341fSTejun Heo }
19391a45470SKAMEZAWA Hiroyuki #endif
19491a45470SKAMEZAWA Hiroyuki 
195a1c3bfb2SJohannes Weiner static unsigned long zone_reclaimable_pages(struct zone *zone)
1966e543d57SLisa Du {
1976e543d57SLisa Du 	int nr;
1986e543d57SLisa Du 
1996e543d57SLisa Du 	nr = zone_page_state(zone, NR_ACTIVE_FILE) +
2006e543d57SLisa Du 	     zone_page_state(zone, NR_INACTIVE_FILE);
2016e543d57SLisa Du 
2026e543d57SLisa Du 	if (get_nr_swap_pages() > 0)
2036e543d57SLisa Du 		nr += zone_page_state(zone, NR_ACTIVE_ANON) +
2046e543d57SLisa Du 		      zone_page_state(zone, NR_INACTIVE_ANON);
2056e543d57SLisa Du 
2066e543d57SLisa Du 	return nr;
2076e543d57SLisa Du }
2086e543d57SLisa Du 
2096e543d57SLisa Du bool zone_reclaimable(struct zone *zone)
2106e543d57SLisa Du {
2110d5d823aSMel Gorman 	return zone_page_state(zone, NR_PAGES_SCANNED) <
2120d5d823aSMel Gorman 		zone_reclaimable_pages(zone) * 6;
2136e543d57SLisa Du }
2146e543d57SLisa Du 
2154d7dcca2SHugh Dickins static unsigned long get_lru_size(struct lruvec *lruvec, enum lru_list lru)
216c9f299d9SKOSAKI Motohiro {
217c3c787e8SHugh Dickins 	if (!mem_cgroup_disabled())
2184d7dcca2SHugh Dickins 		return mem_cgroup_get_lru_size(lruvec, lru);
219a3d8e054SKOSAKI Motohiro 
220074291feSKonstantin Khlebnikov 	return zone_page_state(lruvec_zone(lruvec), NR_LRU_BASE + lru);
221c9f299d9SKOSAKI Motohiro }
222c9f299d9SKOSAKI Motohiro 
2231da177e4SLinus Torvalds /*
2241d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
2251da177e4SLinus Torvalds  */
2261d3d4437SGlauber Costa int register_shrinker(struct shrinker *shrinker)
2271da177e4SLinus Torvalds {
2281d3d4437SGlauber Costa 	size_t size = sizeof(*shrinker->nr_deferred);
2291d3d4437SGlauber Costa 
2301d3d4437SGlauber Costa 	/*
2311d3d4437SGlauber Costa 	 * If we only have one possible node in the system anyway, save
2321d3d4437SGlauber Costa 	 * ourselves the trouble and disable NUMA aware behavior. This way we
2331d3d4437SGlauber Costa 	 * will save memory and some small loop time later.
2341d3d4437SGlauber Costa 	 */
2351d3d4437SGlauber Costa 	if (nr_node_ids == 1)
2361d3d4437SGlauber Costa 		shrinker->flags &= ~SHRINKER_NUMA_AWARE;
2371d3d4437SGlauber Costa 
2381d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
2391d3d4437SGlauber Costa 		size *= nr_node_ids;
2401d3d4437SGlauber Costa 
2411d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
2421d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
2431d3d4437SGlauber Costa 		return -ENOMEM;
2441d3d4437SGlauber Costa 
2451da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2461da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
2471da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
2481d3d4437SGlauber Costa 	return 0;
2491da177e4SLinus Torvalds }
2508e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
2511da177e4SLinus Torvalds 
2521da177e4SLinus Torvalds /*
2531da177e4SLinus Torvalds  * Remove one
2541da177e4SLinus Torvalds  */
2558e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
2561da177e4SLinus Torvalds {
2571da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2581da177e4SLinus Torvalds 	list_del(&shrinker->list);
2591da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
260ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
2611da177e4SLinus Torvalds }
2628e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
2631da177e4SLinus Torvalds 
2641da177e4SLinus Torvalds #define SHRINK_BATCH 128
2651d3d4437SGlauber Costa 
266cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
2676b4f7799SJohannes Weiner 				    struct shrinker *shrinker,
2686b4f7799SJohannes Weiner 				    unsigned long nr_scanned,
2696b4f7799SJohannes Weiner 				    unsigned long nr_eligible)
2701da177e4SLinus Torvalds {
27124f7c6b9SDave Chinner 	unsigned long freed = 0;
2721da177e4SLinus Torvalds 	unsigned long long delta;
273635697c6SKonstantin Khlebnikov 	long total_scan;
274d5bc5fd3SVladimir Davydov 	long freeable;
275acf92b48SDave Chinner 	long nr;
276acf92b48SDave Chinner 	long new_nr;
2771d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
278e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
279e9299f50SDave Chinner 					  : SHRINK_BATCH;
2801da177e4SLinus Torvalds 
281d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
282d5bc5fd3SVladimir Davydov 	if (freeable == 0)
2831d3d4437SGlauber Costa 		return 0;
284635697c6SKonstantin Khlebnikov 
285acf92b48SDave Chinner 	/*
286acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
287acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
288acf92b48SDave Chinner 	 * don't also do this scanning work.
289acf92b48SDave Chinner 	 */
2901d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
291acf92b48SDave Chinner 
292acf92b48SDave Chinner 	total_scan = nr;
2936b4f7799SJohannes Weiner 	delta = (4 * nr_scanned) / shrinker->seeks;
294d5bc5fd3SVladimir Davydov 	delta *= freeable;
2956b4f7799SJohannes Weiner 	do_div(delta, nr_eligible + 1);
296acf92b48SDave Chinner 	total_scan += delta;
297acf92b48SDave Chinner 	if (total_scan < 0) {
2988612c663SPintu Kumar 		pr_err("shrink_slab: %pF negative objects to delete nr=%ld\n",
299a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
300d5bc5fd3SVladimir Davydov 		total_scan = freeable;
301ea164d73SAndrea Arcangeli 	}
302ea164d73SAndrea Arcangeli 
303ea164d73SAndrea Arcangeli 	/*
3043567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
3053567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
3063567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
3073567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
3083567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
309d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
3103567b59aSDave Chinner 	 * memory.
3113567b59aSDave Chinner 	 *
3123567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
3133567b59aSDave Chinner 	 * a large delta change is calculated directly.
3143567b59aSDave Chinner 	 */
315d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
316d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
3173567b59aSDave Chinner 
3183567b59aSDave Chinner 	/*
319ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
320ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
321ea164d73SAndrea Arcangeli 	 * freeable entries.
322ea164d73SAndrea Arcangeli 	 */
323d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
324d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
3251da177e4SLinus Torvalds 
32624f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
3276b4f7799SJohannes Weiner 				   nr_scanned, nr_eligible,
328d5bc5fd3SVladimir Davydov 				   freeable, delta, total_scan);
32909576073SDave Chinner 
3300b1fb40aSVladimir Davydov 	/*
3310b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
3320b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
3330b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
3340b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
3350b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
3360b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
3370b1fb40aSVladimir Davydov 	 * batch_size.
3380b1fb40aSVladimir Davydov 	 *
3390b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
3400b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
341d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
3420b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
3430b1fb40aSVladimir Davydov 	 * possible.
3440b1fb40aSVladimir Davydov 	 */
3450b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
346d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
34724f7c6b9SDave Chinner 		unsigned long ret;
3480b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
3491da177e4SLinus Torvalds 
3500b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
35124f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
35224f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
3531da177e4SLinus Torvalds 			break;
35424f7c6b9SDave Chinner 		freed += ret;
35524f7c6b9SDave Chinner 
3560b1fb40aSVladimir Davydov 		count_vm_events(SLABS_SCANNED, nr_to_scan);
3570b1fb40aSVladimir Davydov 		total_scan -= nr_to_scan;
3581da177e4SLinus Torvalds 
3591da177e4SLinus Torvalds 		cond_resched();
3601da177e4SLinus Torvalds 	}
3611da177e4SLinus Torvalds 
362acf92b48SDave Chinner 	/*
363acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
364acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
365acf92b48SDave Chinner 	 * scan, there is no need to do an update.
366acf92b48SDave Chinner 	 */
36783aeeadaSKonstantin Khlebnikov 	if (total_scan > 0)
36883aeeadaSKonstantin Khlebnikov 		new_nr = atomic_long_add_return(total_scan,
3691d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
37083aeeadaSKonstantin Khlebnikov 	else
3711d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
372acf92b48SDave Chinner 
373df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
3741d3d4437SGlauber Costa 	return freed;
3751d3d4437SGlauber Costa }
3761d3d4437SGlauber Costa 
3776b4f7799SJohannes Weiner /**
378cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
3796b4f7799SJohannes Weiner  * @gfp_mask: allocation context
3806b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
381cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
3826b4f7799SJohannes Weiner  * @nr_scanned: pressure numerator
3836b4f7799SJohannes Weiner  * @nr_eligible: pressure denominator
3841d3d4437SGlauber Costa  *
3856b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
3861d3d4437SGlauber Costa  *
3876b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
3886b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
3891d3d4437SGlauber Costa  *
390cb731d6cSVladimir Davydov  * @memcg specifies the memory cgroup to target. If it is not NULL,
391cb731d6cSVladimir Davydov  * only shrinkers with SHRINKER_MEMCG_AWARE set will be called to scan
392cb731d6cSVladimir Davydov  * objects from the memory cgroup specified. Otherwise all shrinkers
393cb731d6cSVladimir Davydov  * are called, and memcg aware shrinkers are supposed to scan the
394cb731d6cSVladimir Davydov  * global list then.
395cb731d6cSVladimir Davydov  *
3966b4f7799SJohannes Weiner  * @nr_scanned and @nr_eligible form a ratio that indicate how much of
3976b4f7799SJohannes Weiner  * the available objects should be scanned.  Page reclaim for example
3986b4f7799SJohannes Weiner  * passes the number of pages scanned and the number of pages on the
3996b4f7799SJohannes Weiner  * LRU lists that it considered on @nid, plus a bias in @nr_scanned
4006b4f7799SJohannes Weiner  * when it encountered mapped pages.  The ratio is further biased by
4016b4f7799SJohannes Weiner  * the ->seeks setting of the shrink function, which indicates the
4026b4f7799SJohannes Weiner  * cost to recreate an object relative to that of an LRU page.
4031d3d4437SGlauber Costa  *
4046b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
4051d3d4437SGlauber Costa  */
406cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
407cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
4086b4f7799SJohannes Weiner 				 unsigned long nr_scanned,
4096b4f7799SJohannes Weiner 				 unsigned long nr_eligible)
4101d3d4437SGlauber Costa {
4111d3d4437SGlauber Costa 	struct shrinker *shrinker;
4121d3d4437SGlauber Costa 	unsigned long freed = 0;
4131d3d4437SGlauber Costa 
414cb731d6cSVladimir Davydov 	if (memcg && !memcg_kmem_is_active(memcg))
415cb731d6cSVladimir Davydov 		return 0;
416cb731d6cSVladimir Davydov 
4176b4f7799SJohannes Weiner 	if (nr_scanned == 0)
4186b4f7799SJohannes Weiner 		nr_scanned = SWAP_CLUSTER_MAX;
4191d3d4437SGlauber Costa 
4201d3d4437SGlauber Costa 	if (!down_read_trylock(&shrinker_rwsem)) {
4211d3d4437SGlauber Costa 		/*
4221d3d4437SGlauber Costa 		 * If we would return 0, our callers would understand that we
4231d3d4437SGlauber Costa 		 * have nothing else to shrink and give up trying. By returning
4241d3d4437SGlauber Costa 		 * 1 we keep it going and assume we'll be able to shrink next
4251d3d4437SGlauber Costa 		 * time.
4261d3d4437SGlauber Costa 		 */
4271d3d4437SGlauber Costa 		freed = 1;
4281d3d4437SGlauber Costa 		goto out;
4291d3d4437SGlauber Costa 	}
4301d3d4437SGlauber Costa 
4311d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
4326b4f7799SJohannes Weiner 		struct shrink_control sc = {
4336b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
4346b4f7799SJohannes Weiner 			.nid = nid,
435cb731d6cSVladimir Davydov 			.memcg = memcg,
4366b4f7799SJohannes Weiner 		};
4376b4f7799SJohannes Weiner 
438cb731d6cSVladimir Davydov 		if (memcg && !(shrinker->flags & SHRINKER_MEMCG_AWARE))
439cb731d6cSVladimir Davydov 			continue;
440cb731d6cSVladimir Davydov 
4416b4f7799SJohannes Weiner 		if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
4426b4f7799SJohannes Weiner 			sc.nid = 0;
4436b4f7799SJohannes Weiner 
444cb731d6cSVladimir Davydov 		freed += do_shrink_slab(&sc, shrinker, nr_scanned, nr_eligible);
445ec97097bSVladimir Davydov 	}
4461d3d4437SGlauber Costa 
4471da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
448f06590bdSMinchan Kim out:
449f06590bdSMinchan Kim 	cond_resched();
45024f7c6b9SDave Chinner 	return freed;
4511da177e4SLinus Torvalds }
4521da177e4SLinus Torvalds 
453cb731d6cSVladimir Davydov void drop_slab_node(int nid)
454cb731d6cSVladimir Davydov {
455cb731d6cSVladimir Davydov 	unsigned long freed;
456cb731d6cSVladimir Davydov 
457cb731d6cSVladimir Davydov 	do {
458cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
459cb731d6cSVladimir Davydov 
460cb731d6cSVladimir Davydov 		freed = 0;
461cb731d6cSVladimir Davydov 		do {
462cb731d6cSVladimir Davydov 			freed += shrink_slab(GFP_KERNEL, nid, memcg,
463cb731d6cSVladimir Davydov 					     1000, 1000);
464cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
465cb731d6cSVladimir Davydov 	} while (freed > 10);
466cb731d6cSVladimir Davydov }
467cb731d6cSVladimir Davydov 
468cb731d6cSVladimir Davydov void drop_slab(void)
469cb731d6cSVladimir Davydov {
470cb731d6cSVladimir Davydov 	int nid;
471cb731d6cSVladimir Davydov 
472cb731d6cSVladimir Davydov 	for_each_online_node(nid)
473cb731d6cSVladimir Davydov 		drop_slab_node(nid);
474cb731d6cSVladimir Davydov }
475cb731d6cSVladimir Davydov 
4761da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
4771da177e4SLinus Torvalds {
478ceddc3a5SJohannes Weiner 	/*
479ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
480ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
481ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
482ceddc3a5SJohannes Weiner 	 */
483edcf4748SJohannes Weiner 	return page_count(page) - page_has_private(page) == 2;
4841da177e4SLinus Torvalds }
4851da177e4SLinus Torvalds 
486703c2708STejun Heo static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
4871da177e4SLinus Torvalds {
488930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
4891da177e4SLinus Torvalds 		return 1;
490703c2708STejun Heo 	if (!inode_write_congested(inode))
4911da177e4SLinus Torvalds 		return 1;
492703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
4931da177e4SLinus Torvalds 		return 1;
4941da177e4SLinus Torvalds 	return 0;
4951da177e4SLinus Torvalds }
4961da177e4SLinus Torvalds 
4971da177e4SLinus Torvalds /*
4981da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
4991da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
5001da177e4SLinus Torvalds  * fsync(), msync() or close().
5011da177e4SLinus Torvalds  *
5021da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
5031da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
5041da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
5051da177e4SLinus Torvalds  *
5061da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
5071da177e4SLinus Torvalds  * __GFP_FS.
5081da177e4SLinus Torvalds  */
5091da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
5101da177e4SLinus Torvalds 				struct page *page, int error)
5111da177e4SLinus Torvalds {
5127eaceaccSJens Axboe 	lock_page(page);
5133e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
5143e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
5151da177e4SLinus Torvalds 	unlock_page(page);
5161da177e4SLinus Torvalds }
5171da177e4SLinus Torvalds 
51804e62a29SChristoph Lameter /* possible outcome of pageout() */
51904e62a29SChristoph Lameter typedef enum {
52004e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
52104e62a29SChristoph Lameter 	PAGE_KEEP,
52204e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
52304e62a29SChristoph Lameter 	PAGE_ACTIVATE,
52404e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
52504e62a29SChristoph Lameter 	PAGE_SUCCESS,
52604e62a29SChristoph Lameter 	/* page is clean and locked */
52704e62a29SChristoph Lameter 	PAGE_CLEAN,
52804e62a29SChristoph Lameter } pageout_t;
52904e62a29SChristoph Lameter 
5301da177e4SLinus Torvalds /*
5311742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
5321742f19fSAndrew Morton  * Calls ->writepage().
5331da177e4SLinus Torvalds  */
534c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
5357d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
5361da177e4SLinus Torvalds {
5371da177e4SLinus Torvalds 	/*
5381da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
5391da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
5401da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
5411da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
5421da177e4SLinus Torvalds 	 * PagePrivate for that.
5431da177e4SLinus Torvalds 	 *
5448174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
5451da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
5461da177e4SLinus Torvalds 	 * will block.
5471da177e4SLinus Torvalds 	 *
5481da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
5491da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
5501da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
5511da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
5521da177e4SLinus Torvalds 	 */
5531da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
5541da177e4SLinus Torvalds 		return PAGE_KEEP;
5551da177e4SLinus Torvalds 	if (!mapping) {
5561da177e4SLinus Torvalds 		/*
5571da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
5581da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
5591da177e4SLinus Torvalds 		 */
560266cf658SDavid Howells 		if (page_has_private(page)) {
5611da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
5621da177e4SLinus Torvalds 				ClearPageDirty(page);
563b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
5641da177e4SLinus Torvalds 				return PAGE_CLEAN;
5651da177e4SLinus Torvalds 			}
5661da177e4SLinus Torvalds 		}
5671da177e4SLinus Torvalds 		return PAGE_KEEP;
5681da177e4SLinus Torvalds 	}
5691da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
5701da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
571703c2708STejun Heo 	if (!may_write_to_inode(mapping->host, sc))
5721da177e4SLinus Torvalds 		return PAGE_KEEP;
5731da177e4SLinus Torvalds 
5741da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
5751da177e4SLinus Torvalds 		int res;
5761da177e4SLinus Torvalds 		struct writeback_control wbc = {
5771da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
5781da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
579111ebb6eSOGAWA Hirofumi 			.range_start = 0,
580111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
5811da177e4SLinus Torvalds 			.for_reclaim = 1,
5821da177e4SLinus Torvalds 		};
5831da177e4SLinus Torvalds 
5841da177e4SLinus Torvalds 		SetPageReclaim(page);
5851da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
5861da177e4SLinus Torvalds 		if (res < 0)
5871da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
588994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
5891da177e4SLinus Torvalds 			ClearPageReclaim(page);
5901da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
5911da177e4SLinus Torvalds 		}
592c661b078SAndy Whitcroft 
5931da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
5941da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
5951da177e4SLinus Torvalds 			ClearPageReclaim(page);
5961da177e4SLinus Torvalds 		}
59723b9da55SMel Gorman 		trace_mm_vmscan_writepage(page, trace_reclaim_flags(page));
598e129b5c2SAndrew Morton 		inc_zone_page_state(page, NR_VMSCAN_WRITE);
5991da177e4SLinus Torvalds 		return PAGE_SUCCESS;
6001da177e4SLinus Torvalds 	}
6011da177e4SLinus Torvalds 
6021da177e4SLinus Torvalds 	return PAGE_CLEAN;
6031da177e4SLinus Torvalds }
6041da177e4SLinus Torvalds 
605a649fd92SAndrew Morton /*
606e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
607e286781dSNick Piggin  * gets returned with a refcount of 0.
608a649fd92SAndrew Morton  */
609a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
610a528910eSJohannes Weiner 			    bool reclaimed)
61149d2e9ccSChristoph Lameter {
612c4843a75SGreg Thelen 	unsigned long flags;
613c4843a75SGreg Thelen 	struct mem_cgroup *memcg;
614c4843a75SGreg Thelen 
61528e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
61628e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
61749d2e9ccSChristoph Lameter 
618c4843a75SGreg Thelen 	memcg = mem_cgroup_begin_page_stat(page);
619c4843a75SGreg Thelen 	spin_lock_irqsave(&mapping->tree_lock, flags);
62049d2e9ccSChristoph Lameter 	/*
6210fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
6220fd0e6b0SNick Piggin 	 *
6230fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
6240fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
6250fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
6260fd0e6b0SNick Piggin 	 * here, then the following race may occur:
6270fd0e6b0SNick Piggin 	 *
6280fd0e6b0SNick Piggin 	 * get_user_pages(&page);
6290fd0e6b0SNick Piggin 	 * [user mapping goes away]
6300fd0e6b0SNick Piggin 	 * write_to(page);
6310fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
6320fd0e6b0SNick Piggin 	 * SetPageDirty(page);
6330fd0e6b0SNick Piggin 	 * put_page(page);
6340fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
6350fd0e6b0SNick Piggin 	 *
6360fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
6370fd0e6b0SNick Piggin 	 *
6380fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
6390fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
6400fd0e6b0SNick Piggin 	 * load is not satisfied before that of page->_count.
6410fd0e6b0SNick Piggin 	 *
6420fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
6430fd0e6b0SNick Piggin 	 * and thus under tree_lock, then this ordering is not required.
64449d2e9ccSChristoph Lameter 	 */
645e286781dSNick Piggin 	if (!page_freeze_refs(page, 2))
64649d2e9ccSChristoph Lameter 		goto cannot_free;
647e286781dSNick Piggin 	/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
648e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
649e286781dSNick Piggin 		page_unfreeze_refs(page, 2);
65049d2e9ccSChristoph Lameter 		goto cannot_free;
651e286781dSNick Piggin 	}
65249d2e9ccSChristoph Lameter 
65349d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
65449d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
6550a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
65649d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
657c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
658c4843a75SGreg Thelen 		mem_cgroup_end_page_stat(memcg);
6590a31bc97SJohannes Weiner 		swapcache_free(swap);
660e286781dSNick Piggin 	} else {
6616072d13cSLinus Torvalds 		void (*freepage)(struct page *);
662a528910eSJohannes Weiner 		void *shadow = NULL;
6636072d13cSLinus Torvalds 
6646072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
665a528910eSJohannes Weiner 		/*
666a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
667a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
668a528910eSJohannes Weiner 		 *
669a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
670a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
671a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
672a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
673a528910eSJohannes Weiner 		 * back.
674a528910eSJohannes Weiner 		 */
675a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
676a528910eSJohannes Weiner 		    !mapping_exiting(mapping))
677a528910eSJohannes Weiner 			shadow = workingset_eviction(mapping, page);
678c4843a75SGreg Thelen 		__delete_from_page_cache(page, shadow, memcg);
679c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
680c4843a75SGreg Thelen 		mem_cgroup_end_page_stat(memcg);
6816072d13cSLinus Torvalds 
6826072d13cSLinus Torvalds 		if (freepage != NULL)
6836072d13cSLinus Torvalds 			freepage(page);
684e286781dSNick Piggin 	}
685e286781dSNick Piggin 
68649d2e9ccSChristoph Lameter 	return 1;
68749d2e9ccSChristoph Lameter 
68849d2e9ccSChristoph Lameter cannot_free:
689c4843a75SGreg Thelen 	spin_unlock_irqrestore(&mapping->tree_lock, flags);
690c4843a75SGreg Thelen 	mem_cgroup_end_page_stat(memcg);
69149d2e9ccSChristoph Lameter 	return 0;
69249d2e9ccSChristoph Lameter }
69349d2e9ccSChristoph Lameter 
6941da177e4SLinus Torvalds /*
695e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
696e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
697e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
698e286781dSNick Piggin  * this page.
699e286781dSNick Piggin  */
700e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
701e286781dSNick Piggin {
702a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
703e286781dSNick Piggin 		/*
704e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
705e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
706e286781dSNick Piggin 		 * atomic operation.
707e286781dSNick Piggin 		 */
708e286781dSNick Piggin 		page_unfreeze_refs(page, 1);
709e286781dSNick Piggin 		return 1;
710e286781dSNick Piggin 	}
711e286781dSNick Piggin 	return 0;
712e286781dSNick Piggin }
713e286781dSNick Piggin 
714894bc310SLee Schermerhorn /**
715894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
716894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
717894bc310SLee Schermerhorn  *
718894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
719894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
720894bc310SLee Schermerhorn  *
721894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
722894bc310SLee Schermerhorn  */
723894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
724894bc310SLee Schermerhorn {
7250ec3b74cSVlastimil Babka 	bool is_unevictable;
726bbfd28eeSLee Schermerhorn 	int was_unevictable = PageUnevictable(page);
727894bc310SLee Schermerhorn 
728309381feSSasha Levin 	VM_BUG_ON_PAGE(PageLRU(page), page);
729894bc310SLee Schermerhorn 
730894bc310SLee Schermerhorn redo:
731894bc310SLee Schermerhorn 	ClearPageUnevictable(page);
732894bc310SLee Schermerhorn 
73339b5f29aSHugh Dickins 	if (page_evictable(page)) {
734894bc310SLee Schermerhorn 		/*
735894bc310SLee Schermerhorn 		 * For evictable pages, we can use the cache.
736894bc310SLee Schermerhorn 		 * In event of a race, worst case is we end up with an
737894bc310SLee Schermerhorn 		 * unevictable page on [in]active list.
738894bc310SLee Schermerhorn 		 * We know how to handle that.
739894bc310SLee Schermerhorn 		 */
7400ec3b74cSVlastimil Babka 		is_unevictable = false;
741c53954a0SMel Gorman 		lru_cache_add(page);
742894bc310SLee Schermerhorn 	} else {
743894bc310SLee Schermerhorn 		/*
744894bc310SLee Schermerhorn 		 * Put unevictable pages directly on zone's unevictable
745894bc310SLee Schermerhorn 		 * list.
746894bc310SLee Schermerhorn 		 */
7470ec3b74cSVlastimil Babka 		is_unevictable = true;
748894bc310SLee Schermerhorn 		add_page_to_unevictable_list(page);
7496a7b9548SJohannes Weiner 		/*
75021ee9f39SMinchan Kim 		 * When racing with an mlock or AS_UNEVICTABLE clearing
75121ee9f39SMinchan Kim 		 * (page is unlocked) make sure that if the other thread
75221ee9f39SMinchan Kim 		 * does not observe our setting of PG_lru and fails
75324513264SHugh Dickins 		 * isolation/check_move_unevictable_pages,
75421ee9f39SMinchan Kim 		 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
7556a7b9548SJohannes Weiner 		 * the page back to the evictable list.
7566a7b9548SJohannes Weiner 		 *
75721ee9f39SMinchan Kim 		 * The other side is TestClearPageMlocked() or shmem_lock().
7586a7b9548SJohannes Weiner 		 */
7596a7b9548SJohannes Weiner 		smp_mb();
760894bc310SLee Schermerhorn 	}
761894bc310SLee Schermerhorn 
762894bc310SLee Schermerhorn 	/*
763894bc310SLee Schermerhorn 	 * page's status can change while we move it among lru. If an evictable
764894bc310SLee Schermerhorn 	 * page is on unevictable list, it never be freed. To avoid that,
765894bc310SLee Schermerhorn 	 * check after we added it to the list, again.
766894bc310SLee Schermerhorn 	 */
7670ec3b74cSVlastimil Babka 	if (is_unevictable && page_evictable(page)) {
768894bc310SLee Schermerhorn 		if (!isolate_lru_page(page)) {
769894bc310SLee Schermerhorn 			put_page(page);
770894bc310SLee Schermerhorn 			goto redo;
771894bc310SLee Schermerhorn 		}
772894bc310SLee Schermerhorn 		/* This means someone else dropped this page from LRU
773894bc310SLee Schermerhorn 		 * So, it will be freed or putback to LRU again. There is
774894bc310SLee Schermerhorn 		 * nothing to do here.
775894bc310SLee Schermerhorn 		 */
776894bc310SLee Schermerhorn 	}
777894bc310SLee Schermerhorn 
7780ec3b74cSVlastimil Babka 	if (was_unevictable && !is_unevictable)
779bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGRESCUED);
7800ec3b74cSVlastimil Babka 	else if (!was_unevictable && is_unevictable)
781bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGCULLED);
782bbfd28eeSLee Schermerhorn 
783894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
784894bc310SLee Schermerhorn }
785894bc310SLee Schermerhorn 
786dfc8d636SJohannes Weiner enum page_references {
787dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
788dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
78964574746SJohannes Weiner 	PAGEREF_KEEP,
790dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
791dfc8d636SJohannes Weiner };
792dfc8d636SJohannes Weiner 
793dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
794dfc8d636SJohannes Weiner 						  struct scan_control *sc)
795dfc8d636SJohannes Weiner {
79664574746SJohannes Weiner 	int referenced_ptes, referenced_page;
797dfc8d636SJohannes Weiner 	unsigned long vm_flags;
798dfc8d636SJohannes Weiner 
799c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
800c3ac9a8aSJohannes Weiner 					  &vm_flags);
80164574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
802dfc8d636SJohannes Weiner 
803dfc8d636SJohannes Weiner 	/*
804dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
805dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
806dfc8d636SJohannes Weiner 	 */
807dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
808dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
809dfc8d636SJohannes Weiner 
81064574746SJohannes Weiner 	if (referenced_ptes) {
811e4898273SMichal Hocko 		if (PageSwapBacked(page))
81264574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
81364574746SJohannes Weiner 		/*
81464574746SJohannes Weiner 		 * All mapped pages start out with page table
81564574746SJohannes Weiner 		 * references from the instantiating fault, so we need
81664574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
81764574746SJohannes Weiner 		 * than once.
81864574746SJohannes Weiner 		 *
81964574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
82064574746SJohannes Weiner 		 * inactive list.  Another page table reference will
82164574746SJohannes Weiner 		 * lead to its activation.
82264574746SJohannes Weiner 		 *
82364574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
82464574746SJohannes Weiner 		 * so that recently deactivated but used pages are
82564574746SJohannes Weiner 		 * quickly recovered.
82664574746SJohannes Weiner 		 */
82764574746SJohannes Weiner 		SetPageReferenced(page);
82864574746SJohannes Weiner 
82934dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
830dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
831dfc8d636SJohannes Weiner 
832c909e993SKonstantin Khlebnikov 		/*
833c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
834c909e993SKonstantin Khlebnikov 		 */
835c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
836c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
837c909e993SKonstantin Khlebnikov 
83864574746SJohannes Weiner 		return PAGEREF_KEEP;
83964574746SJohannes Weiner 	}
84064574746SJohannes Weiner 
841dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
8422e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
843dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
84464574746SJohannes Weiner 
84564574746SJohannes Weiner 	return PAGEREF_RECLAIM;
846dfc8d636SJohannes Weiner }
847dfc8d636SJohannes Weiner 
848e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
849e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
850e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
851e2be15f6SMel Gorman {
852b4597226SMel Gorman 	struct address_space *mapping;
853b4597226SMel Gorman 
854e2be15f6SMel Gorman 	/*
855e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
856e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
857e2be15f6SMel Gorman 	 */
858e2be15f6SMel Gorman 	if (!page_is_file_cache(page)) {
859e2be15f6SMel Gorman 		*dirty = false;
860e2be15f6SMel Gorman 		*writeback = false;
861e2be15f6SMel Gorman 		return;
862e2be15f6SMel Gorman 	}
863e2be15f6SMel Gorman 
864e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
865e2be15f6SMel Gorman 	*dirty = PageDirty(page);
866e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
867b4597226SMel Gorman 
868b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
869b4597226SMel Gorman 	if (!page_has_private(page))
870b4597226SMel Gorman 		return;
871b4597226SMel Gorman 
872b4597226SMel Gorman 	mapping = page_mapping(page);
873b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
874b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
875e2be15f6SMel Gorman }
876e2be15f6SMel Gorman 
877e286781dSNick Piggin /*
8781742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
8791da177e4SLinus Torvalds  */
8801742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
8816a18adb3SKonstantin Khlebnikov 				      struct zone *zone,
882f84f6e2bSMel Gorman 				      struct scan_control *sc,
88302c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
8848e950282SMel Gorman 				      unsigned long *ret_nr_dirty,
885d43006d5SMel Gorman 				      unsigned long *ret_nr_unqueued_dirty,
8868e950282SMel Gorman 				      unsigned long *ret_nr_congested,
88702c6de8dSMinchan Kim 				      unsigned long *ret_nr_writeback,
888b1a6f21eSMel Gorman 				      unsigned long *ret_nr_immediate,
88902c6de8dSMinchan Kim 				      bool force_reclaim)
8901da177e4SLinus Torvalds {
8911da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
892abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
8931da177e4SLinus Torvalds 	int pgactivate = 0;
894d43006d5SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
8950e093d99SMel Gorman 	unsigned long nr_dirty = 0;
8960e093d99SMel Gorman 	unsigned long nr_congested = 0;
89705ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
89892df3a72SMel Gorman 	unsigned long nr_writeback = 0;
899b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
9001da177e4SLinus Torvalds 
9011da177e4SLinus Torvalds 	cond_resched();
9021da177e4SLinus Torvalds 
9031da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
9041da177e4SLinus Torvalds 		struct address_space *mapping;
9051da177e4SLinus Torvalds 		struct page *page;
9061da177e4SLinus Torvalds 		int may_enter_fs;
90702c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
908e2be15f6SMel Gorman 		bool dirty, writeback;
9091da177e4SLinus Torvalds 
9101da177e4SLinus Torvalds 		cond_resched();
9111da177e4SLinus Torvalds 
9121da177e4SLinus Torvalds 		page = lru_to_page(page_list);
9131da177e4SLinus Torvalds 		list_del(&page->lru);
9141da177e4SLinus Torvalds 
915529ae9aaSNick Piggin 		if (!trylock_page(page))
9161da177e4SLinus Torvalds 			goto keep;
9171da177e4SLinus Torvalds 
918309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
919309381feSSasha Levin 		VM_BUG_ON_PAGE(page_zone(page) != zone, page);
9201da177e4SLinus Torvalds 
9211da177e4SLinus Torvalds 		sc->nr_scanned++;
92280e43426SChristoph Lameter 
92339b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
924b291f000SNick Piggin 			goto cull_mlocked;
925894bc310SLee Schermerhorn 
926a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
92780e43426SChristoph Lameter 			goto keep_locked;
92880e43426SChristoph Lameter 
9291da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
9301da177e4SLinus Torvalds 		if (page_mapped(page) || PageSwapCache(page))
9311da177e4SLinus Torvalds 			sc->nr_scanned++;
9321da177e4SLinus Torvalds 
933c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
934c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
935c661b078SAndy Whitcroft 
936e62e384eSMichal Hocko 		/*
937e2be15f6SMel Gorman 		 * The number of dirty pages determines if a zone is marked
938e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
939e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
940e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
941e2be15f6SMel Gorman 		 */
942e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
943e2be15f6SMel Gorman 		if (dirty || writeback)
944e2be15f6SMel Gorman 			nr_dirty++;
945e2be15f6SMel Gorman 
946e2be15f6SMel Gorman 		if (dirty && !writeback)
947e2be15f6SMel Gorman 			nr_unqueued_dirty++;
948e2be15f6SMel Gorman 
949d04e8acdSMel Gorman 		/*
950d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
951d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
952d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
953d04e8acdSMel Gorman 		 * end of the LRU a second time.
954d04e8acdSMel Gorman 		 */
955e2be15f6SMel Gorman 		mapping = page_mapping(page);
9561da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
957703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
958d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
959e2be15f6SMel Gorman 			nr_congested++;
960e2be15f6SMel Gorman 
961e2be15f6SMel Gorman 		/*
962283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
963283aba9fSMel Gorman 		 * are three cases to consider.
964e62e384eSMichal Hocko 		 *
965283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
966283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
967283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
968283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
969283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
970283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
971283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
972b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
973b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
974c3b94f44SHugh Dickins 		 *
97597c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
976*ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
977*ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
978*ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
97997c9341fSTejun Heo 		 *    reclaim and continue scanning.
980283aba9fSMel Gorman 		 *
981*ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
982*ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
983283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
984283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
985283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
986283aba9fSMel Gorman 		 *    would probably show more reasons.
987283aba9fSMel Gorman 		 *
98897c9341fSTejun Heo 		 * 3) Legacy memcg encounters a page that is not already marked
989283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
990283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
991283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
992283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
993e62e384eSMichal Hocko 		 */
994283aba9fSMel Gorman 		if (PageWriteback(page)) {
995283aba9fSMel Gorman 			/* Case 1 above */
996283aba9fSMel Gorman 			if (current_is_kswapd() &&
997283aba9fSMel Gorman 			    PageReclaim(page) &&
99857054651SJohannes Weiner 			    test_bit(ZONE_WRITEBACK, &zone->flags)) {
999b1a6f21eSMel Gorman 				nr_immediate++;
1000b1a6f21eSMel Gorman 				goto keep_locked;
1001283aba9fSMel Gorman 
1002283aba9fSMel Gorman 			/* Case 2 above */
100397c9341fSTejun Heo 			} else if (sane_reclaim(sc) ||
1004*ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1005c3b94f44SHugh Dickins 				/*
1006c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1007c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1008c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1009c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1010c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1011c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1012c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1013c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1014c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1015c3b94f44SHugh Dickins 				 */
1016c3b94f44SHugh Dickins 				SetPageReclaim(page);
101792df3a72SMel Gorman 				nr_writeback++;
1018283aba9fSMel Gorman 
1019c3b94f44SHugh Dickins 				goto keep_locked;
1020283aba9fSMel Gorman 
1021283aba9fSMel Gorman 			/* Case 3 above */
1022283aba9fSMel Gorman 			} else {
1023c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
1024e62e384eSMichal Hocko 			}
1025283aba9fSMel Gorman 		}
10261da177e4SLinus Torvalds 
102702c6de8dSMinchan Kim 		if (!force_reclaim)
10286a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
102902c6de8dSMinchan Kim 
1030dfc8d636SJohannes Weiner 		switch (references) {
1031dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
10321da177e4SLinus Torvalds 			goto activate_locked;
103364574746SJohannes Weiner 		case PAGEREF_KEEP:
103464574746SJohannes Weiner 			goto keep_locked;
1035dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1036dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1037dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1038dfc8d636SJohannes Weiner 		}
10391da177e4SLinus Torvalds 
10401da177e4SLinus Torvalds 		/*
10411da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
10421da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
10431da177e4SLinus Torvalds 		 */
1044b291f000SNick Piggin 		if (PageAnon(page) && !PageSwapCache(page)) {
104563eb6b93SHugh Dickins 			if (!(sc->gfp_mask & __GFP_IO))
104663eb6b93SHugh Dickins 				goto keep_locked;
10475bc7b8acSShaohua Li 			if (!add_to_swap(page, page_list))
10481da177e4SLinus Torvalds 				goto activate_locked;
104963eb6b93SHugh Dickins 			may_enter_fs = 1;
10501da177e4SLinus Torvalds 
1051e2be15f6SMel Gorman 			/* Adding to swap updated mapping */
10521da177e4SLinus Torvalds 			mapping = page_mapping(page);
1053e2be15f6SMel Gorman 		}
10541da177e4SLinus Torvalds 
10551da177e4SLinus Torvalds 		/*
10561da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
10571da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
10581da177e4SLinus Torvalds 		 */
10591da177e4SLinus Torvalds 		if (page_mapped(page) && mapping) {
106002c6de8dSMinchan Kim 			switch (try_to_unmap(page, ttu_flags)) {
10611da177e4SLinus Torvalds 			case SWAP_FAIL:
10621da177e4SLinus Torvalds 				goto activate_locked;
10631da177e4SLinus Torvalds 			case SWAP_AGAIN:
10641da177e4SLinus Torvalds 				goto keep_locked;
1065b291f000SNick Piggin 			case SWAP_MLOCK:
1066b291f000SNick Piggin 				goto cull_mlocked;
10671da177e4SLinus Torvalds 			case SWAP_SUCCESS:
10681da177e4SLinus Torvalds 				; /* try to free the page below */
10691da177e4SLinus Torvalds 			}
10701da177e4SLinus Torvalds 		}
10711da177e4SLinus Torvalds 
10721da177e4SLinus Torvalds 		if (PageDirty(page)) {
1073ee72886dSMel Gorman 			/*
1074ee72886dSMel Gorman 			 * Only kswapd can writeback filesystem pages to
1075d43006d5SMel Gorman 			 * avoid risk of stack overflow but only writeback
1076d43006d5SMel Gorman 			 * if many dirty pages have been encountered.
1077ee72886dSMel Gorman 			 */
1078f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
10799e3b2f8cSKonstantin Khlebnikov 					(!current_is_kswapd() ||
108057054651SJohannes Weiner 					 !test_bit(ZONE_DIRTY, &zone->flags))) {
108149ea7eb6SMel Gorman 				/*
108249ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
108349ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
108449ea7eb6SMel Gorman 				 * except we already have the page isolated
108549ea7eb6SMel Gorman 				 * and know it's dirty
108649ea7eb6SMel Gorman 				 */
108749ea7eb6SMel Gorman 				inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE);
108849ea7eb6SMel Gorman 				SetPageReclaim(page);
108949ea7eb6SMel Gorman 
1090ee72886dSMel Gorman 				goto keep_locked;
1091ee72886dSMel Gorman 			}
1092ee72886dSMel Gorman 
1093dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
10941da177e4SLinus Torvalds 				goto keep_locked;
10954dd4b920SAndrew Morton 			if (!may_enter_fs)
10961da177e4SLinus Torvalds 				goto keep_locked;
109752a8363eSChristoph Lameter 			if (!sc->may_writepage)
10981da177e4SLinus Torvalds 				goto keep_locked;
10991da177e4SLinus Torvalds 
11001da177e4SLinus Torvalds 			/* Page is dirty, try to write it out here */
11017d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
11021da177e4SLinus Torvalds 			case PAGE_KEEP:
11031da177e4SLinus Torvalds 				goto keep_locked;
11041da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
11051da177e4SLinus Torvalds 				goto activate_locked;
11061da177e4SLinus Torvalds 			case PAGE_SUCCESS:
11077d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
110841ac1999SMel Gorman 					goto keep;
11097d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
11101da177e4SLinus Torvalds 					goto keep;
11117d3579e8SKOSAKI Motohiro 
11121da177e4SLinus Torvalds 				/*
11131da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
11141da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
11151da177e4SLinus Torvalds 				 */
1116529ae9aaSNick Piggin 				if (!trylock_page(page))
11171da177e4SLinus Torvalds 					goto keep;
11181da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
11191da177e4SLinus Torvalds 					goto keep_locked;
11201da177e4SLinus Torvalds 				mapping = page_mapping(page);
11211da177e4SLinus Torvalds 			case PAGE_CLEAN:
11221da177e4SLinus Torvalds 				; /* try to free the page below */
11231da177e4SLinus Torvalds 			}
11241da177e4SLinus Torvalds 		}
11251da177e4SLinus Torvalds 
11261da177e4SLinus Torvalds 		/*
11271da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
11281da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
11291da177e4SLinus Torvalds 		 * the page as well.
11301da177e4SLinus Torvalds 		 *
11311da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
11321da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
11331da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
11341da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
11351da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
11361da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
11371da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
11381da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
11391da177e4SLinus Torvalds 		 *
11401da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
11411da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
11421da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
11431da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
11441da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
11451da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
11461da177e4SLinus Torvalds 		 */
1147266cf658SDavid Howells 		if (page_has_private(page)) {
11481da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
11491da177e4SLinus Torvalds 				goto activate_locked;
1150e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1151e286781dSNick Piggin 				unlock_page(page);
1152e286781dSNick Piggin 				if (put_page_testzero(page))
11531da177e4SLinus Torvalds 					goto free_it;
1154e286781dSNick Piggin 				else {
1155e286781dSNick Piggin 					/*
1156e286781dSNick Piggin 					 * rare race with speculative reference.
1157e286781dSNick Piggin 					 * the speculative reference will free
1158e286781dSNick Piggin 					 * this page shortly, so we may
1159e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1160e286781dSNick Piggin 					 * leave it off the LRU).
1161e286781dSNick Piggin 					 */
1162e286781dSNick Piggin 					nr_reclaimed++;
1163e286781dSNick Piggin 					continue;
1164e286781dSNick Piggin 				}
1165e286781dSNick Piggin 			}
11661da177e4SLinus Torvalds 		}
11671da177e4SLinus Torvalds 
1168a528910eSJohannes Weiner 		if (!mapping || !__remove_mapping(mapping, page, true))
116949d2e9ccSChristoph Lameter 			goto keep_locked;
11701da177e4SLinus Torvalds 
1171a978d6f5SNick Piggin 		/*
1172a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
1173a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
1174a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
1175a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
1176a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
1177a978d6f5SNick Piggin 		 */
1178a978d6f5SNick Piggin 		__clear_page_locked(page);
1179e286781dSNick Piggin free_it:
118005ff5137SAndrew Morton 		nr_reclaimed++;
1181abe4c3b5SMel Gorman 
1182abe4c3b5SMel Gorman 		/*
1183abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1184abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1185abe4c3b5SMel Gorman 		 */
1186abe4c3b5SMel Gorman 		list_add(&page->lru, &free_pages);
11871da177e4SLinus Torvalds 		continue;
11881da177e4SLinus Torvalds 
1189b291f000SNick Piggin cull_mlocked:
119063d6c5adSHugh Dickins 		if (PageSwapCache(page))
119163d6c5adSHugh Dickins 			try_to_free_swap(page);
1192b291f000SNick Piggin 		unlock_page(page);
1193b291f000SNick Piggin 		putback_lru_page(page);
1194b291f000SNick Piggin 		continue;
1195b291f000SNick Piggin 
11961da177e4SLinus Torvalds activate_locked:
119768a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
119868a22394SRik van Riel 		if (PageSwapCache(page) && vm_swap_full())
1199a2c43eedSHugh Dickins 			try_to_free_swap(page);
1200309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
12011da177e4SLinus Torvalds 		SetPageActive(page);
12021da177e4SLinus Torvalds 		pgactivate++;
12031da177e4SLinus Torvalds keep_locked:
12041da177e4SLinus Torvalds 		unlock_page(page);
12051da177e4SLinus Torvalds keep:
12061da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1207309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
12081da177e4SLinus Torvalds 	}
1209abe4c3b5SMel Gorman 
1210747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
1211b745bc85SMel Gorman 	free_hot_cold_page_list(&free_pages, true);
1212abe4c3b5SMel Gorman 
12131da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1214f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
12150a31bc97SJohannes Weiner 
12168e950282SMel Gorman 	*ret_nr_dirty += nr_dirty;
12178e950282SMel Gorman 	*ret_nr_congested += nr_congested;
1218d43006d5SMel Gorman 	*ret_nr_unqueued_dirty += nr_unqueued_dirty;
121992df3a72SMel Gorman 	*ret_nr_writeback += nr_writeback;
1220b1a6f21eSMel Gorman 	*ret_nr_immediate += nr_immediate;
122105ff5137SAndrew Morton 	return nr_reclaimed;
12221da177e4SLinus Torvalds }
12231da177e4SLinus Torvalds 
122402c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
122502c6de8dSMinchan Kim 					    struct list_head *page_list)
122602c6de8dSMinchan Kim {
122702c6de8dSMinchan Kim 	struct scan_control sc = {
122802c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
122902c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
123002c6de8dSMinchan Kim 		.may_unmap = 1,
123102c6de8dSMinchan Kim 	};
12328e950282SMel Gorman 	unsigned long ret, dummy1, dummy2, dummy3, dummy4, dummy5;
123302c6de8dSMinchan Kim 	struct page *page, *next;
123402c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
123502c6de8dSMinchan Kim 
123602c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1237117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1238117aad1eSRafael Aquini 		    !isolated_balloon_page(page)) {
123902c6de8dSMinchan Kim 			ClearPageActive(page);
124002c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
124102c6de8dSMinchan Kim 		}
124202c6de8dSMinchan Kim 	}
124302c6de8dSMinchan Kim 
124402c6de8dSMinchan Kim 	ret = shrink_page_list(&clean_pages, zone, &sc,
124502c6de8dSMinchan Kim 			TTU_UNMAP|TTU_IGNORE_ACCESS,
12468e950282SMel Gorman 			&dummy1, &dummy2, &dummy3, &dummy4, &dummy5, true);
124702c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
124883da7510SChristoph Lameter 	mod_zone_page_state(zone, NR_ISOLATED_FILE, -ret);
124902c6de8dSMinchan Kim 	return ret;
125002c6de8dSMinchan Kim }
125102c6de8dSMinchan Kim 
12525ad333ebSAndy Whitcroft /*
12535ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
12545ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
12555ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
12565ad333ebSAndy Whitcroft  *
12575ad333ebSAndy Whitcroft  * page:	page to consider
12585ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
12595ad333ebSAndy Whitcroft  *
12605ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
12615ad333ebSAndy Whitcroft  */
1262f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
12635ad333ebSAndy Whitcroft {
12645ad333ebSAndy Whitcroft 	int ret = -EINVAL;
12655ad333ebSAndy Whitcroft 
12665ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
12675ad333ebSAndy Whitcroft 	if (!PageLRU(page))
12685ad333ebSAndy Whitcroft 		return ret;
12695ad333ebSAndy Whitcroft 
1270e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1271e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1272894bc310SLee Schermerhorn 		return ret;
1273894bc310SLee Schermerhorn 
12745ad333ebSAndy Whitcroft 	ret = -EBUSY;
127508e552c6SKAMEZAWA Hiroyuki 
1276c8244935SMel Gorman 	/*
1277c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1278c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1279c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1280c8244935SMel Gorman 	 *
1281c8244935SMel Gorman 	 * ISOLATE_CLEAN means that only clean pages should be isolated. This
1282c8244935SMel Gorman 	 * is used by reclaim when it is cannot write to backing storage
1283c8244935SMel Gorman 	 *
1284c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1285c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1286c8244935SMel Gorman 	 */
1287c8244935SMel Gorman 	if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
1288c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1289c8244935SMel Gorman 		if (PageWriteback(page))
129039deaf85SMinchan Kim 			return ret;
129139deaf85SMinchan Kim 
1292c8244935SMel Gorman 		if (PageDirty(page)) {
1293c8244935SMel Gorman 			struct address_space *mapping;
1294c8244935SMel Gorman 
1295c8244935SMel Gorman 			/* ISOLATE_CLEAN means only clean pages */
1296c8244935SMel Gorman 			if (mode & ISOLATE_CLEAN)
1297c8244935SMel Gorman 				return ret;
1298c8244935SMel Gorman 
1299c8244935SMel Gorman 			/*
1300c8244935SMel Gorman 			 * Only pages without mappings or that have a
1301c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
1302c8244935SMel Gorman 			 * without blocking
1303c8244935SMel Gorman 			 */
1304c8244935SMel Gorman 			mapping = page_mapping(page);
1305c8244935SMel Gorman 			if (mapping && !mapping->a_ops->migratepage)
1306c8244935SMel Gorman 				return ret;
1307c8244935SMel Gorman 		}
1308c8244935SMel Gorman 	}
1309c8244935SMel Gorman 
1310f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1311f80c0673SMinchan Kim 		return ret;
1312f80c0673SMinchan Kim 
13135ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
13145ad333ebSAndy Whitcroft 		/*
13155ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
13165ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
13175ad333ebSAndy Whitcroft 		 * page release code relies on it.
13185ad333ebSAndy Whitcroft 		 */
13195ad333ebSAndy Whitcroft 		ClearPageLRU(page);
13205ad333ebSAndy Whitcroft 		ret = 0;
13215ad333ebSAndy Whitcroft 	}
13225ad333ebSAndy Whitcroft 
13235ad333ebSAndy Whitcroft 	return ret;
13245ad333ebSAndy Whitcroft }
13255ad333ebSAndy Whitcroft 
132649d2e9ccSChristoph Lameter /*
13271da177e4SLinus Torvalds  * zone->lru_lock is heavily contended.  Some of the functions that
13281da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
13291da177e4SLinus Torvalds  * and working on them outside the LRU lock.
13301da177e4SLinus Torvalds  *
13311da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
13321da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
13331da177e4SLinus Torvalds  *
13341da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
13351da177e4SLinus Torvalds  *
13361da177e4SLinus Torvalds  * @nr_to_scan:	The number of pages to look through on the list.
13375dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
13381da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1339f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1340fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
13415ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
13423cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
13431da177e4SLinus Torvalds  *
13441da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
13451da177e4SLinus Torvalds  */
134669e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
13475dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1348fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
13493cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
13501da177e4SLinus Torvalds {
135175b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
135269e05944SAndrew Morton 	unsigned long nr_taken = 0;
1353c9b02d97SWu Fengguang 	unsigned long scan;
13541da177e4SLinus Torvalds 
1355c9b02d97SWu Fengguang 	for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
13565ad333ebSAndy Whitcroft 		struct page *page;
1357fa9add64SHugh Dickins 		int nr_pages;
13585ad333ebSAndy Whitcroft 
13591da177e4SLinus Torvalds 		page = lru_to_page(src);
13601da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
13611da177e4SLinus Torvalds 
1362309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
13638d438f96SNick Piggin 
1364f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
13655ad333ebSAndy Whitcroft 		case 0:
1366fa9add64SHugh Dickins 			nr_pages = hpage_nr_pages(page);
1367fa9add64SHugh Dickins 			mem_cgroup_update_lru_size(lruvec, lru, -nr_pages);
13685ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
1369fa9add64SHugh Dickins 			nr_taken += nr_pages;
13705ad333ebSAndy Whitcroft 			break;
13717c8ee9a8SNick Piggin 
13725ad333ebSAndy Whitcroft 		case -EBUSY:
13735ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
13745ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
13755ad333ebSAndy Whitcroft 			continue;
13765ad333ebSAndy Whitcroft 
13775ad333ebSAndy Whitcroft 		default:
13785ad333ebSAndy Whitcroft 			BUG();
13795ad333ebSAndy Whitcroft 		}
13805ad333ebSAndy Whitcroft 	}
13811da177e4SLinus Torvalds 
1382f626012dSHugh Dickins 	*nr_scanned = scan;
138375b00af7SHugh Dickins 	trace_mm_vmscan_lru_isolate(sc->order, nr_to_scan, scan,
138475b00af7SHugh Dickins 				    nr_taken, mode, is_file_lru(lru));
13851da177e4SLinus Torvalds 	return nr_taken;
13861da177e4SLinus Torvalds }
13871da177e4SLinus Torvalds 
138862695a84SNick Piggin /**
138962695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
139062695a84SNick Piggin  * @page: page to isolate from its LRU list
139162695a84SNick Piggin  *
139262695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
139362695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
139462695a84SNick Piggin  *
139562695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
139662695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
139762695a84SNick Piggin  *
139862695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1399894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1400894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1401894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
140262695a84SNick Piggin  *
140362695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
140462695a84SNick Piggin  * found will be decremented.
140562695a84SNick Piggin  *
140662695a84SNick Piggin  * Restrictions:
140762695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
140862695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
140962695a84SNick Piggin  *     without a stable reference).
141062695a84SNick Piggin  * (2) the lru_lock must not be held.
141162695a84SNick Piggin  * (3) interrupts must be enabled.
141262695a84SNick Piggin  */
141362695a84SNick Piggin int isolate_lru_page(struct page *page)
141462695a84SNick Piggin {
141562695a84SNick Piggin 	int ret = -EBUSY;
141662695a84SNick Piggin 
1417309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
14180c917313SKonstantin Khlebnikov 
141962695a84SNick Piggin 	if (PageLRU(page)) {
142062695a84SNick Piggin 		struct zone *zone = page_zone(page);
1421fa9add64SHugh Dickins 		struct lruvec *lruvec;
142262695a84SNick Piggin 
142362695a84SNick Piggin 		spin_lock_irq(&zone->lru_lock);
1424fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
14250c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1426894bc310SLee Schermerhorn 			int lru = page_lru(page);
14270c917313SKonstantin Khlebnikov 			get_page(page);
142862695a84SNick Piggin 			ClearPageLRU(page);
1429fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1430fa9add64SHugh Dickins 			ret = 0;
143162695a84SNick Piggin 		}
143262695a84SNick Piggin 		spin_unlock_irq(&zone->lru_lock);
143362695a84SNick Piggin 	}
143462695a84SNick Piggin 	return ret;
143562695a84SNick Piggin }
143662695a84SNick Piggin 
14375ad333ebSAndy Whitcroft /*
1438d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1439d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1440d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1441d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1442d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
144335cd7815SRik van Riel  */
144435cd7815SRik van Riel static int too_many_isolated(struct zone *zone, int file,
144535cd7815SRik van Riel 		struct scan_control *sc)
144635cd7815SRik van Riel {
144735cd7815SRik van Riel 	unsigned long inactive, isolated;
144835cd7815SRik van Riel 
144935cd7815SRik van Riel 	if (current_is_kswapd())
145035cd7815SRik van Riel 		return 0;
145135cd7815SRik van Riel 
145297c9341fSTejun Heo 	if (!sane_reclaim(sc))
145335cd7815SRik van Riel 		return 0;
145435cd7815SRik van Riel 
145535cd7815SRik van Riel 	if (file) {
145635cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_FILE);
145735cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_FILE);
145835cd7815SRik van Riel 	} else {
145935cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_ANON);
146035cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_ANON);
146135cd7815SRik van Riel 	}
146235cd7815SRik van Riel 
14633cf23841SFengguang Wu 	/*
14643cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
14653cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
14663cf23841SFengguang Wu 	 * deadlock.
14673cf23841SFengguang Wu 	 */
14683cf23841SFengguang Wu 	if ((sc->gfp_mask & GFP_IOFS) == GFP_IOFS)
14693cf23841SFengguang Wu 		inactive >>= 3;
14703cf23841SFengguang Wu 
147135cd7815SRik van Riel 	return isolated > inactive;
147235cd7815SRik van Riel }
147335cd7815SRik van Riel 
147466635629SMel Gorman static noinline_for_stack void
147575b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
147666635629SMel Gorman {
147727ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
147827ac81d8SKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
14793f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
148066635629SMel Gorman 
148166635629SMel Gorman 	/*
148266635629SMel Gorman 	 * Put back any unfreeable pages.
148366635629SMel Gorman 	 */
148466635629SMel Gorman 	while (!list_empty(page_list)) {
14853f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
148666635629SMel Gorman 		int lru;
14873f79768fSHugh Dickins 
1488309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
148966635629SMel Gorman 		list_del(&page->lru);
149039b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
149166635629SMel Gorman 			spin_unlock_irq(&zone->lru_lock);
149266635629SMel Gorman 			putback_lru_page(page);
149366635629SMel Gorman 			spin_lock_irq(&zone->lru_lock);
149466635629SMel Gorman 			continue;
149566635629SMel Gorman 		}
1496fa9add64SHugh Dickins 
1497fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
1498fa9add64SHugh Dickins 
14997a608572SLinus Torvalds 		SetPageLRU(page);
150066635629SMel Gorman 		lru = page_lru(page);
1501fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1502fa9add64SHugh Dickins 
150366635629SMel Gorman 		if (is_active_lru(lru)) {
150466635629SMel Gorman 			int file = is_file_lru(lru);
15059992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
15069992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
150766635629SMel Gorman 		}
15082bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
15092bcf8879SHugh Dickins 			__ClearPageLRU(page);
15102bcf8879SHugh Dickins 			__ClearPageActive(page);
1511fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
15122bcf8879SHugh Dickins 
15132bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
151466635629SMel Gorman 				spin_unlock_irq(&zone->lru_lock);
1515747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
15162bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
151766635629SMel Gorman 				spin_lock_irq(&zone->lru_lock);
15182bcf8879SHugh Dickins 			} else
15192bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
152066635629SMel Gorman 		}
152166635629SMel Gorman 	}
152266635629SMel Gorman 
15233f79768fSHugh Dickins 	/*
15243f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
15253f79768fSHugh Dickins 	 */
15263f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
152766635629SMel Gorman }
152866635629SMel Gorman 
152966635629SMel Gorman /*
1530399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1531399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1532399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1533399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1534399ba0b9SNeilBrown  */
1535399ba0b9SNeilBrown static int current_may_throttle(void)
1536399ba0b9SNeilBrown {
1537399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1538399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1539399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1540399ba0b9SNeilBrown }
1541399ba0b9SNeilBrown 
1542399ba0b9SNeilBrown /*
15431742f19fSAndrew Morton  * shrink_inactive_list() is a helper for shrink_zone().  It returns the number
15441742f19fSAndrew Morton  * of reclaimed pages
15451da177e4SLinus Torvalds  */
154666635629SMel Gorman static noinline_for_stack unsigned long
15471a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
15489e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
15491da177e4SLinus Torvalds {
15501da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1551e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
155205ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1553e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
15548e950282SMel Gorman 	unsigned long nr_dirty = 0;
15558e950282SMel Gorman 	unsigned long nr_congested = 0;
1556e2be15f6SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
155792df3a72SMel Gorman 	unsigned long nr_writeback = 0;
1558b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
1559f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
15603cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
15611a93be0eSKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
15621a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
156378dc583dSKOSAKI Motohiro 
156435cd7815SRik van Riel 	while (unlikely(too_many_isolated(zone, file, sc))) {
156558355c78SKOSAKI Motohiro 		congestion_wait(BLK_RW_ASYNC, HZ/10);
156635cd7815SRik van Riel 
156735cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
156835cd7815SRik van Riel 		if (fatal_signal_pending(current))
156935cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
157035cd7815SRik van Riel 	}
157135cd7815SRik van Riel 
15721da177e4SLinus Torvalds 	lru_add_drain();
1573f80c0673SMinchan Kim 
1574f80c0673SMinchan Kim 	if (!sc->may_unmap)
157561317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1576f80c0673SMinchan Kim 	if (!sc->may_writepage)
157761317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1578f80c0673SMinchan Kim 
15791da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
15801da177e4SLinus Torvalds 
15815dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
15825dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
158395d918fcSKonstantin Khlebnikov 
158495d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
158595d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
158695d918fcSKonstantin Khlebnikov 
158789b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
15880d5d823aSMel Gorman 		__mod_zone_page_state(zone, NR_PAGES_SCANNED, nr_scanned);
1589b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
159075b00af7SHugh Dickins 			__count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scanned);
1591b35ea17bSKOSAKI Motohiro 		else
159275b00af7SHugh Dickins 			__count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scanned);
1593b35ea17bSKOSAKI Motohiro 	}
159466635629SMel Gorman 	spin_unlock_irq(&zone->lru_lock);
1595d563c050SHillf Danton 
1596d563c050SHillf Danton 	if (nr_taken == 0)
159766635629SMel Gorman 		return 0;
1598b35ea17bSKOSAKI Motohiro 
159902c6de8dSMinchan Kim 	nr_reclaimed = shrink_page_list(&page_list, zone, sc, TTU_UNMAP,
16008e950282SMel Gorman 				&nr_dirty, &nr_unqueued_dirty, &nr_congested,
16018e950282SMel Gorman 				&nr_writeback, &nr_immediate,
1602b1a6f21eSMel Gorman 				false);
1603c661b078SAndy Whitcroft 
16043f79768fSHugh Dickins 	spin_lock_irq(&zone->lru_lock);
16053f79768fSHugh Dickins 
160695d918fcSKonstantin Khlebnikov 	reclaim_stat->recent_scanned[file] += nr_taken;
1607d563c050SHillf Danton 
1608904249aaSYing Han 	if (global_reclaim(sc)) {
1609b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1610904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_KSWAPD, zone,
1611904249aaSYing Han 					       nr_reclaimed);
1612904249aaSYing Han 		else
1613904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_DIRECT, zone,
1614904249aaSYing Han 					       nr_reclaimed);
1615904249aaSYing Han 	}
1616a74609faSNick Piggin 
161727ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
16183f79768fSHugh Dickins 
161995d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
16203f79768fSHugh Dickins 
16213f79768fSHugh Dickins 	spin_unlock_irq(&zone->lru_lock);
16223f79768fSHugh Dickins 
1623747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
1624b745bc85SMel Gorman 	free_hot_cold_page_list(&page_list, true);
1625e11da5b4SMel Gorman 
162692df3a72SMel Gorman 	/*
162792df3a72SMel Gorman 	 * If reclaim is isolating dirty pages under writeback, it implies
162892df3a72SMel Gorman 	 * that the long-lived page allocation rate is exceeding the page
162992df3a72SMel Gorman 	 * laundering rate. Either the global limits are not being effective
163092df3a72SMel Gorman 	 * at throttling processes due to the page distribution throughout
163192df3a72SMel Gorman 	 * zones or there is heavy usage of a slow backing device. The
163292df3a72SMel Gorman 	 * only option is to throttle from reclaim context which is not ideal
163392df3a72SMel Gorman 	 * as there is no guarantee the dirtying process is throttled in the
163492df3a72SMel Gorman 	 * same way balance_dirty_pages() manages.
163592df3a72SMel Gorman 	 *
16368e950282SMel Gorman 	 * Once a zone is flagged ZONE_WRITEBACK, kswapd will count the number
16378e950282SMel Gorman 	 * of pages under pages flagged for immediate reclaim and stall if any
16388e950282SMel Gorman 	 * are encountered in the nr_immediate check below.
163992df3a72SMel Gorman 	 */
1640918fc718SMel Gorman 	if (nr_writeback && nr_writeback == nr_taken)
164157054651SJohannes Weiner 		set_bit(ZONE_WRITEBACK, &zone->flags);
164292df3a72SMel Gorman 
1643d43006d5SMel Gorman 	/*
164497c9341fSTejun Heo 	 * Legacy memcg will stall in page writeback so avoid forcibly
164597c9341fSTejun Heo 	 * stalling here.
1646d43006d5SMel Gorman 	 */
164797c9341fSTejun Heo 	if (sane_reclaim(sc)) {
1648b1a6f21eSMel Gorman 		/*
16498e950282SMel Gorman 		 * Tag a zone as congested if all the dirty pages scanned were
16508e950282SMel Gorman 		 * backed by a congested BDI and wait_iff_congested will stall.
16518e950282SMel Gorman 		 */
16528e950282SMel Gorman 		if (nr_dirty && nr_dirty == nr_congested)
165357054651SJohannes Weiner 			set_bit(ZONE_CONGESTED, &zone->flags);
16548e950282SMel Gorman 
16558e950282SMel Gorman 		/*
1656b1a6f21eSMel Gorman 		 * If dirty pages are scanned that are not queued for IO, it
1657b1a6f21eSMel Gorman 		 * implies that flushers are not keeping up. In this case, flag
165857054651SJohannes Weiner 		 * the zone ZONE_DIRTY and kswapd will start writing pages from
165957054651SJohannes Weiner 		 * reclaim context.
1660b1a6f21eSMel Gorman 		 */
1661b1a6f21eSMel Gorman 		if (nr_unqueued_dirty == nr_taken)
166257054651SJohannes Weiner 			set_bit(ZONE_DIRTY, &zone->flags);
1663b1a6f21eSMel Gorman 
1664b1a6f21eSMel Gorman 		/*
1665b738d764SLinus Torvalds 		 * If kswapd scans pages marked marked for immediate
1666b738d764SLinus Torvalds 		 * reclaim and under writeback (nr_immediate), it implies
1667b738d764SLinus Torvalds 		 * that pages are cycling through the LRU faster than
1668b1a6f21eSMel Gorman 		 * they are written so also forcibly stall.
1669b1a6f21eSMel Gorman 		 */
1670b738d764SLinus Torvalds 		if (nr_immediate && current_may_throttle())
1671b1a6f21eSMel Gorman 			congestion_wait(BLK_RW_ASYNC, HZ/10);
1672e2be15f6SMel Gorman 	}
1673d43006d5SMel Gorman 
16748e950282SMel Gorman 	/*
16758e950282SMel Gorman 	 * Stall direct reclaim for IO completions if underlying BDIs or zone
16768e950282SMel Gorman 	 * is congested. Allow kswapd to continue until it starts encountering
16778e950282SMel Gorman 	 * unqueued dirty pages or cycling through the LRU too quickly.
16788e950282SMel Gorman 	 */
1679399ba0b9SNeilBrown 	if (!sc->hibernation_mode && !current_is_kswapd() &&
1680399ba0b9SNeilBrown 	    current_may_throttle())
16818e950282SMel Gorman 		wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10);
16828e950282SMel Gorman 
1683e11da5b4SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(zone->zone_pgdat->node_id,
1684e11da5b4SMel Gorman 		zone_idx(zone),
1685e11da5b4SMel Gorman 		nr_scanned, nr_reclaimed,
16869e3b2f8cSKonstantin Khlebnikov 		sc->priority,
168723b9da55SMel Gorman 		trace_shrink_flags(file));
168805ff5137SAndrew Morton 	return nr_reclaimed;
16891da177e4SLinus Torvalds }
16901da177e4SLinus Torvalds 
16913bb1a852SMartin Bligh /*
16921cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
16931cfb419bSKAMEZAWA Hiroyuki  *
16941cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
16951cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
16961cfb419bSKAMEZAWA Hiroyuki  *
16971cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
16981cfb419bSKAMEZAWA Hiroyuki  * appropriate to hold zone->lru_lock across the whole operation.  But if
16991cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
17001cfb419bSKAMEZAWA Hiroyuki  * should drop zone->lru_lock around each page.  It's impossible to balance
17011cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
17021cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
17031cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
17041cfb419bSKAMEZAWA Hiroyuki  *
17051cfb419bSKAMEZAWA Hiroyuki  * The downside is that we have to touch page->_count against each page.
17061cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
17071cfb419bSKAMEZAWA Hiroyuki  */
17081cfb419bSKAMEZAWA Hiroyuki 
1709fa9add64SHugh Dickins static void move_active_pages_to_lru(struct lruvec *lruvec,
17103eb4140fSWu Fengguang 				     struct list_head *list,
17112bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
17123eb4140fSWu Fengguang 				     enum lru_list lru)
17133eb4140fSWu Fengguang {
1714fa9add64SHugh Dickins 	struct zone *zone = lruvec_zone(lruvec);
17153eb4140fSWu Fengguang 	unsigned long pgmoved = 0;
17163eb4140fSWu Fengguang 	struct page *page;
1717fa9add64SHugh Dickins 	int nr_pages;
17183eb4140fSWu Fengguang 
17193eb4140fSWu Fengguang 	while (!list_empty(list)) {
17203eb4140fSWu Fengguang 		page = lru_to_page(list);
1721fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
17223eb4140fSWu Fengguang 
1723309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
17243eb4140fSWu Fengguang 		SetPageLRU(page);
17253eb4140fSWu Fengguang 
1726fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
1727fa9add64SHugh Dickins 		mem_cgroup_update_lru_size(lruvec, lru, nr_pages);
1728925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
1729fa9add64SHugh Dickins 		pgmoved += nr_pages;
17303eb4140fSWu Fengguang 
17312bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
17322bcf8879SHugh Dickins 			__ClearPageLRU(page);
17332bcf8879SHugh Dickins 			__ClearPageActive(page);
1734fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
17352bcf8879SHugh Dickins 
17362bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
17373eb4140fSWu Fengguang 				spin_unlock_irq(&zone->lru_lock);
1738747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
17392bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
17403eb4140fSWu Fengguang 				spin_lock_irq(&zone->lru_lock);
17412bcf8879SHugh Dickins 			} else
17422bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
17433eb4140fSWu Fengguang 		}
17443eb4140fSWu Fengguang 	}
17453eb4140fSWu Fengguang 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved);
17463eb4140fSWu Fengguang 	if (!is_active_lru(lru))
17473eb4140fSWu Fengguang 		__count_vm_events(PGDEACTIVATE, pgmoved);
17483eb4140fSWu Fengguang }
17491cfb419bSKAMEZAWA Hiroyuki 
1750f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
17511a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1752f16015fbSJohannes Weiner 			       struct scan_control *sc,
17539e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
17541cfb419bSKAMEZAWA Hiroyuki {
175544c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1756f626012dSHugh Dickins 	unsigned long nr_scanned;
17576fe6b7e3SWu Fengguang 	unsigned long vm_flags;
17581cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
17598cab4754SWu Fengguang 	LIST_HEAD(l_active);
1760b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
17611cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
17621a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
176344c241f1SKOSAKI Motohiro 	unsigned long nr_rotated = 0;
1764f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
17653cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
17661a93be0eSKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
17671cfb419bSKAMEZAWA Hiroyuki 
17681da177e4SLinus Torvalds 	lru_add_drain();
1769f80c0673SMinchan Kim 
1770f80c0673SMinchan Kim 	if (!sc->may_unmap)
177161317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1772f80c0673SMinchan Kim 	if (!sc->may_writepage)
177361317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1774f80c0673SMinchan Kim 
17751da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
1776925b7673SJohannes Weiner 
17775dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
17785dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
177989b5fae5SJohannes Weiner 	if (global_reclaim(sc))
17800d5d823aSMel Gorman 		__mod_zone_page_state(zone, NR_PAGES_SCANNED, nr_scanned);
178189b5fae5SJohannes Weiner 
1782b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
17831cfb419bSKAMEZAWA Hiroyuki 
1784f626012dSHugh Dickins 	__count_zone_vm_events(PGREFILL, zone, nr_scanned);
17853cb99451SKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
1786a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
17871da177e4SLinus Torvalds 	spin_unlock_irq(&zone->lru_lock);
17881da177e4SLinus Torvalds 
17891da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
17901da177e4SLinus Torvalds 		cond_resched();
17911da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
17921da177e4SLinus Torvalds 		list_del(&page->lru);
17937e9cd484SRik van Riel 
179439b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1795894bc310SLee Schermerhorn 			putback_lru_page(page);
1796894bc310SLee Schermerhorn 			continue;
1797894bc310SLee Schermerhorn 		}
1798894bc310SLee Schermerhorn 
1799cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
1800cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
1801cc715d99SMel Gorman 				if (page_has_private(page))
1802cc715d99SMel Gorman 					try_to_release_page(page, 0);
1803cc715d99SMel Gorman 				unlock_page(page);
1804cc715d99SMel Gorman 			}
1805cc715d99SMel Gorman 		}
1806cc715d99SMel Gorman 
1807c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
1808c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
18099992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
18108cab4754SWu Fengguang 			/*
18118cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
18128cab4754SWu Fengguang 			 * give them one more trip around the active list. So
18138cab4754SWu Fengguang 			 * that executable code get better chances to stay in
18148cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
18158cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
18168cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
18178cab4754SWu Fengguang 			 * so we ignore them here.
18188cab4754SWu Fengguang 			 */
181941e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
18208cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
18218cab4754SWu Fengguang 				continue;
18228cab4754SWu Fengguang 			}
18238cab4754SWu Fengguang 		}
18247e9cd484SRik van Riel 
18255205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
18261da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
18271da177e4SLinus Torvalds 	}
18281da177e4SLinus Torvalds 
1829b555749aSAndrew Morton 	/*
18308cab4754SWu Fengguang 	 * Move pages back to the lru list.
1831b555749aSAndrew Morton 	 */
18322a1dc509SJohannes Weiner 	spin_lock_irq(&zone->lru_lock);
18334f98a2feSRik van Riel 	/*
18348cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
18358cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
18368cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
18377c0db9e9SJerome Marchand 	 * get_scan_count.
1838556adecbSRik van Riel 	 */
1839b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
1840556adecbSRik van Riel 
1841fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
1842fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1843a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1844f8891e5eSChristoph Lameter 	spin_unlock_irq(&zone->lru_lock);
18452bcf8879SHugh Dickins 
1846747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&l_hold);
1847b745bc85SMel Gorman 	free_hot_cold_page_list(&l_hold, true);
18481da177e4SLinus Torvalds }
18491da177e4SLinus Torvalds 
185074e3f3c3SMinchan Kim #ifdef CONFIG_SWAP
185114797e23SKOSAKI Motohiro static int inactive_anon_is_low_global(struct zone *zone)
1852f89eb90eSKOSAKI Motohiro {
1853f89eb90eSKOSAKI Motohiro 	unsigned long active, inactive;
1854f89eb90eSKOSAKI Motohiro 
1855f89eb90eSKOSAKI Motohiro 	active = zone_page_state(zone, NR_ACTIVE_ANON);
1856f89eb90eSKOSAKI Motohiro 	inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1857f89eb90eSKOSAKI Motohiro 
1858f89eb90eSKOSAKI Motohiro 	if (inactive * zone->inactive_ratio < active)
1859f89eb90eSKOSAKI Motohiro 		return 1;
1860f89eb90eSKOSAKI Motohiro 
1861f89eb90eSKOSAKI Motohiro 	return 0;
1862f89eb90eSKOSAKI Motohiro }
1863f89eb90eSKOSAKI Motohiro 
186414797e23SKOSAKI Motohiro /**
186514797e23SKOSAKI Motohiro  * inactive_anon_is_low - check if anonymous pages need to be deactivated
1866c56d5c7dSKonstantin Khlebnikov  * @lruvec: LRU vector to check
186714797e23SKOSAKI Motohiro  *
186814797e23SKOSAKI Motohiro  * Returns true if the zone does not have enough inactive anon pages,
186914797e23SKOSAKI Motohiro  * meaning some active anon pages need to be deactivated.
187014797e23SKOSAKI Motohiro  */
1871c56d5c7dSKonstantin Khlebnikov static int inactive_anon_is_low(struct lruvec *lruvec)
187214797e23SKOSAKI Motohiro {
187374e3f3c3SMinchan Kim 	/*
187474e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
187574e3f3c3SMinchan Kim 	 * is pointless.
187674e3f3c3SMinchan Kim 	 */
187774e3f3c3SMinchan Kim 	if (!total_swap_pages)
187874e3f3c3SMinchan Kim 		return 0;
187974e3f3c3SMinchan Kim 
1880c3c787e8SHugh Dickins 	if (!mem_cgroup_disabled())
1881c56d5c7dSKonstantin Khlebnikov 		return mem_cgroup_inactive_anon_is_low(lruvec);
1882f16015fbSJohannes Weiner 
1883c56d5c7dSKonstantin Khlebnikov 	return inactive_anon_is_low_global(lruvec_zone(lruvec));
188414797e23SKOSAKI Motohiro }
188574e3f3c3SMinchan Kim #else
1886c56d5c7dSKonstantin Khlebnikov static inline int inactive_anon_is_low(struct lruvec *lruvec)
188774e3f3c3SMinchan Kim {
188874e3f3c3SMinchan Kim 	return 0;
188974e3f3c3SMinchan Kim }
189074e3f3c3SMinchan Kim #endif
189114797e23SKOSAKI Motohiro 
189256e49d21SRik van Riel /**
189356e49d21SRik van Riel  * inactive_file_is_low - check if file pages need to be deactivated
1894c56d5c7dSKonstantin Khlebnikov  * @lruvec: LRU vector to check
189556e49d21SRik van Riel  *
189656e49d21SRik van Riel  * When the system is doing streaming IO, memory pressure here
189756e49d21SRik van Riel  * ensures that active file pages get deactivated, until more
189856e49d21SRik van Riel  * than half of the file pages are on the inactive list.
189956e49d21SRik van Riel  *
190056e49d21SRik van Riel  * Once we get to that situation, protect the system's working
190156e49d21SRik van Riel  * set from being evicted by disabling active file page aging.
190256e49d21SRik van Riel  *
190356e49d21SRik van Riel  * This uses a different ratio than the anonymous pages, because
190456e49d21SRik van Riel  * the page cache uses a use-once replacement algorithm.
190556e49d21SRik van Riel  */
1906c56d5c7dSKonstantin Khlebnikov static int inactive_file_is_low(struct lruvec *lruvec)
190756e49d21SRik van Riel {
1908e3790144SJohannes Weiner 	unsigned long inactive;
1909e3790144SJohannes Weiner 	unsigned long active;
191056e49d21SRik van Riel 
1911e3790144SJohannes Weiner 	inactive = get_lru_size(lruvec, LRU_INACTIVE_FILE);
1912e3790144SJohannes Weiner 	active = get_lru_size(lruvec, LRU_ACTIVE_FILE);
1913e3790144SJohannes Weiner 
1914e3790144SJohannes Weiner 	return active > inactive;
191556e49d21SRik van Riel }
191656e49d21SRik van Riel 
191775b00af7SHugh Dickins static int inactive_list_is_low(struct lruvec *lruvec, enum lru_list lru)
1918b39415b2SRik van Riel {
191975b00af7SHugh Dickins 	if (is_file_lru(lru))
1920c56d5c7dSKonstantin Khlebnikov 		return inactive_file_is_low(lruvec);
1921b39415b2SRik van Riel 	else
1922c56d5c7dSKonstantin Khlebnikov 		return inactive_anon_is_low(lruvec);
1923b39415b2SRik van Riel }
1924b39415b2SRik van Riel 
19254f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
19261a93be0eSKonstantin Khlebnikov 				 struct lruvec *lruvec, struct scan_control *sc)
1927b69408e8SChristoph Lameter {
1928b39415b2SRik van Riel 	if (is_active_lru(lru)) {
192975b00af7SHugh Dickins 		if (inactive_list_is_low(lruvec, lru))
19301a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
1931556adecbSRik van Riel 		return 0;
1932556adecbSRik van Riel 	}
1933556adecbSRik van Riel 
19341a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
1935b69408e8SChristoph Lameter }
1936b69408e8SChristoph Lameter 
19379a265114SJohannes Weiner enum scan_balance {
19389a265114SJohannes Weiner 	SCAN_EQUAL,
19399a265114SJohannes Weiner 	SCAN_FRACT,
19409a265114SJohannes Weiner 	SCAN_ANON,
19419a265114SJohannes Weiner 	SCAN_FILE,
19429a265114SJohannes Weiner };
19439a265114SJohannes Weiner 
19441da177e4SLinus Torvalds /*
19454f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
19464f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
19474f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
19484f98a2feSRik van Riel  * onto the active list instead of evict.
19494f98a2feSRik van Riel  *
1950be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
1951be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
19524f98a2feSRik van Riel  */
195302695175SJohannes Weiner static void get_scan_count(struct lruvec *lruvec, int swappiness,
19546b4f7799SJohannes Weiner 			   struct scan_control *sc, unsigned long *nr,
19556b4f7799SJohannes Weiner 			   unsigned long *lru_pages)
19564f98a2feSRik van Riel {
195790126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
19589a265114SJohannes Weiner 	u64 fraction[2];
19599a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
196090126375SKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
19619a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
19629a265114SJohannes Weiner 	enum scan_balance scan_balance;
19630bf1457fSJohannes Weiner 	unsigned long anon, file;
19649a265114SJohannes Weiner 	bool force_scan = false;
19659a265114SJohannes Weiner 	unsigned long ap, fp;
19669a265114SJohannes Weiner 	enum lru_list lru;
19676f04f48dSSuleiman Souhlal 	bool some_scanned;
19686f04f48dSSuleiman Souhlal 	int pass;
1969246e87a9SKAMEZAWA Hiroyuki 
1970f11c0ca5SJohannes Weiner 	/*
1971f11c0ca5SJohannes Weiner 	 * If the zone or memcg is small, nr[l] can be 0.  This
1972f11c0ca5SJohannes Weiner 	 * results in no scanning on this priority and a potential
1973f11c0ca5SJohannes Weiner 	 * priority drop.  Global direct reclaim can go to the next
1974f11c0ca5SJohannes Weiner 	 * zone and tends to have no problems. Global kswapd is for
1975f11c0ca5SJohannes Weiner 	 * zone balancing and it needs to scan a minimum amount. When
1976f11c0ca5SJohannes Weiner 	 * reclaiming for a memcg, a priority drop can cause high
1977f11c0ca5SJohannes Weiner 	 * latencies, so it's better to scan a minimum amount there as
1978f11c0ca5SJohannes Weiner 	 * well.
1979f11c0ca5SJohannes Weiner 	 */
198090cbc250SVladimir Davydov 	if (current_is_kswapd()) {
198190cbc250SVladimir Davydov 		if (!zone_reclaimable(zone))
1982a4d3e9e7SJohannes Weiner 			force_scan = true;
198390cbc250SVladimir Davydov 		if (!mem_cgroup_lruvec_online(lruvec))
198490cbc250SVladimir Davydov 			force_scan = true;
198590cbc250SVladimir Davydov 	}
198689b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
1987a4d3e9e7SJohannes Weiner 		force_scan = true;
198876a33fc3SShaohua Li 
198976a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
1990ec8acf20SShaohua Li 	if (!sc->may_swap || (get_nr_swap_pages() <= 0)) {
19919a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
199276a33fc3SShaohua Li 		goto out;
199376a33fc3SShaohua Li 	}
19944f98a2feSRik van Riel 
199510316b31SJohannes Weiner 	/*
199610316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
199710316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
199810316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
199910316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
200010316b31SJohannes Weiner 	 * too expensive.
200110316b31SJohannes Weiner 	 */
200202695175SJohannes Weiner 	if (!global_reclaim(sc) && !swappiness) {
20039a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
200410316b31SJohannes Weiner 		goto out;
200510316b31SJohannes Weiner 	}
200610316b31SJohannes Weiner 
200710316b31SJohannes Weiner 	/*
200810316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
200910316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
201010316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
201110316b31SJohannes Weiner 	 */
201202695175SJohannes Weiner 	if (!sc->priority && swappiness) {
20139a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
201410316b31SJohannes Weiner 		goto out;
201510316b31SJohannes Weiner 	}
201610316b31SJohannes Weiner 
201711d16c25SJohannes Weiner 	/*
201862376251SJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
201962376251SJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
202062376251SJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
202162376251SJohannes Weiner 	 * shrinks, so does the window for rotation from references.
202262376251SJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
202362376251SJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
202462376251SJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
202562376251SJohannes Weiner 	 */
202662376251SJohannes Weiner 	if (global_reclaim(sc)) {
20272ab051e1SJerome Marchand 		unsigned long zonefile;
20282ab051e1SJerome Marchand 		unsigned long zonefree;
202962376251SJohannes Weiner 
20302ab051e1SJerome Marchand 		zonefree = zone_page_state(zone, NR_FREE_PAGES);
20312ab051e1SJerome Marchand 		zonefile = zone_page_state(zone, NR_ACTIVE_FILE) +
20322ab051e1SJerome Marchand 			   zone_page_state(zone, NR_INACTIVE_FILE);
20332ab051e1SJerome Marchand 
20342ab051e1SJerome Marchand 		if (unlikely(zonefile + zonefree <= high_wmark_pages(zone))) {
203562376251SJohannes Weiner 			scan_balance = SCAN_ANON;
203662376251SJohannes Weiner 			goto out;
203762376251SJohannes Weiner 		}
203862376251SJohannes Weiner 	}
203962376251SJohannes Weiner 
204062376251SJohannes Weiner 	/*
20417c5bd705SJohannes Weiner 	 * There is enough inactive page cache, do not reclaim
20427c5bd705SJohannes Weiner 	 * anything from the anonymous working set right now.
2043e9868505SRik van Riel 	 */
20447c5bd705SJohannes Weiner 	if (!inactive_file_is_low(lruvec)) {
20459a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2046e9868505SRik van Riel 		goto out;
20474f98a2feSRik van Riel 	}
20484f98a2feSRik van Riel 
20499a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
20509a265114SJohannes Weiner 
20514f98a2feSRik van Riel 	/*
205258c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
205358c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
205458c37f6eSKOSAKI Motohiro 	 */
205502695175SJohannes Weiner 	anon_prio = swappiness;
205675b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
205758c37f6eSKOSAKI Motohiro 
205858c37f6eSKOSAKI Motohiro 	/*
20594f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
20604f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
20614f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
20624f98a2feSRik van Riel 	 *
20634f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
20644f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
20654f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
20664f98a2feSRik van Riel 	 *
20674f98a2feSRik van Riel 	 * anon in [0], file in [1]
20684f98a2feSRik van Riel 	 */
20692ab051e1SJerome Marchand 
20702ab051e1SJerome Marchand 	anon  = get_lru_size(lruvec, LRU_ACTIVE_ANON) +
20712ab051e1SJerome Marchand 		get_lru_size(lruvec, LRU_INACTIVE_ANON);
20722ab051e1SJerome Marchand 	file  = get_lru_size(lruvec, LRU_ACTIVE_FILE) +
20732ab051e1SJerome Marchand 		get_lru_size(lruvec, LRU_INACTIVE_FILE);
20742ab051e1SJerome Marchand 
207590126375SKonstantin Khlebnikov 	spin_lock_irq(&zone->lru_lock);
207658c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
20776e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
20786e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
20794f98a2feSRik van Riel 	}
20804f98a2feSRik van Riel 
20816e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
20826e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
20836e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
20844f98a2feSRik van Riel 	}
20854f98a2feSRik van Riel 
20864f98a2feSRik van Riel 	/*
208700d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
208800d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
208900d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
20904f98a2feSRik van Riel 	 */
2091fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
20926e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
20934f98a2feSRik van Riel 
2094fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
20956e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
209690126375SKonstantin Khlebnikov 	spin_unlock_irq(&zone->lru_lock);
20974f98a2feSRik van Riel 
209876a33fc3SShaohua Li 	fraction[0] = ap;
209976a33fc3SShaohua Li 	fraction[1] = fp;
210076a33fc3SShaohua Li 	denominator = ap + fp + 1;
210176a33fc3SShaohua Li out:
21026f04f48dSSuleiman Souhlal 	some_scanned = false;
21036f04f48dSSuleiman Souhlal 	/* Only use force_scan on second pass. */
21046f04f48dSSuleiman Souhlal 	for (pass = 0; !some_scanned && pass < 2; pass++) {
21056b4f7799SJohannes Weiner 		*lru_pages = 0;
21064111304dSHugh Dickins 		for_each_evictable_lru(lru) {
21074111304dSHugh Dickins 			int file = is_file_lru(lru);
2108d778df51SJohannes Weiner 			unsigned long size;
210976a33fc3SShaohua Li 			unsigned long scan;
211076a33fc3SShaohua Li 
2111d778df51SJohannes Weiner 			size = get_lru_size(lruvec, lru);
2112d778df51SJohannes Weiner 			scan = size >> sc->priority;
21139a265114SJohannes Weiner 
21146f04f48dSSuleiman Souhlal 			if (!scan && pass && force_scan)
2115d778df51SJohannes Weiner 				scan = min(size, SWAP_CLUSTER_MAX);
21169a265114SJohannes Weiner 
21179a265114SJohannes Weiner 			switch (scan_balance) {
21189a265114SJohannes Weiner 			case SCAN_EQUAL:
21199a265114SJohannes Weiner 				/* Scan lists relative to size */
21209a265114SJohannes Weiner 				break;
21219a265114SJohannes Weiner 			case SCAN_FRACT:
21229a265114SJohannes Weiner 				/*
21239a265114SJohannes Weiner 				 * Scan types proportional to swappiness and
21249a265114SJohannes Weiner 				 * their relative recent reclaim efficiency.
21259a265114SJohannes Weiner 				 */
21266f04f48dSSuleiman Souhlal 				scan = div64_u64(scan * fraction[file],
21276f04f48dSSuleiman Souhlal 							denominator);
21289a265114SJohannes Weiner 				break;
21299a265114SJohannes Weiner 			case SCAN_FILE:
21309a265114SJohannes Weiner 			case SCAN_ANON:
21319a265114SJohannes Weiner 				/* Scan one type exclusively */
21326b4f7799SJohannes Weiner 				if ((scan_balance == SCAN_FILE) != file) {
21336b4f7799SJohannes Weiner 					size = 0;
21349a265114SJohannes Weiner 					scan = 0;
21356b4f7799SJohannes Weiner 				}
21369a265114SJohannes Weiner 				break;
21379a265114SJohannes Weiner 			default:
21389a265114SJohannes Weiner 				/* Look ma, no brain */
21399a265114SJohannes Weiner 				BUG();
21409a265114SJohannes Weiner 			}
21416b4f7799SJohannes Weiner 
21426b4f7799SJohannes Weiner 			*lru_pages += size;
21434111304dSHugh Dickins 			nr[lru] = scan;
21446b4f7799SJohannes Weiner 
21456f04f48dSSuleiman Souhlal 			/*
21466f04f48dSSuleiman Souhlal 			 * Skip the second pass and don't force_scan,
21476f04f48dSSuleiman Souhlal 			 * if we found something to scan.
21486f04f48dSSuleiman Souhlal 			 */
21496f04f48dSSuleiman Souhlal 			some_scanned |= !!scan;
21506f04f48dSSuleiman Souhlal 		}
215176a33fc3SShaohua Li 	}
21526e08a369SWu Fengguang }
21534f98a2feSRik van Riel 
21549b4f98cdSJohannes Weiner /*
21559b4f98cdSJohannes Weiner  * This is a basic per-zone page freer.  Used by both kswapd and direct reclaim.
21569b4f98cdSJohannes Weiner  */
215702695175SJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, int swappiness,
21586b4f7799SJohannes Weiner 			  struct scan_control *sc, unsigned long *lru_pages)
21599b4f98cdSJohannes Weiner {
21609b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2161e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
21629b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
21639b4f98cdSJohannes Weiner 	enum lru_list lru;
21649b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
21659b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
21669b4f98cdSJohannes Weiner 	struct blk_plug plug;
21671a501907SMel Gorman 	bool scan_adjusted;
21689b4f98cdSJohannes Weiner 
21696b4f7799SJohannes Weiner 	get_scan_count(lruvec, swappiness, sc, nr, lru_pages);
21709b4f98cdSJohannes Weiner 
2171e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2172e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2173e82e0561SMel Gorman 
21741a501907SMel Gorman 	/*
21751a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
21761a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
21771a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
21781a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
21791a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
21801a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
21811a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
21821a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
21831a501907SMel Gorman 	 * dropped to zero at the first pass.
21841a501907SMel Gorman 	 */
21851a501907SMel Gorman 	scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
21861a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
21871a501907SMel Gorman 
21889b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
21899b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
21909b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2191e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2192e82e0561SMel Gorman 		unsigned long nr_scanned;
2193e82e0561SMel Gorman 
21949b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
21959b4f98cdSJohannes Weiner 			if (nr[lru]) {
21969b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
21979b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
21989b4f98cdSJohannes Weiner 
21999b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
22009b4f98cdSJohannes Weiner 							    lruvec, sc);
22019b4f98cdSJohannes Weiner 			}
22029b4f98cdSJohannes Weiner 		}
2203e82e0561SMel Gorman 
2204e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2205e82e0561SMel Gorman 			continue;
2206e82e0561SMel Gorman 
22079b4f98cdSJohannes Weiner 		/*
2208e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
22091a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2210e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2211e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2212e82e0561SMel Gorman 		 * proportional to the original scan target.
2213e82e0561SMel Gorman 		 */
2214e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2215e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2216e82e0561SMel Gorman 
22171a501907SMel Gorman 		/*
22181a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
22191a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
22201a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
22211a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
22221a501907SMel Gorman 		 */
22231a501907SMel Gorman 		if (!nr_file || !nr_anon)
22241a501907SMel Gorman 			break;
22251a501907SMel Gorman 
2226e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2227e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2228e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2229e82e0561SMel Gorman 			lru = LRU_BASE;
2230e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2231e82e0561SMel Gorman 		} else {
2232e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2233e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2234e82e0561SMel Gorman 			lru = LRU_FILE;
2235e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2236e82e0561SMel Gorman 		}
2237e82e0561SMel Gorman 
2238e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2239e82e0561SMel Gorman 		nr[lru] = 0;
2240e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2241e82e0561SMel Gorman 
2242e82e0561SMel Gorman 		/*
2243e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2244e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2245e82e0561SMel Gorman 		 */
2246e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2247e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2248e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2249e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2250e82e0561SMel Gorman 
2251e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2252e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2253e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2254e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2255e82e0561SMel Gorman 
2256e82e0561SMel Gorman 		scan_adjusted = true;
22579b4f98cdSJohannes Weiner 	}
22589b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
22599b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
22609b4f98cdSJohannes Weiner 
22619b4f98cdSJohannes Weiner 	/*
22629b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
22639b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
22649b4f98cdSJohannes Weiner 	 */
22659b4f98cdSJohannes Weiner 	if (inactive_anon_is_low(lruvec))
22669b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
22679b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
22689b4f98cdSJohannes Weiner 
22699b4f98cdSJohannes Weiner 	throttle_vm_writeout(sc->gfp_mask);
22709b4f98cdSJohannes Weiner }
22719b4f98cdSJohannes Weiner 
227223b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
22739e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
227423b9da55SMel Gorman {
2275d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
227623b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
22779e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
227823b9da55SMel Gorman 		return true;
227923b9da55SMel Gorman 
228023b9da55SMel Gorman 	return false;
228123b9da55SMel Gorman }
228223b9da55SMel Gorman 
22834f98a2feSRik van Riel /*
228423b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
228523b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
228623b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
228723b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
228823b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
22893e7d3449SMel Gorman  */
22909b4f98cdSJohannes Weiner static inline bool should_continue_reclaim(struct zone *zone,
22913e7d3449SMel Gorman 					unsigned long nr_reclaimed,
22923e7d3449SMel Gorman 					unsigned long nr_scanned,
22933e7d3449SMel Gorman 					struct scan_control *sc)
22943e7d3449SMel Gorman {
22953e7d3449SMel Gorman 	unsigned long pages_for_compaction;
22963e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
22973e7d3449SMel Gorman 
22983e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
22999e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
23003e7d3449SMel Gorman 		return false;
23013e7d3449SMel Gorman 
23022876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
23032876592fSMel Gorman 	if (sc->gfp_mask & __GFP_REPEAT) {
23043e7d3449SMel Gorman 		/*
23052876592fSMel Gorman 		 * For __GFP_REPEAT allocations, stop reclaiming if the
23062876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
23072876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
23082876592fSMel Gorman 		 * expensive but a __GFP_REPEAT caller really wants to succeed
23093e7d3449SMel Gorman 		 */
23103e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
23113e7d3449SMel Gorman 			return false;
23122876592fSMel Gorman 	} else {
23132876592fSMel Gorman 		/*
23142876592fSMel Gorman 		 * For non-__GFP_REPEAT allocations which can presumably
23152876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
23162876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
23172876592fSMel Gorman 		 * pages that were scanned. This will return to the
23182876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
23192876592fSMel Gorman 		 * the resulting allocation attempt fails
23202876592fSMel Gorman 		 */
23212876592fSMel Gorman 		if (!nr_reclaimed)
23222876592fSMel Gorman 			return false;
23232876592fSMel Gorman 	}
23243e7d3449SMel Gorman 
23253e7d3449SMel Gorman 	/*
23263e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
23273e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
23283e7d3449SMel Gorman 	 */
23293e7d3449SMel Gorman 	pages_for_compaction = (2UL << sc->order);
23309b4f98cdSJohannes Weiner 	inactive_lru_pages = zone_page_state(zone, NR_INACTIVE_FILE);
2331ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
23329b4f98cdSJohannes Weiner 		inactive_lru_pages += zone_page_state(zone, NR_INACTIVE_ANON);
23333e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
23343e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
23353e7d3449SMel Gorman 		return true;
23363e7d3449SMel Gorman 
23373e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2338ebff3980SVlastimil Babka 	switch (compaction_suitable(zone, sc->order, 0, 0)) {
23393e7d3449SMel Gorman 	case COMPACT_PARTIAL:
23403e7d3449SMel Gorman 	case COMPACT_CONTINUE:
23413e7d3449SMel Gorman 		return false;
23423e7d3449SMel Gorman 	default:
23433e7d3449SMel Gorman 		return true;
23443e7d3449SMel Gorman 	}
23453e7d3449SMel Gorman }
23463e7d3449SMel Gorman 
23476b4f7799SJohannes Weiner static bool shrink_zone(struct zone *zone, struct scan_control *sc,
23486b4f7799SJohannes Weiner 			bool is_classzone)
2349f16015fbSJohannes Weiner {
2350cb731d6cSVladimir Davydov 	struct reclaim_state *reclaim_state = current->reclaim_state;
23519b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
23522344d7e4SJohannes Weiner 	bool reclaimable = false;
23539b4f98cdSJohannes Weiner 
23549b4f98cdSJohannes Weiner 	do {
23555660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
23565660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
23575660048cSJohannes Weiner 			.zone = zone,
23589e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
23595660048cSJohannes Weiner 		};
23606b4f7799SJohannes Weiner 		unsigned long zone_lru_pages = 0;
2361694fbc0fSAndrew Morton 		struct mem_cgroup *memcg;
23625660048cSJohannes Weiner 
23639b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
23649b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
23659b4f98cdSJohannes Weiner 
2366694fbc0fSAndrew Morton 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
2367694fbc0fSAndrew Morton 		do {
23686b4f7799SJohannes Weiner 			unsigned long lru_pages;
2369cb731d6cSVladimir Davydov 			unsigned long scanned;
23709b4f98cdSJohannes Weiner 			struct lruvec *lruvec;
237102695175SJohannes Weiner 			int swappiness;
23729b4f98cdSJohannes Weiner 
2373241994edSJohannes Weiner 			if (mem_cgroup_low(root, memcg)) {
2374241994edSJohannes Weiner 				if (!sc->may_thrash)
2375241994edSJohannes Weiner 					continue;
2376241994edSJohannes Weiner 				mem_cgroup_events(memcg, MEMCG_LOW, 1);
2377241994edSJohannes Weiner 			}
2378241994edSJohannes Weiner 
23799b4f98cdSJohannes Weiner 			lruvec = mem_cgroup_zone_lruvec(zone, memcg);
238002695175SJohannes Weiner 			swappiness = mem_cgroup_swappiness(memcg);
2381cb731d6cSVladimir Davydov 			scanned = sc->nr_scanned;
23825660048cSJohannes Weiner 
23836b4f7799SJohannes Weiner 			shrink_lruvec(lruvec, swappiness, sc, &lru_pages);
23846b4f7799SJohannes Weiner 			zone_lru_pages += lru_pages;
2385f9be23d6SKonstantin Khlebnikov 
2386cb731d6cSVladimir Davydov 			if (memcg && is_classzone)
2387cb731d6cSVladimir Davydov 				shrink_slab(sc->gfp_mask, zone_to_nid(zone),
2388cb731d6cSVladimir Davydov 					    memcg, sc->nr_scanned - scanned,
2389cb731d6cSVladimir Davydov 					    lru_pages);
2390cb731d6cSVladimir Davydov 
23915660048cSJohannes Weiner 			/*
2392a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2393a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
23949b4f98cdSJohannes Weiner 			 * zone.
2395a394cb8eSMichal Hocko 			 *
2396a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2397a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2398a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2399a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
24005660048cSJohannes Weiner 			 */
2401a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2402a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
24035660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
24045660048cSJohannes Weiner 				break;
24055660048cSJohannes Weiner 			}
2406241994edSJohannes Weiner 		} while ((memcg = mem_cgroup_iter(root, memcg, &reclaim)));
240770ddf637SAnton Vorontsov 
24086b4f7799SJohannes Weiner 		/*
24096b4f7799SJohannes Weiner 		 * Shrink the slab caches in the same proportion that
24106b4f7799SJohannes Weiner 		 * the eligible LRU pages were scanned.
24116b4f7799SJohannes Weiner 		 */
2412cb731d6cSVladimir Davydov 		if (global_reclaim(sc) && is_classzone)
2413cb731d6cSVladimir Davydov 			shrink_slab(sc->gfp_mask, zone_to_nid(zone), NULL,
24146b4f7799SJohannes Weiner 				    sc->nr_scanned - nr_scanned,
24156b4f7799SJohannes Weiner 				    zone_lru_pages);
24166b4f7799SJohannes Weiner 
24176b4f7799SJohannes Weiner 		if (reclaim_state) {
2418cb731d6cSVladimir Davydov 			sc->nr_reclaimed += reclaim_state->reclaimed_slab;
24196b4f7799SJohannes Weiner 			reclaim_state->reclaimed_slab = 0;
24206b4f7799SJohannes Weiner 		}
24216b4f7799SJohannes Weiner 
242270ddf637SAnton Vorontsov 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup,
242370ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
242470ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
242570ddf637SAnton Vorontsov 
24262344d7e4SJohannes Weiner 		if (sc->nr_reclaimed - nr_reclaimed)
24272344d7e4SJohannes Weiner 			reclaimable = true;
24282344d7e4SJohannes Weiner 
24299b4f98cdSJohannes Weiner 	} while (should_continue_reclaim(zone, sc->nr_reclaimed - nr_reclaimed,
24309b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
24312344d7e4SJohannes Weiner 
24322344d7e4SJohannes Weiner 	return reclaimable;
2433f16015fbSJohannes Weiner }
2434f16015fbSJohannes Weiner 
243553853e2dSVlastimil Babka /*
243653853e2dSVlastimil Babka  * Returns true if compaction should go ahead for a high-order request, or
243753853e2dSVlastimil Babka  * the high-order allocation would succeed without compaction.
243853853e2dSVlastimil Babka  */
24390b06496aSJohannes Weiner static inline bool compaction_ready(struct zone *zone, int order)
2440fe4b1b24SMel Gorman {
2441fe4b1b24SMel Gorman 	unsigned long balance_gap, watermark;
2442fe4b1b24SMel Gorman 	bool watermark_ok;
2443fe4b1b24SMel Gorman 
2444fe4b1b24SMel Gorman 	/*
2445fe4b1b24SMel Gorman 	 * Compaction takes time to run and there are potentially other
2446fe4b1b24SMel Gorman 	 * callers using the pages just freed. Continue reclaiming until
2447fe4b1b24SMel Gorman 	 * there is a buffer of free pages available to give compaction
2448fe4b1b24SMel Gorman 	 * a reasonable chance of completing and allocating the page
2449fe4b1b24SMel Gorman 	 */
24504be89a34SJianyu Zhan 	balance_gap = min(low_wmark_pages(zone), DIV_ROUND_UP(
24514be89a34SJianyu Zhan 			zone->managed_pages, KSWAPD_ZONE_BALANCE_GAP_RATIO));
24520b06496aSJohannes Weiner 	watermark = high_wmark_pages(zone) + balance_gap + (2UL << order);
2453fe4b1b24SMel Gorman 	watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, 0, 0);
2454fe4b1b24SMel Gorman 
2455fe4b1b24SMel Gorman 	/*
2456fe4b1b24SMel Gorman 	 * If compaction is deferred, reclaim up to a point where
2457fe4b1b24SMel Gorman 	 * compaction will have a chance of success when re-enabled
2458fe4b1b24SMel Gorman 	 */
24590b06496aSJohannes Weiner 	if (compaction_deferred(zone, order))
2460fe4b1b24SMel Gorman 		return watermark_ok;
2461fe4b1b24SMel Gorman 
246253853e2dSVlastimil Babka 	/*
246353853e2dSVlastimil Babka 	 * If compaction is not ready to start and allocation is not likely
246453853e2dSVlastimil Babka 	 * to succeed without it, then keep reclaiming.
246553853e2dSVlastimil Babka 	 */
2466ebff3980SVlastimil Babka 	if (compaction_suitable(zone, order, 0, 0) == COMPACT_SKIPPED)
2467fe4b1b24SMel Gorman 		return false;
2468fe4b1b24SMel Gorman 
2469fe4b1b24SMel Gorman 	return watermark_ok;
2470fe4b1b24SMel Gorman }
2471fe4b1b24SMel Gorman 
24721da177e4SLinus Torvalds /*
24731da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
24741da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
24751da177e4SLinus Torvalds  * request.
24761da177e4SLinus Torvalds  *
247741858966SMel Gorman  * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
247841858966SMel Gorman  * Because:
24791da177e4SLinus Torvalds  * a) The caller may be trying to free *extra* pages to satisfy a higher-order
24801da177e4SLinus Torvalds  *    allocation or
248141858966SMel Gorman  * b) The target zone may be at high_wmark_pages(zone) but the lower zones
248241858966SMel Gorman  *    must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
248341858966SMel Gorman  *    zone defense algorithm.
24841da177e4SLinus Torvalds  *
24851da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
24861da177e4SLinus Torvalds  * scan then give up on it.
24872344d7e4SJohannes Weiner  *
24882344d7e4SJohannes Weiner  * Returns true if a zone was reclaimable.
24891da177e4SLinus Torvalds  */
24902344d7e4SJohannes Weiner static bool shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
24911da177e4SLinus Torvalds {
2492dd1a239fSMel Gorman 	struct zoneref *z;
249354a6eb5cSMel Gorman 	struct zone *zone;
24940608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
24950608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2496619d0d76SWeijie Yang 	gfp_t orig_mask;
24979bbc04eeSWeijie Yang 	enum zone_type requested_highidx = gfp_zone(sc->gfp_mask);
24982344d7e4SJohannes Weiner 	bool reclaimable = false;
24991cfb419bSKAMEZAWA Hiroyuki 
2500cc715d99SMel Gorman 	/*
2501cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2502cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2503cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2504cc715d99SMel Gorman 	 */
2505619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2506cc715d99SMel Gorman 	if (buffer_heads_over_limit)
2507cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
2508cc715d99SMel Gorman 
2509d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
25106b4f7799SJohannes Weiner 					requested_highidx, sc->nodemask) {
25116b4f7799SJohannes Weiner 		enum zone_type classzone_idx;
25126b4f7799SJohannes Weiner 
2513f3fe6512SCon Kolivas 		if (!populated_zone(zone))
25141da177e4SLinus Torvalds 			continue;
25156b4f7799SJohannes Weiner 
25166b4f7799SJohannes Weiner 		classzone_idx = requested_highidx;
25176b4f7799SJohannes Weiner 		while (!populated_zone(zone->zone_pgdat->node_zones +
25186b4f7799SJohannes Weiner 							classzone_idx))
25196b4f7799SJohannes Weiner 			classzone_idx--;
25206b4f7799SJohannes Weiner 
25211cfb419bSKAMEZAWA Hiroyuki 		/*
25221cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
25231cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
25241cfb419bSKAMEZAWA Hiroyuki 		 */
252589b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2526344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2527344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
25281da177e4SLinus Torvalds 				continue;
252965ec02cbSVladimir Davydov 
25306e543d57SLisa Du 			if (sc->priority != DEF_PRIORITY &&
25316e543d57SLisa Du 			    !zone_reclaimable(zone))
25321da177e4SLinus Torvalds 				continue;	/* Let kswapd poll it */
25330b06496aSJohannes Weiner 
2534e0887c19SRik van Riel 			/*
2535e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2536e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2537e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2538e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2539e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2540c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2541c7cfa37bSCopot Alexandru 			 * page allocations.
2542e0887c19SRik van Riel 			 */
25430b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
25440b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
25450b06496aSJohannes Weiner 			    zonelist_zone_idx(z) <= requested_highidx &&
25460b06496aSJohannes Weiner 			    compaction_ready(zone, sc->order)) {
25470b06496aSJohannes Weiner 				sc->compaction_ready = true;
2548e0887c19SRik van Riel 				continue;
2549e0887c19SRik van Riel 			}
25500b06496aSJohannes Weiner 
25510608f43dSAndrew Morton 			/*
25520608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
25530608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
25540608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
25550608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
25560608f43dSAndrew Morton 			 */
25570608f43dSAndrew Morton 			nr_soft_scanned = 0;
25580608f43dSAndrew Morton 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
25590608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
25600608f43dSAndrew Morton 						&nr_soft_scanned);
25610608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
25620608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
25632344d7e4SJohannes Weiner 			if (nr_soft_reclaimed)
25642344d7e4SJohannes Weiner 				reclaimable = true;
2565ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2566ac34a1a3SKAMEZAWA Hiroyuki 		}
2567d149e3b2SYing Han 
25686b4f7799SJohannes Weiner 		if (shrink_zone(zone, sc, zone_idx(zone) == classzone_idx))
25692344d7e4SJohannes Weiner 			reclaimable = true;
25702344d7e4SJohannes Weiner 
25712344d7e4SJohannes Weiner 		if (global_reclaim(sc) &&
25722344d7e4SJohannes Weiner 		    !reclaimable && zone_reclaimable(zone))
25732344d7e4SJohannes Weiner 			reclaimable = true;
25741da177e4SLinus Torvalds 	}
2575e0c23279SMel Gorman 
257665ec02cbSVladimir Davydov 	/*
2577619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2578619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
2579619d0d76SWeijie Yang 	 */
2580619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
2581d1908362SMinchan Kim 
25822344d7e4SJohannes Weiner 	return reclaimable;
25831da177e4SLinus Torvalds }
25841da177e4SLinus Torvalds 
25851da177e4SLinus Torvalds /*
25861da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
25871da177e4SLinus Torvalds  *
25881da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
25891da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
25901da177e4SLinus Torvalds  *
25911da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
25921da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
25935b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
25945b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
25955b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
25965b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2597a41f24eaSNishanth Aravamudan  *
2598a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2599a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
26001da177e4SLinus Torvalds  */
2601dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
26023115cd91SVladimir Davydov 					  struct scan_control *sc)
26031da177e4SLinus Torvalds {
2604241994edSJohannes Weiner 	int initial_priority = sc->priority;
260569e05944SAndrew Morton 	unsigned long total_scanned = 0;
260622fba335SKOSAKI Motohiro 	unsigned long writeback_threshold;
26072344d7e4SJohannes Weiner 	bool zones_reclaimable;
2608241994edSJohannes Weiner retry:
2609873b4771SKeika Kobayashi 	delayacct_freepages_start();
2610873b4771SKeika Kobayashi 
261189b5fae5SJohannes Weiner 	if (global_reclaim(sc))
2612f8891e5eSChristoph Lameter 		count_vm_event(ALLOCSTALL);
26131da177e4SLinus Torvalds 
26149e3b2f8cSKonstantin Khlebnikov 	do {
261570ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
261670ddf637SAnton Vorontsov 				sc->priority);
261766e1707bSBalbir Singh 		sc->nr_scanned = 0;
26182344d7e4SJohannes Weiner 		zones_reclaimable = shrink_zones(zonelist, sc);
2619e0c23279SMel Gorman 
262066e1707bSBalbir Singh 		total_scanned += sc->nr_scanned;
2621bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
26220b06496aSJohannes Weiner 			break;
26230b06496aSJohannes Weiner 
26240b06496aSJohannes Weiner 		if (sc->compaction_ready)
26250b06496aSJohannes Weiner 			break;
26261da177e4SLinus Torvalds 
26271da177e4SLinus Torvalds 		/*
26280e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
26290e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
26300e50ce3bSMinchan Kim 		 */
26310e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
26320e50ce3bSMinchan Kim 			sc->may_writepage = 1;
26330e50ce3bSMinchan Kim 
26340e50ce3bSMinchan Kim 		/*
26351da177e4SLinus Torvalds 		 * Try to write back as many pages as we just scanned.  This
26361da177e4SLinus Torvalds 		 * tends to cause slow streaming writers to write data to the
26371da177e4SLinus Torvalds 		 * disk smoothly, at the dirtying rate, which is nice.   But
26381da177e4SLinus Torvalds 		 * that's undesirable in laptop mode, where we *want* lumpy
26391da177e4SLinus Torvalds 		 * writeout.  So in laptop mode, write out the whole world.
26401da177e4SLinus Torvalds 		 */
264122fba335SKOSAKI Motohiro 		writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
264222fba335SKOSAKI Motohiro 		if (total_scanned > writeback_threshold) {
26430e175a18SCurt Wohlgemuth 			wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
26440e175a18SCurt Wohlgemuth 						WB_REASON_TRY_TO_FREE_PAGES);
264566e1707bSBalbir Singh 			sc->may_writepage = 1;
26461da177e4SLinus Torvalds 		}
26470b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
2648bb21c7ceSKOSAKI Motohiro 
2649873b4771SKeika Kobayashi 	delayacct_freepages_end();
2650873b4771SKeika Kobayashi 
2651bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2652bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2653bb21c7ceSKOSAKI Motohiro 
26540cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
26550b06496aSJohannes Weiner 	if (sc->compaction_ready)
26567335084dSMel Gorman 		return 1;
26577335084dSMel Gorman 
2658241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
2659241994edSJohannes Weiner 	if (!sc->may_thrash) {
2660241994edSJohannes Weiner 		sc->priority = initial_priority;
2661241994edSJohannes Weiner 		sc->may_thrash = 1;
2662241994edSJohannes Weiner 		goto retry;
2663241994edSJohannes Weiner 	}
2664241994edSJohannes Weiner 
26652344d7e4SJohannes Weiner 	/* Any of the zones still reclaimable?  Don't OOM. */
26662344d7e4SJohannes Weiner 	if (zones_reclaimable)
2667bb21c7ceSKOSAKI Motohiro 		return 1;
2668bb21c7ceSKOSAKI Motohiro 
2669bb21c7ceSKOSAKI Motohiro 	return 0;
26701da177e4SLinus Torvalds }
26711da177e4SLinus Torvalds 
26725515061dSMel Gorman static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
26735515061dSMel Gorman {
26745515061dSMel Gorman 	struct zone *zone;
26755515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
26765515061dSMel Gorman 	unsigned long free_pages = 0;
26775515061dSMel Gorman 	int i;
26785515061dSMel Gorman 	bool wmark_ok;
26795515061dSMel Gorman 
26805515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
26815515061dSMel Gorman 		zone = &pgdat->node_zones[i];
2682f012a84aSNishanth Aravamudan 		if (!populated_zone(zone) ||
2683f012a84aSNishanth Aravamudan 		    zone_reclaimable_pages(zone) == 0)
2684675becceSMel Gorman 			continue;
2685675becceSMel Gorman 
26865515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
26875515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
26885515061dSMel Gorman 	}
26895515061dSMel Gorman 
2690675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
2691675becceSMel Gorman 	if (!pfmemalloc_reserve)
2692675becceSMel Gorman 		return true;
2693675becceSMel Gorman 
26945515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
26955515061dSMel Gorman 
26965515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
26975515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
26985515061dSMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx,
26995515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
27005515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
27015515061dSMel Gorman 	}
27025515061dSMel Gorman 
27035515061dSMel Gorman 	return wmark_ok;
27045515061dSMel Gorman }
27055515061dSMel Gorman 
27065515061dSMel Gorman /*
27075515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
27085515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
27095515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
271050694c28SMel Gorman  * when the low watermark is reached.
271150694c28SMel Gorman  *
271250694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
271350694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
27145515061dSMel Gorman  */
271550694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
27165515061dSMel Gorman 					nodemask_t *nodemask)
27175515061dSMel Gorman {
2718675becceSMel Gorman 	struct zoneref *z;
27195515061dSMel Gorman 	struct zone *zone;
2720675becceSMel Gorman 	pg_data_t *pgdat = NULL;
27215515061dSMel Gorman 
27225515061dSMel Gorman 	/*
27235515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
27245515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
27255515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
27265515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
27275515061dSMel Gorman 	 * processes to block on log_wait_commit().
27285515061dSMel Gorman 	 */
27295515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
273050694c28SMel Gorman 		goto out;
273150694c28SMel Gorman 
273250694c28SMel Gorman 	/*
273350694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
273450694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
273550694c28SMel Gorman 	 */
273650694c28SMel Gorman 	if (fatal_signal_pending(current))
273750694c28SMel Gorman 		goto out;
27385515061dSMel Gorman 
2739675becceSMel Gorman 	/*
2740675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
2741675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
2742675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
2743675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
2744675becceSMel Gorman 	 *
2745675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
2746675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
2747675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
2748675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
2749675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
2750675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
2751675becceSMel Gorman 	 * should make reasonable progress.
2752675becceSMel Gorman 	 */
2753675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
275417636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
2755675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
2756675becceSMel Gorman 			continue;
2757675becceSMel Gorman 
2758675becceSMel Gorman 		/* Throttle based on the first usable node */
27595515061dSMel Gorman 		pgdat = zone->zone_pgdat;
27605515061dSMel Gorman 		if (pfmemalloc_watermark_ok(pgdat))
276150694c28SMel Gorman 			goto out;
2762675becceSMel Gorman 		break;
2763675becceSMel Gorman 	}
2764675becceSMel Gorman 
2765675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
2766675becceSMel Gorman 	if (!pgdat)
2767675becceSMel Gorman 		goto out;
27685515061dSMel Gorman 
276968243e76SMel Gorman 	/* Account for the throttling */
277068243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
277168243e76SMel Gorman 
27725515061dSMel Gorman 	/*
27735515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
27745515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
27755515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
27765515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
27775515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
27785515061dSMel Gorman 	 * second before continuing.
27795515061dSMel Gorman 	 */
27805515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
27815515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
27825515061dSMel Gorman 			pfmemalloc_watermark_ok(pgdat), HZ);
278350694c28SMel Gorman 
278450694c28SMel Gorman 		goto check_pending;
27855515061dSMel Gorman 	}
27865515061dSMel Gorman 
27875515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
27885515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
27895515061dSMel Gorman 		pfmemalloc_watermark_ok(pgdat));
279050694c28SMel Gorman 
279150694c28SMel Gorman check_pending:
279250694c28SMel Gorman 	if (fatal_signal_pending(current))
279350694c28SMel Gorman 		return true;
279450694c28SMel Gorman 
279550694c28SMel Gorman out:
279650694c28SMel Gorman 	return false;
27975515061dSMel Gorman }
27985515061dSMel Gorman 
2799dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2800327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
280166e1707bSBalbir Singh {
280233906bc5SMel Gorman 	unsigned long nr_reclaimed;
280366e1707bSBalbir Singh 	struct scan_control sc = {
280422fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2805ee814fe2SJohannes Weiner 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
2806ee814fe2SJohannes Weiner 		.order = order,
2807ee814fe2SJohannes Weiner 		.nodemask = nodemask,
2808ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
2809ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
2810a6dc60f8SJohannes Weiner 		.may_unmap = 1,
28112e2e4259SKOSAKI Motohiro 		.may_swap = 1,
281266e1707bSBalbir Singh 	};
281366e1707bSBalbir Singh 
28145515061dSMel Gorman 	/*
281550694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
281650694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
281750694c28SMel Gorman 	 * point.
28185515061dSMel Gorman 	 */
281950694c28SMel Gorman 	if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
28205515061dSMel Gorman 		return 1;
28215515061dSMel Gorman 
282233906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
282333906bc5SMel Gorman 				sc.may_writepage,
282433906bc5SMel Gorman 				gfp_mask);
282533906bc5SMel Gorman 
28263115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
282733906bc5SMel Gorman 
282833906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
282933906bc5SMel Gorman 
283033906bc5SMel Gorman 	return nr_reclaimed;
283166e1707bSBalbir Singh }
283266e1707bSBalbir Singh 
2833c255a458SAndrew Morton #ifdef CONFIG_MEMCG
283466e1707bSBalbir Singh 
283572835c86SJohannes Weiner unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg,
28364e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
28370ae5e89cSYing Han 						struct zone *zone,
28380ae5e89cSYing Han 						unsigned long *nr_scanned)
28394e416953SBalbir Singh {
28404e416953SBalbir Singh 	struct scan_control sc = {
2841b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2842ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
28434e416953SBalbir Singh 		.may_writepage = !laptop_mode,
28444e416953SBalbir Singh 		.may_unmap = 1,
28454e416953SBalbir Singh 		.may_swap = !noswap,
28464e416953SBalbir Singh 	};
2847f9be23d6SKonstantin Khlebnikov 	struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
284802695175SJohannes Weiner 	int swappiness = mem_cgroup_swappiness(memcg);
28496b4f7799SJohannes Weiner 	unsigned long lru_pages;
28500ae5e89cSYing Han 
28514e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
28524e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2853bdce6d9eSKOSAKI Motohiro 
28549e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
2855bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
2856bdce6d9eSKOSAKI Motohiro 						      sc.gfp_mask);
2857bdce6d9eSKOSAKI Motohiro 
28584e416953SBalbir Singh 	/*
28594e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
28604e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
28614e416953SBalbir Singh 	 * if we don't reclaim here, the shrink_zone from balance_pgdat
28624e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
28634e416953SBalbir Singh 	 * the priority and make it zero.
28644e416953SBalbir Singh 	 */
28656b4f7799SJohannes Weiner 	shrink_lruvec(lruvec, swappiness, &sc, &lru_pages);
2866bdce6d9eSKOSAKI Motohiro 
2867bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
2868bdce6d9eSKOSAKI Motohiro 
28690ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
28704e416953SBalbir Singh 	return sc.nr_reclaimed;
28714e416953SBalbir Singh }
28724e416953SBalbir Singh 
287372835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
2874b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
28758c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
2876b70a2a21SJohannes Weiner 					   bool may_swap)
287766e1707bSBalbir Singh {
28784e416953SBalbir Singh 	struct zonelist *zonelist;
2879bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
2880889976dbSYing Han 	int nid;
288166e1707bSBalbir Singh 	struct scan_control sc = {
2882b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
2883ee814fe2SJohannes Weiner 		.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2884ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
2885ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
2886ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
288766e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
2888a6dc60f8SJohannes Weiner 		.may_unmap = 1,
2889b70a2a21SJohannes Weiner 		.may_swap = may_swap,
2890a09ed5e0SYing Han 	};
289166e1707bSBalbir Singh 
2892889976dbSYing Han 	/*
2893889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
2894889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
2895889976dbSYing Han 	 * scan does not need to be the current node.
2896889976dbSYing Han 	 */
289772835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
2898889976dbSYing Han 
2899889976dbSYing Han 	zonelist = NODE_DATA(nid)->node_zonelists;
2900bdce6d9eSKOSAKI Motohiro 
2901bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
2902bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
2903bdce6d9eSKOSAKI Motohiro 					    sc.gfp_mask);
2904bdce6d9eSKOSAKI Motohiro 
29053115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
2906bdce6d9eSKOSAKI Motohiro 
2907bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
2908bdce6d9eSKOSAKI Motohiro 
2909bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
291066e1707bSBalbir Singh }
291166e1707bSBalbir Singh #endif
291266e1707bSBalbir Singh 
29139e3b2f8cSKonstantin Khlebnikov static void age_active_anon(struct zone *zone, struct scan_control *sc)
2914f16015fbSJohannes Weiner {
2915b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
2916b95a2f2dSJohannes Weiner 
2917b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
2918b95a2f2dSJohannes Weiner 		return;
2919b95a2f2dSJohannes Weiner 
2920b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
2921b95a2f2dSJohannes Weiner 	do {
2922c56d5c7dSKonstantin Khlebnikov 		struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
2923f16015fbSJohannes Weiner 
2924c56d5c7dSKonstantin Khlebnikov 		if (inactive_anon_is_low(lruvec))
29251a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
29269e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
2927b95a2f2dSJohannes Weiner 
2928b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
2929b95a2f2dSJohannes Weiner 	} while (memcg);
2930f16015fbSJohannes Weiner }
2931f16015fbSJohannes Weiner 
293260cefed4SJohannes Weiner static bool zone_balanced(struct zone *zone, int order,
293360cefed4SJohannes Weiner 			  unsigned long balance_gap, int classzone_idx)
293460cefed4SJohannes Weiner {
293560cefed4SJohannes Weiner 	if (!zone_watermark_ok_safe(zone, order, high_wmark_pages(zone) +
293660cefed4SJohannes Weiner 				    balance_gap, classzone_idx, 0))
293760cefed4SJohannes Weiner 		return false;
293860cefed4SJohannes Weiner 
2939ebff3980SVlastimil Babka 	if (IS_ENABLED(CONFIG_COMPACTION) && order && compaction_suitable(zone,
2940ebff3980SVlastimil Babka 				order, 0, classzone_idx) == COMPACT_SKIPPED)
294160cefed4SJohannes Weiner 		return false;
294260cefed4SJohannes Weiner 
294360cefed4SJohannes Weiner 	return true;
294460cefed4SJohannes Weiner }
294560cefed4SJohannes Weiner 
29461741c877SMel Gorman /*
29474ae0a48bSZlatko Calusic  * pgdat_balanced() is used when checking if a node is balanced.
29484ae0a48bSZlatko Calusic  *
29494ae0a48bSZlatko Calusic  * For order-0, all zones must be balanced!
29504ae0a48bSZlatko Calusic  *
29514ae0a48bSZlatko Calusic  * For high-order allocations only zones that meet watermarks and are in a
29524ae0a48bSZlatko Calusic  * zone allowed by the callers classzone_idx are added to balanced_pages. The
29534ae0a48bSZlatko Calusic  * total of balanced pages must be at least 25% of the zones allowed by
29544ae0a48bSZlatko Calusic  * classzone_idx for the node to be considered balanced. Forcing all zones to
29554ae0a48bSZlatko Calusic  * be balanced for high orders can cause excessive reclaim when there are
29564ae0a48bSZlatko Calusic  * imbalanced zones.
29571741c877SMel Gorman  * The choice of 25% is due to
29581741c877SMel Gorman  *   o a 16M DMA zone that is balanced will not balance a zone on any
29591741c877SMel Gorman  *     reasonable sized machine
29601741c877SMel Gorman  *   o On all other machines, the top zone must be at least a reasonable
296125985edcSLucas De Marchi  *     percentage of the middle zones. For example, on 32-bit x86, highmem
29621741c877SMel Gorman  *     would need to be at least 256M for it to be balance a whole node.
29631741c877SMel Gorman  *     Similarly, on x86-64 the Normal zone would need to be at least 1G
29641741c877SMel Gorman  *     to balance a node on its own. These seemed like reasonable ratios.
29651741c877SMel Gorman  */
29664ae0a48bSZlatko Calusic static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
29671741c877SMel Gorman {
2968b40da049SJiang Liu 	unsigned long managed_pages = 0;
29694ae0a48bSZlatko Calusic 	unsigned long balanced_pages = 0;
29701741c877SMel Gorman 	int i;
29711741c877SMel Gorman 
29724ae0a48bSZlatko Calusic 	/* Check the watermark levels */
29734ae0a48bSZlatko Calusic 	for (i = 0; i <= classzone_idx; i++) {
29744ae0a48bSZlatko Calusic 		struct zone *zone = pgdat->node_zones + i;
29751741c877SMel Gorman 
29764ae0a48bSZlatko Calusic 		if (!populated_zone(zone))
29774ae0a48bSZlatko Calusic 			continue;
29784ae0a48bSZlatko Calusic 
2979b40da049SJiang Liu 		managed_pages += zone->managed_pages;
29804ae0a48bSZlatko Calusic 
29814ae0a48bSZlatko Calusic 		/*
29824ae0a48bSZlatko Calusic 		 * A special case here:
29834ae0a48bSZlatko Calusic 		 *
29844ae0a48bSZlatko Calusic 		 * balance_pgdat() skips over all_unreclaimable after
29854ae0a48bSZlatko Calusic 		 * DEF_PRIORITY. Effectively, it considers them balanced so
29864ae0a48bSZlatko Calusic 		 * they must be considered balanced here as well!
29874ae0a48bSZlatko Calusic 		 */
29886e543d57SLisa Du 		if (!zone_reclaimable(zone)) {
2989b40da049SJiang Liu 			balanced_pages += zone->managed_pages;
29904ae0a48bSZlatko Calusic 			continue;
29914ae0a48bSZlatko Calusic 		}
29924ae0a48bSZlatko Calusic 
29934ae0a48bSZlatko Calusic 		if (zone_balanced(zone, order, 0, i))
2994b40da049SJiang Liu 			balanced_pages += zone->managed_pages;
29954ae0a48bSZlatko Calusic 		else if (!order)
29964ae0a48bSZlatko Calusic 			return false;
29974ae0a48bSZlatko Calusic 	}
29984ae0a48bSZlatko Calusic 
29994ae0a48bSZlatko Calusic 	if (order)
3000b40da049SJiang Liu 		return balanced_pages >= (managed_pages >> 2);
30014ae0a48bSZlatko Calusic 	else
30024ae0a48bSZlatko Calusic 		return true;
30031741c877SMel Gorman }
30041741c877SMel Gorman 
30055515061dSMel Gorman /*
30065515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
30075515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
30085515061dSMel Gorman  *
30095515061dSMel Gorman  * Returns true if kswapd is ready to sleep
30105515061dSMel Gorman  */
30115515061dSMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, long remaining,
3012dc83edd9SMel Gorman 					int classzone_idx)
3013f50de2d3SMel Gorman {
3014f50de2d3SMel Gorman 	/* If a direct reclaimer woke kswapd within HZ/10, it's premature */
3015f50de2d3SMel Gorman 	if (remaining)
30165515061dSMel Gorman 		return false;
30175515061dSMel Gorman 
30185515061dSMel Gorman 	/*
30199e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
30209e5e3661SVlastimil Babka 	 * soon as pfmemalloc_watermark_ok() is true. But there is a potential
30219e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
30229e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
30239e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
30249e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
30259e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
30269e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
30279e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
30289e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
30299e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
30305515061dSMel Gorman 	 */
30319e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
30329e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3033f50de2d3SMel Gorman 
30344ae0a48bSZlatko Calusic 	return pgdat_balanced(pgdat, order, classzone_idx);
3035f50de2d3SMel Gorman }
3036f50de2d3SMel Gorman 
30371da177e4SLinus Torvalds /*
303875485363SMel Gorman  * kswapd shrinks the zone by the number of pages required to reach
303975485363SMel Gorman  * the high watermark.
3040b8e83b94SMel Gorman  *
3041b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3042283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3043283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
304475485363SMel Gorman  */
3045b8e83b94SMel Gorman static bool kswapd_shrink_zone(struct zone *zone,
30467c954f6dSMel Gorman 			       int classzone_idx,
304775485363SMel Gorman 			       struct scan_control *sc,
30482ab44f43SMel Gorman 			       unsigned long *nr_attempted)
304975485363SMel Gorman {
30507c954f6dSMel Gorman 	int testorder = sc->order;
30517c954f6dSMel Gorman 	unsigned long balance_gap;
30527c954f6dSMel Gorman 	bool lowmem_pressure;
305375485363SMel Gorman 
305475485363SMel Gorman 	/* Reclaim above the high watermark. */
305575485363SMel Gorman 	sc->nr_to_reclaim = max(SWAP_CLUSTER_MAX, high_wmark_pages(zone));
30567c954f6dSMel Gorman 
30577c954f6dSMel Gorman 	/*
30587c954f6dSMel Gorman 	 * Kswapd reclaims only single pages with compaction enabled. Trying
30597c954f6dSMel Gorman 	 * too hard to reclaim until contiguous free pages have become
30607c954f6dSMel Gorman 	 * available can hurt performance by evicting too much useful data
30617c954f6dSMel Gorman 	 * from memory. Do not reclaim more than needed for compaction.
30627c954f6dSMel Gorman 	 */
30637c954f6dSMel Gorman 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
3064ebff3980SVlastimil Babka 			compaction_suitable(zone, sc->order, 0, classzone_idx)
3065ebff3980SVlastimil Babka 							!= COMPACT_SKIPPED)
30667c954f6dSMel Gorman 		testorder = 0;
30677c954f6dSMel Gorman 
30687c954f6dSMel Gorman 	/*
30697c954f6dSMel Gorman 	 * We put equal pressure on every zone, unless one zone has way too
30707c954f6dSMel Gorman 	 * many pages free already. The "too many pages" is defined as the
30717c954f6dSMel Gorman 	 * high wmark plus a "gap" where the gap is either the low
30727c954f6dSMel Gorman 	 * watermark or 1% of the zone, whichever is smaller.
30737c954f6dSMel Gorman 	 */
30744be89a34SJianyu Zhan 	balance_gap = min(low_wmark_pages(zone), DIV_ROUND_UP(
30754be89a34SJianyu Zhan 			zone->managed_pages, KSWAPD_ZONE_BALANCE_GAP_RATIO));
30767c954f6dSMel Gorman 
30777c954f6dSMel Gorman 	/*
30787c954f6dSMel Gorman 	 * If there is no low memory pressure or the zone is balanced then no
30797c954f6dSMel Gorman 	 * reclaim is necessary
30807c954f6dSMel Gorman 	 */
30817c954f6dSMel Gorman 	lowmem_pressure = (buffer_heads_over_limit && is_highmem(zone));
30827c954f6dSMel Gorman 	if (!lowmem_pressure && zone_balanced(zone, testorder,
30837c954f6dSMel Gorman 						balance_gap, classzone_idx))
30847c954f6dSMel Gorman 		return true;
30857c954f6dSMel Gorman 
30866b4f7799SJohannes Weiner 	shrink_zone(zone, sc, zone_idx(zone) == classzone_idx);
308775485363SMel Gorman 
30882ab44f43SMel Gorman 	/* Account for the number of pages attempted to reclaim */
30892ab44f43SMel Gorman 	*nr_attempted += sc->nr_to_reclaim;
30902ab44f43SMel Gorman 
309157054651SJohannes Weiner 	clear_bit(ZONE_WRITEBACK, &zone->flags);
3092283aba9fSMel Gorman 
30937c954f6dSMel Gorman 	/*
30947c954f6dSMel Gorman 	 * If a zone reaches its high watermark, consider it to be no longer
30957c954f6dSMel Gorman 	 * congested. It's possible there are dirty pages backed by congested
30967c954f6dSMel Gorman 	 * BDIs but as pressure is relieved, speculatively avoid congestion
30977c954f6dSMel Gorman 	 * waits.
30987c954f6dSMel Gorman 	 */
30996e543d57SLisa Du 	if (zone_reclaimable(zone) &&
31007c954f6dSMel Gorman 	    zone_balanced(zone, testorder, 0, classzone_idx)) {
310157054651SJohannes Weiner 		clear_bit(ZONE_CONGESTED, &zone->flags);
310257054651SJohannes Weiner 		clear_bit(ZONE_DIRTY, &zone->flags);
31037c954f6dSMel Gorman 	}
31047c954f6dSMel Gorman 
3105b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
310675485363SMel Gorman }
310775485363SMel Gorman 
310875485363SMel Gorman /*
31091da177e4SLinus Torvalds  * For kswapd, balance_pgdat() will work across all this node's zones until
311041858966SMel Gorman  * they are all at high_wmark_pages(zone).
31111da177e4SLinus Torvalds  *
31120abdee2bSMel Gorman  * Returns the final order kswapd was reclaiming at
31131da177e4SLinus Torvalds  *
31141da177e4SLinus Torvalds  * There is special handling here for zones which are full of pinned pages.
31151da177e4SLinus Torvalds  * This can happen if the pages are all mlocked, or if they are all used by
31161da177e4SLinus Torvalds  * device drivers (say, ZONE_DMA).  Or if they are all in use by hugetlb.
31171da177e4SLinus Torvalds  * What we do is to detect the case where all pages in the zone have been
31181da177e4SLinus Torvalds  * scanned twice and there has been zero successful reclaim.  Mark the zone as
31191da177e4SLinus Torvalds  * dead and from now on, only perform a short scan.  Basically we're polling
31201da177e4SLinus Torvalds  * the zone for when the problem goes away.
31211da177e4SLinus Torvalds  *
31221da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
312341858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
312441858966SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
312541858966SMel Gorman  * lower zones regardless of the number of free pages in the lower zones. This
312641858966SMel Gorman  * interoperates with the page allocator fallback scheme to ensure that aging
312741858966SMel Gorman  * of pages is balanced across the zones.
31281da177e4SLinus Torvalds  */
312999504748SMel Gorman static unsigned long balance_pgdat(pg_data_t *pgdat, int order,
3130dc83edd9SMel Gorman 							int *classzone_idx)
31311da177e4SLinus Torvalds {
31321da177e4SLinus Torvalds 	int i;
313399504748SMel Gorman 	int end_zone = 0;	/* Inclusive.  0 = ZONE_DMA */
31340608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
31350608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3136179e9639SAndrew Morton 	struct scan_control sc = {
3137179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3138ee814fe2SJohannes Weiner 		.order = order,
3139b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
3140ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3141a6dc60f8SJohannes Weiner 		.may_unmap = 1,
31422e2e4259SKOSAKI Motohiro 		.may_swap = 1,
3143179e9639SAndrew Morton 	};
3144f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
31451da177e4SLinus Torvalds 
31469e3b2f8cSKonstantin Khlebnikov 	do {
31472ab44f43SMel Gorman 		unsigned long nr_attempted = 0;
3148b8e83b94SMel Gorman 		bool raise_priority = true;
31492ab44f43SMel Gorman 		bool pgdat_needs_compaction = (order > 0);
3150b8e83b94SMel Gorman 
3151b8e83b94SMel Gorman 		sc.nr_reclaimed = 0;
31521da177e4SLinus Torvalds 
31531da177e4SLinus Torvalds 		/*
31541da177e4SLinus Torvalds 		 * Scan in the highmem->dma direction for the highest
31551da177e4SLinus Torvalds 		 * zone which needs scanning
31561da177e4SLinus Torvalds 		 */
31571da177e4SLinus Torvalds 		for (i = pgdat->nr_zones - 1; i >= 0; i--) {
31581da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
31591da177e4SLinus Torvalds 
3160f3fe6512SCon Kolivas 			if (!populated_zone(zone))
31611da177e4SLinus Torvalds 				continue;
31621da177e4SLinus Torvalds 
31636e543d57SLisa Du 			if (sc.priority != DEF_PRIORITY &&
31646e543d57SLisa Du 			    !zone_reclaimable(zone))
31651da177e4SLinus Torvalds 				continue;
31661da177e4SLinus Torvalds 
3167556adecbSRik van Riel 			/*
3168556adecbSRik van Riel 			 * Do some background aging of the anon list, to give
3169556adecbSRik van Riel 			 * pages a chance to be referenced before reclaiming.
3170556adecbSRik van Riel 			 */
31719e3b2f8cSKonstantin Khlebnikov 			age_active_anon(zone, &sc);
3172556adecbSRik van Riel 
3173cc715d99SMel Gorman 			/*
3174cc715d99SMel Gorman 			 * If the number of buffer_heads in the machine
3175cc715d99SMel Gorman 			 * exceeds the maximum allowed level and this node
3176cc715d99SMel Gorman 			 * has a highmem zone, force kswapd to reclaim from
3177cc715d99SMel Gorman 			 * it to relieve lowmem pressure.
3178cc715d99SMel Gorman 			 */
3179cc715d99SMel Gorman 			if (buffer_heads_over_limit && is_highmem_idx(i)) {
3180cc715d99SMel Gorman 				end_zone = i;
3181cc715d99SMel Gorman 				break;
3182cc715d99SMel Gorman 			}
3183cc715d99SMel Gorman 
318460cefed4SJohannes Weiner 			if (!zone_balanced(zone, order, 0, 0)) {
31851da177e4SLinus Torvalds 				end_zone = i;
3186e1dbeda6SAndrew Morton 				break;
3187439423f6SShaohua Li 			} else {
3188d43006d5SMel Gorman 				/*
3189d43006d5SMel Gorman 				 * If balanced, clear the dirty and congested
3190d43006d5SMel Gorman 				 * flags
3191d43006d5SMel Gorman 				 */
319257054651SJohannes Weiner 				clear_bit(ZONE_CONGESTED, &zone->flags);
319357054651SJohannes Weiner 				clear_bit(ZONE_DIRTY, &zone->flags);
31941da177e4SLinus Torvalds 			}
31951da177e4SLinus Torvalds 		}
3196dafcb73eSZlatko Calusic 
3197b8e83b94SMel Gorman 		if (i < 0)
31981da177e4SLinus Torvalds 			goto out;
3199e1dbeda6SAndrew Morton 
32001da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
32011da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
32021da177e4SLinus Torvalds 
32032ab44f43SMel Gorman 			if (!populated_zone(zone))
32042ab44f43SMel Gorman 				continue;
32052ab44f43SMel Gorman 
32062ab44f43SMel Gorman 			/*
32072ab44f43SMel Gorman 			 * If any zone is currently balanced then kswapd will
32082ab44f43SMel Gorman 			 * not call compaction as it is expected that the
32092ab44f43SMel Gorman 			 * necessary pages are already available.
32102ab44f43SMel Gorman 			 */
32112ab44f43SMel Gorman 			if (pgdat_needs_compaction &&
32122ab44f43SMel Gorman 					zone_watermark_ok(zone, order,
32132ab44f43SMel Gorman 						low_wmark_pages(zone),
32142ab44f43SMel Gorman 						*classzone_idx, 0))
32152ab44f43SMel Gorman 				pgdat_needs_compaction = false;
32161da177e4SLinus Torvalds 		}
32171da177e4SLinus Torvalds 
32181da177e4SLinus Torvalds 		/*
3219b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3220b7ea3c41SMel Gorman 		 * even in laptop mode.
3221b7ea3c41SMel Gorman 		 */
3222b7ea3c41SMel Gorman 		if (sc.priority < DEF_PRIORITY - 2)
3223b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3224b7ea3c41SMel Gorman 
3225b7ea3c41SMel Gorman 		/*
32261da177e4SLinus Torvalds 		 * Now scan the zone in the dma->highmem direction, stopping
32271da177e4SLinus Torvalds 		 * at the last zone which needs scanning.
32281da177e4SLinus Torvalds 		 *
32291da177e4SLinus Torvalds 		 * We do this because the page allocator works in the opposite
32301da177e4SLinus Torvalds 		 * direction.  This prevents the page allocator from allocating
32311da177e4SLinus Torvalds 		 * pages behind kswapd's direction of progress, which would
32321da177e4SLinus Torvalds 		 * cause too much scanning of the lower zones.
32331da177e4SLinus Torvalds 		 */
32341da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
32351da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
32361da177e4SLinus Torvalds 
3237f3fe6512SCon Kolivas 			if (!populated_zone(zone))
32381da177e4SLinus Torvalds 				continue;
32391da177e4SLinus Torvalds 
32406e543d57SLisa Du 			if (sc.priority != DEF_PRIORITY &&
32416e543d57SLisa Du 			    !zone_reclaimable(zone))
32421da177e4SLinus Torvalds 				continue;
32431da177e4SLinus Torvalds 
32441da177e4SLinus Torvalds 			sc.nr_scanned = 0;
32454e416953SBalbir Singh 
32460608f43dSAndrew Morton 			nr_soft_scanned = 0;
32470608f43dSAndrew Morton 			/*
32480608f43dSAndrew Morton 			 * Call soft limit reclaim before calling shrink_zone.
32490608f43dSAndrew Morton 			 */
32500608f43dSAndrew Morton 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
32510608f43dSAndrew Morton 							order, sc.gfp_mask,
32520608f43dSAndrew Morton 							&nr_soft_scanned);
32530608f43dSAndrew Morton 			sc.nr_reclaimed += nr_soft_reclaimed;
32540608f43dSAndrew Morton 
325532a4330dSRik van Riel 			/*
32567c954f6dSMel Gorman 			 * There should be no need to raise the scanning
32577c954f6dSMel Gorman 			 * priority if enough pages are already being scanned
32587c954f6dSMel Gorman 			 * that that high watermark would be met at 100%
32597c954f6dSMel Gorman 			 * efficiency.
326032a4330dSRik van Riel 			 */
32616b4f7799SJohannes Weiner 			if (kswapd_shrink_zone(zone, end_zone,
32626b4f7799SJohannes Weiner 					       &sc, &nr_attempted))
3263b8e83b94SMel Gorman 				raise_priority = false;
3264b8e83b94SMel Gorman 		}
3265d7868daeSMel Gorman 
32665515061dSMel Gorman 		/*
32675515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
32685515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
32695515061dSMel Gorman 		 * able to safely make forward progress. Wake them
32705515061dSMel Gorman 		 */
32715515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
32725515061dSMel Gorman 				pfmemalloc_watermark_ok(pgdat))
3273cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
32745515061dSMel Gorman 
32751da177e4SLinus Torvalds 		/*
3276b8e83b94SMel Gorman 		 * Fragmentation may mean that the system cannot be rebalanced
3277b8e83b94SMel Gorman 		 * for high-order allocations in all zones. If twice the
3278b8e83b94SMel Gorman 		 * allocation size has been reclaimed and the zones are still
3279b8e83b94SMel Gorman 		 * not balanced then recheck the watermarks at order-0 to
3280b8e83b94SMel Gorman 		 * prevent kswapd reclaiming excessively. Assume that a
3281b8e83b94SMel Gorman 		 * process requested a high-order can direct reclaim/compact.
32821da177e4SLinus Torvalds 		 */
3283b8e83b94SMel Gorman 		if (order && sc.nr_reclaimed >= 2UL << order)
328473ce02e9SKOSAKI Motohiro 			order = sc.order = 0;
328573ce02e9SKOSAKI Motohiro 
3286b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
3287b8e83b94SMel Gorman 		if (try_to_freeze() || kthread_should_stop())
3288b8e83b94SMel Gorman 			break;
3289b8e83b94SMel Gorman 
3290b8e83b94SMel Gorman 		/*
32912ab44f43SMel Gorman 		 * Compact if necessary and kswapd is reclaiming at least the
32922ab44f43SMel Gorman 		 * high watermark number of pages as requsted
32932ab44f43SMel Gorman 		 */
32942ab44f43SMel Gorman 		if (pgdat_needs_compaction && sc.nr_reclaimed > nr_attempted)
32952ab44f43SMel Gorman 			compact_pgdat(pgdat, order);
32962ab44f43SMel Gorman 
32972ab44f43SMel Gorman 		/*
3298b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3299b8e83b94SMel Gorman 		 * progress in reclaiming pages
3300b8e83b94SMel Gorman 		 */
3301b8e83b94SMel Gorman 		if (raise_priority || !sc.nr_reclaimed)
3302b8e83b94SMel Gorman 			sc.priority--;
33039aa41348SMel Gorman 	} while (sc.priority >= 1 &&
3304b8e83b94SMel Gorman 		 !pgdat_balanced(pgdat, order, *classzone_idx));
33051da177e4SLinus Torvalds 
3306b8e83b94SMel Gorman out:
33070abdee2bSMel Gorman 	/*
33085515061dSMel Gorman 	 * Return the order we were reclaiming at so prepare_kswapd_sleep()
33090abdee2bSMel Gorman 	 * makes a decision on the order we were last reclaiming at. However,
33100abdee2bSMel Gorman 	 * if another caller entered the allocator slow path while kswapd
33110abdee2bSMel Gorman 	 * was awake, order will remain at the higher level
33120abdee2bSMel Gorman 	 */
3313dc83edd9SMel Gorman 	*classzone_idx = end_zone;
33140abdee2bSMel Gorman 	return order;
33151da177e4SLinus Torvalds }
33161da177e4SLinus Torvalds 
3317dc83edd9SMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3318f0bc0a60SKOSAKI Motohiro {
3319f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3320f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3321f0bc0a60SKOSAKI Motohiro 
3322f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3323f0bc0a60SKOSAKI Motohiro 		return;
3324f0bc0a60SKOSAKI Motohiro 
3325f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3326f0bc0a60SKOSAKI Motohiro 
3327f0bc0a60SKOSAKI Motohiro 	/* Try to sleep for a short interval */
33285515061dSMel Gorman 	if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
3329f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
3330f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3331f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3332f0bc0a60SKOSAKI Motohiro 	}
3333f0bc0a60SKOSAKI Motohiro 
3334f0bc0a60SKOSAKI Motohiro 	/*
3335f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3336f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3337f0bc0a60SKOSAKI Motohiro 	 */
33385515061dSMel Gorman 	if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
3339f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3340f0bc0a60SKOSAKI Motohiro 
3341f0bc0a60SKOSAKI Motohiro 		/*
3342f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3343f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3344f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3345f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3346f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3347f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3348f0bc0a60SKOSAKI Motohiro 		 */
3349f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
33501c7e7f6cSAaditya Kumar 
335162997027SMel Gorman 		/*
335262997027SMel Gorman 		 * Compaction records what page blocks it recently failed to
335362997027SMel Gorman 		 * isolate pages from and skips them in the future scanning.
335462997027SMel Gorman 		 * When kswapd is going to sleep, it is reasonable to assume
335562997027SMel Gorman 		 * that pages and compaction may succeed so reset the cache.
335662997027SMel Gorman 		 */
335762997027SMel Gorman 		reset_isolation_suitable(pgdat);
335862997027SMel Gorman 
33591c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3360f0bc0a60SKOSAKI Motohiro 			schedule();
33611c7e7f6cSAaditya Kumar 
3362f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3363f0bc0a60SKOSAKI Motohiro 	} else {
3364f0bc0a60SKOSAKI Motohiro 		if (remaining)
3365f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3366f0bc0a60SKOSAKI Motohiro 		else
3367f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3368f0bc0a60SKOSAKI Motohiro 	}
3369f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3370f0bc0a60SKOSAKI Motohiro }
3371f0bc0a60SKOSAKI Motohiro 
33721da177e4SLinus Torvalds /*
33731da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
33741da177e4SLinus Torvalds  * from the init process.
33751da177e4SLinus Torvalds  *
33761da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
33771da177e4SLinus Torvalds  * free memory available even if there is no other activity
33781da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
33791da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
33801da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
33811da177e4SLinus Torvalds  *
33821da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
33831da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
33841da177e4SLinus Torvalds  */
33851da177e4SLinus Torvalds static int kswapd(void *p)
33861da177e4SLinus Torvalds {
3387215ddd66SMel Gorman 	unsigned long order, new_order;
3388d2ebd0f6SAlex,Shi 	unsigned balanced_order;
3389215ddd66SMel Gorman 	int classzone_idx, new_classzone_idx;
3390d2ebd0f6SAlex,Shi 	int balanced_classzone_idx;
33911da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
33921da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3393f0bc0a60SKOSAKI Motohiro 
33941da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
33951da177e4SLinus Torvalds 		.reclaimed_slab = 0,
33961da177e4SLinus Torvalds 	};
3397a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
33981da177e4SLinus Torvalds 
3399cf40bd16SNick Piggin 	lockdep_set_current_reclaim_state(GFP_KERNEL);
3400cf40bd16SNick Piggin 
3401174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3402c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
34031da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
34041da177e4SLinus Torvalds 
34051da177e4SLinus Torvalds 	/*
34061da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
34071da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
34081da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
34091da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
34101da177e4SLinus Torvalds 	 *
34111da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
34121da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
34131da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
34141da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
34151da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
34161da177e4SLinus Torvalds 	 */
3417930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
341883144186SRafael J. Wysocki 	set_freezable();
34191da177e4SLinus Torvalds 
3420215ddd66SMel Gorman 	order = new_order = 0;
3421d2ebd0f6SAlex,Shi 	balanced_order = 0;
3422215ddd66SMel Gorman 	classzone_idx = new_classzone_idx = pgdat->nr_zones - 1;
3423d2ebd0f6SAlex,Shi 	balanced_classzone_idx = classzone_idx;
34241da177e4SLinus Torvalds 	for ( ; ; ) {
34256f6313d4SJeff Liu 		bool ret;
34263e1d1d28SChristoph Lameter 
3427215ddd66SMel Gorman 		/*
3428215ddd66SMel Gorman 		 * If the last balance_pgdat was unsuccessful it's unlikely a
3429215ddd66SMel Gorman 		 * new request of a similar or harder type will succeed soon
3430215ddd66SMel Gorman 		 * so consider going to sleep on the basis we reclaimed at
3431215ddd66SMel Gorman 		 */
3432d2ebd0f6SAlex,Shi 		if (balanced_classzone_idx >= new_classzone_idx &&
3433d2ebd0f6SAlex,Shi 					balanced_order == new_order) {
34341da177e4SLinus Torvalds 			new_order = pgdat->kswapd_max_order;
343599504748SMel Gorman 			new_classzone_idx = pgdat->classzone_idx;
34361da177e4SLinus Torvalds 			pgdat->kswapd_max_order =  0;
3437215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
3438215ddd66SMel Gorman 		}
3439215ddd66SMel Gorman 
344099504748SMel Gorman 		if (order < new_order || classzone_idx > new_classzone_idx) {
34411da177e4SLinus Torvalds 			/*
34421da177e4SLinus Torvalds 			 * Don't sleep if someone wants a larger 'order'
344399504748SMel Gorman 			 * allocation or has tigher zone constraints
34441da177e4SLinus Torvalds 			 */
34451da177e4SLinus Torvalds 			order = new_order;
344699504748SMel Gorman 			classzone_idx = new_classzone_idx;
34471da177e4SLinus Torvalds 		} else {
3448d2ebd0f6SAlex,Shi 			kswapd_try_to_sleep(pgdat, balanced_order,
3449d2ebd0f6SAlex,Shi 						balanced_classzone_idx);
34501da177e4SLinus Torvalds 			order = pgdat->kswapd_max_order;
345199504748SMel Gorman 			classzone_idx = pgdat->classzone_idx;
3452f0dfcde0SAlex,Shi 			new_order = order;
3453f0dfcde0SAlex,Shi 			new_classzone_idx = classzone_idx;
34544d40502eSMel Gorman 			pgdat->kswapd_max_order = 0;
3455215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
34561da177e4SLinus Torvalds 		}
34571da177e4SLinus Torvalds 
34588fe23e05SDavid Rientjes 		ret = try_to_freeze();
34598fe23e05SDavid Rientjes 		if (kthread_should_stop())
34608fe23e05SDavid Rientjes 			break;
34618fe23e05SDavid Rientjes 
34628fe23e05SDavid Rientjes 		/*
34638fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
34648fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3465b1296cc4SRafael J. Wysocki 		 */
346633906bc5SMel Gorman 		if (!ret) {
346733906bc5SMel Gorman 			trace_mm_vmscan_kswapd_wake(pgdat->node_id, order);
3468d2ebd0f6SAlex,Shi 			balanced_classzone_idx = classzone_idx;
3469d2ebd0f6SAlex,Shi 			balanced_order = balance_pgdat(pgdat, order,
3470d2ebd0f6SAlex,Shi 						&balanced_classzone_idx);
34711da177e4SLinus Torvalds 		}
347233906bc5SMel Gorman 	}
3473b0a8cc58STakamori Yamaguchi 
347471abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
3475b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
347671abdc15SJohannes Weiner 	lockdep_clear_current_reclaim_state();
347771abdc15SJohannes Weiner 
34781da177e4SLinus Torvalds 	return 0;
34791da177e4SLinus Torvalds }
34801da177e4SLinus Torvalds 
34811da177e4SLinus Torvalds /*
34821da177e4SLinus Torvalds  * A zone is low on free memory, so wake its kswapd task to service it.
34831da177e4SLinus Torvalds  */
348499504748SMel Gorman void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
34851da177e4SLinus Torvalds {
34861da177e4SLinus Torvalds 	pg_data_t *pgdat;
34871da177e4SLinus Torvalds 
3488f3fe6512SCon Kolivas 	if (!populated_zone(zone))
34891da177e4SLinus Torvalds 		return;
34901da177e4SLinus Torvalds 
3491344736f2SVladimir Davydov 	if (!cpuset_zone_allowed(zone, GFP_KERNEL | __GFP_HARDWALL))
34921da177e4SLinus Torvalds 		return;
349388f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
349499504748SMel Gorman 	if (pgdat->kswapd_max_order < order) {
349588f5acf8SMel Gorman 		pgdat->kswapd_max_order = order;
349699504748SMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx);
349799504748SMel Gorman 	}
34988d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
34991da177e4SLinus Torvalds 		return;
3500892f795dSJohannes Weiner 	if (zone_balanced(zone, order, 0, 0))
350188f5acf8SMel Gorman 		return;
350288f5acf8SMel Gorman 
350388f5acf8SMel Gorman 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
35048d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
35051da177e4SLinus Torvalds }
35061da177e4SLinus Torvalds 
3507c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
35081da177e4SLinus Torvalds /*
35097b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3510d6277db4SRafael J. Wysocki  * freed pages.
3511d6277db4SRafael J. Wysocki  *
3512d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3513d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3514d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
35151da177e4SLinus Torvalds  */
35167b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
35171da177e4SLinus Torvalds {
3518d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3519d6277db4SRafael J. Wysocki 	struct scan_control sc = {
35207b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
3521ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
35229e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
3523ee814fe2SJohannes Weiner 		.may_writepage = 1,
3524ee814fe2SJohannes Weiner 		.may_unmap = 1,
3525ee814fe2SJohannes Weiner 		.may_swap = 1,
3526ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
35271da177e4SLinus Torvalds 	};
35287b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
35297b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
35307b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
35311da177e4SLinus Torvalds 
35327b51755cSKOSAKI Motohiro 	p->flags |= PF_MEMALLOC;
35337b51755cSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(sc.gfp_mask);
3534d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
35357b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3536d6277db4SRafael J. Wysocki 
35373115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3538d6277db4SRafael J. Wysocki 
35397b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
35407b51755cSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
35417b51755cSKOSAKI Motohiro 	p->flags &= ~PF_MEMALLOC;
3542d6277db4SRafael J. Wysocki 
35437b51755cSKOSAKI Motohiro 	return nr_reclaimed;
35441da177e4SLinus Torvalds }
3545c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
35461da177e4SLinus Torvalds 
35471da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
35481da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
35491da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
35501da177e4SLinus Torvalds    restore their cpu bindings. */
3551fcb35a9bSGreg Kroah-Hartman static int cpu_callback(struct notifier_block *nfb, unsigned long action,
3552fcb35a9bSGreg Kroah-Hartman 			void *hcpu)
35531da177e4SLinus Torvalds {
355458c0a4a7SYasunori Goto 	int nid;
35551da177e4SLinus Torvalds 
35568bb78442SRafael J. Wysocki 	if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
355748fb2e24SLai Jiangshan 		for_each_node_state(nid, N_MEMORY) {
3558c5f59f08SMike Travis 			pg_data_t *pgdat = NODE_DATA(nid);
3559a70f7302SRusty Russell 			const struct cpumask *mask;
3560a70f7302SRusty Russell 
3561a70f7302SRusty Russell 			mask = cpumask_of_node(pgdat->node_id);
3562c5f59f08SMike Travis 
35633e597945SRusty Russell 			if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
35641da177e4SLinus Torvalds 				/* One of our CPUs online: restore mask */
3565c5f59f08SMike Travis 				set_cpus_allowed_ptr(pgdat->kswapd, mask);
35661da177e4SLinus Torvalds 		}
35671da177e4SLinus Torvalds 	}
35681da177e4SLinus Torvalds 	return NOTIFY_OK;
35691da177e4SLinus Torvalds }
35701da177e4SLinus Torvalds 
35713218ae14SYasunori Goto /*
35723218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
35733218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
35743218ae14SYasunori Goto  */
35753218ae14SYasunori Goto int kswapd_run(int nid)
35763218ae14SYasunori Goto {
35773218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
35783218ae14SYasunori Goto 	int ret = 0;
35793218ae14SYasunori Goto 
35803218ae14SYasunori Goto 	if (pgdat->kswapd)
35813218ae14SYasunori Goto 		return 0;
35823218ae14SYasunori Goto 
35833218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
35843218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
35853218ae14SYasunori Goto 		/* failure at boot is fatal */
35863218ae14SYasunori Goto 		BUG_ON(system_state == SYSTEM_BOOTING);
3587d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3588d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3589d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
35903218ae14SYasunori Goto 	}
35913218ae14SYasunori Goto 	return ret;
35923218ae14SYasunori Goto }
35933218ae14SYasunori Goto 
35948fe23e05SDavid Rientjes /*
3595d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3596bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
35978fe23e05SDavid Rientjes  */
35988fe23e05SDavid Rientjes void kswapd_stop(int nid)
35998fe23e05SDavid Rientjes {
36008fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
36018fe23e05SDavid Rientjes 
3602d8adde17SJiang Liu 	if (kswapd) {
36038fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3604d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3605d8adde17SJiang Liu 	}
36068fe23e05SDavid Rientjes }
36078fe23e05SDavid Rientjes 
36081da177e4SLinus Torvalds static int __init kswapd_init(void)
36091da177e4SLinus Torvalds {
36103218ae14SYasunori Goto 	int nid;
361169e05944SAndrew Morton 
36121da177e4SLinus Torvalds 	swap_setup();
361348fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
36143218ae14SYasunori Goto  		kswapd_run(nid);
36151da177e4SLinus Torvalds 	hotcpu_notifier(cpu_callback, 0);
36161da177e4SLinus Torvalds 	return 0;
36171da177e4SLinus Torvalds }
36181da177e4SLinus Torvalds 
36191da177e4SLinus Torvalds module_init(kswapd_init)
36209eeff239SChristoph Lameter 
36219eeff239SChristoph Lameter #ifdef CONFIG_NUMA
36229eeff239SChristoph Lameter /*
36239eeff239SChristoph Lameter  * Zone reclaim mode
36249eeff239SChristoph Lameter  *
36259eeff239SChristoph Lameter  * If non-zero call zone_reclaim when the number of free pages falls below
36269eeff239SChristoph Lameter  * the watermarks.
36279eeff239SChristoph Lameter  */
36289eeff239SChristoph Lameter int zone_reclaim_mode __read_mostly;
36299eeff239SChristoph Lameter 
36301b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
36317d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
36321b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
363395bbc0c7SZhihui Zhang #define RECLAIM_UNMAP (1<<2)	/* Unmap pages during reclaim */
36341b2ffb78SChristoph Lameter 
36359eeff239SChristoph Lameter /*
3636a92f7126SChristoph Lameter  * Priority for ZONE_RECLAIM. This determines the fraction of pages
3637a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3638a92f7126SChristoph Lameter  * a zone.
3639a92f7126SChristoph Lameter  */
3640a92f7126SChristoph Lameter #define ZONE_RECLAIM_PRIORITY 4
3641a92f7126SChristoph Lameter 
36429eeff239SChristoph Lameter /*
36439614634fSChristoph Lameter  * Percentage of pages in a zone that must be unmapped for zone_reclaim to
36449614634fSChristoph Lameter  * occur.
36459614634fSChristoph Lameter  */
36469614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
36479614634fSChristoph Lameter 
36489614634fSChristoph Lameter /*
36490ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
36500ff38490SChristoph Lameter  * slab reclaim needs to occur.
36510ff38490SChristoph Lameter  */
36520ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
36530ff38490SChristoph Lameter 
365490afa5deSMel Gorman static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
365590afa5deSMel Gorman {
365690afa5deSMel Gorman 	unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
365790afa5deSMel Gorman 	unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
365890afa5deSMel Gorman 		zone_page_state(zone, NR_ACTIVE_FILE);
365990afa5deSMel Gorman 
366090afa5deSMel Gorman 	/*
366190afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
366290afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
366390afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
366490afa5deSMel Gorman 	 */
366590afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
366690afa5deSMel Gorman }
366790afa5deSMel Gorman 
366890afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
366990afa5deSMel Gorman static long zone_pagecache_reclaimable(struct zone *zone)
367090afa5deSMel Gorman {
367190afa5deSMel Gorman 	long nr_pagecache_reclaimable;
367290afa5deSMel Gorman 	long delta = 0;
367390afa5deSMel Gorman 
367490afa5deSMel Gorman 	/*
367595bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
367690afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
367790afa5deSMel Gorman 	 * pages like swapcache and zone_unmapped_file_pages() provides
367890afa5deSMel Gorman 	 * a better estimate
367990afa5deSMel Gorman 	 */
368095bbc0c7SZhihui Zhang 	if (zone_reclaim_mode & RECLAIM_UNMAP)
368190afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
368290afa5deSMel Gorman 	else
368390afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
368490afa5deSMel Gorman 
368590afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
368690afa5deSMel Gorman 	if (!(zone_reclaim_mode & RECLAIM_WRITE))
368790afa5deSMel Gorman 		delta += zone_page_state(zone, NR_FILE_DIRTY);
368890afa5deSMel Gorman 
368990afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
369090afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
369190afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
369290afa5deSMel Gorman 
369390afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
369490afa5deSMel Gorman }
369590afa5deSMel Gorman 
36960ff38490SChristoph Lameter /*
36979eeff239SChristoph Lameter  * Try to free up some pages from this zone through reclaim.
36989eeff239SChristoph Lameter  */
3699179e9639SAndrew Morton static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
37009eeff239SChristoph Lameter {
37017fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
370269e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
37039eeff239SChristoph Lameter 	struct task_struct *p = current;
37049eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
3705179e9639SAndrew Morton 	struct scan_control sc = {
370662b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
370721caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
3708bd2f6199SJohannes Weiner 		.order = order,
37099e3b2f8cSKonstantin Khlebnikov 		.priority = ZONE_RECLAIM_PRIORITY,
3710ee814fe2SJohannes Weiner 		.may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
371195bbc0c7SZhihui Zhang 		.may_unmap = !!(zone_reclaim_mode & RECLAIM_UNMAP),
3712ee814fe2SJohannes Weiner 		.may_swap = 1,
3713179e9639SAndrew Morton 	};
37149eeff239SChristoph Lameter 
37159eeff239SChristoph Lameter 	cond_resched();
3716d4f7796eSChristoph Lameter 	/*
371795bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
3718d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
371995bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
3720d4f7796eSChristoph Lameter 	 */
3721d4f7796eSChristoph Lameter 	p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
372276ca542dSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(gfp_mask);
37239eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
37249eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3725c84db23cSChristoph Lameter 
372690afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
3727a92f7126SChristoph Lameter 		/*
37280ff38490SChristoph Lameter 		 * Free memory by calling shrink zone with increasing
37290ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3730a92f7126SChristoph Lameter 		 */
3731a92f7126SChristoph Lameter 		do {
37326b4f7799SJohannes Weiner 			shrink_zone(zone, &sc, true);
37339e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
37340ff38490SChristoph Lameter 	}
3735a92f7126SChristoph Lameter 
37369eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3737d4f7796eSChristoph Lameter 	current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
373876ca542dSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
3739a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
37409eeff239SChristoph Lameter }
3741179e9639SAndrew Morton 
3742179e9639SAndrew Morton int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
3743179e9639SAndrew Morton {
3744179e9639SAndrew Morton 	int node_id;
3745d773ed6bSDavid Rientjes 	int ret;
3746179e9639SAndrew Morton 
3747179e9639SAndrew Morton 	/*
37480ff38490SChristoph Lameter 	 * Zone reclaim reclaims unmapped file backed pages and
37490ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
375034aa1330SChristoph Lameter 	 *
37519614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
37529614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
37539614634fSChristoph Lameter 	 * thrown out if the zone is overallocated. So we do not reclaim
37549614634fSChristoph Lameter 	 * if less than a specified percentage of the zone is used by
37559614634fSChristoph Lameter 	 * unmapped file backed pages.
3756179e9639SAndrew Morton 	 */
375790afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
375890afa5deSMel Gorman 	    zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
3759fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3760179e9639SAndrew Morton 
37616e543d57SLisa Du 	if (!zone_reclaimable(zone))
3762fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3763d773ed6bSDavid Rientjes 
3764179e9639SAndrew Morton 	/*
3765d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3766179e9639SAndrew Morton 	 */
3767d773ed6bSDavid Rientjes 	if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
3768fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3769179e9639SAndrew Morton 
3770179e9639SAndrew Morton 	/*
3771179e9639SAndrew Morton 	 * Only run zone reclaim on the local zone or on zones that do not
3772179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3773179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3774179e9639SAndrew Morton 	 * as wide as possible.
3775179e9639SAndrew Morton 	 */
377689fa3024SChristoph Lameter 	node_id = zone_to_nid(zone);
377737c0708dSChristoph Lameter 	if (node_state(node_id, N_CPU) && node_id != numa_node_id())
3778fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3779d773ed6bSDavid Rientjes 
378057054651SJohannes Weiner 	if (test_and_set_bit(ZONE_RECLAIM_LOCKED, &zone->flags))
3781fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3782fa5e084eSMel Gorman 
3783d773ed6bSDavid Rientjes 	ret = __zone_reclaim(zone, gfp_mask, order);
378457054651SJohannes Weiner 	clear_bit(ZONE_RECLAIM_LOCKED, &zone->flags);
3785d773ed6bSDavid Rientjes 
378624cf7251SMel Gorman 	if (!ret)
378724cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
378824cf7251SMel Gorman 
3789d773ed6bSDavid Rientjes 	return ret;
3790179e9639SAndrew Morton }
37919eeff239SChristoph Lameter #endif
3792894bc310SLee Schermerhorn 
3793894bc310SLee Schermerhorn /*
3794894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3795894bc310SLee Schermerhorn  * @page: the page to test
3796894bc310SLee Schermerhorn  *
3797894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
379839b5f29aSHugh Dickins  * lists vs unevictable list.
3799894bc310SLee Schermerhorn  *
3800894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3801ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3802b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3803ba9ddf49SLee Schermerhorn  *
3804894bc310SLee Schermerhorn  */
380539b5f29aSHugh Dickins int page_evictable(struct page *page)
3806894bc310SLee Schermerhorn {
380739b5f29aSHugh Dickins 	return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3808894bc310SLee Schermerhorn }
380989e004eaSLee Schermerhorn 
381085046579SHugh Dickins #ifdef CONFIG_SHMEM
381189e004eaSLee Schermerhorn /**
381224513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
381324513264SHugh Dickins  * @pages:	array of pages to check
381424513264SHugh Dickins  * @nr_pages:	number of pages to check
381589e004eaSLee Schermerhorn  *
381624513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
381785046579SHugh Dickins  *
381885046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
381989e004eaSLee Schermerhorn  */
382024513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
382189e004eaSLee Schermerhorn {
3822925b7673SJohannes Weiner 	struct lruvec *lruvec;
382324513264SHugh Dickins 	struct zone *zone = NULL;
382424513264SHugh Dickins 	int pgscanned = 0;
382524513264SHugh Dickins 	int pgrescued = 0;
382689e004eaSLee Schermerhorn 	int i;
382789e004eaSLee Schermerhorn 
382824513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
382924513264SHugh Dickins 		struct page *page = pages[i];
383024513264SHugh Dickins 		struct zone *pagezone;
383189e004eaSLee Schermerhorn 
383224513264SHugh Dickins 		pgscanned++;
383324513264SHugh Dickins 		pagezone = page_zone(page);
383489e004eaSLee Schermerhorn 		if (pagezone != zone) {
383589e004eaSLee Schermerhorn 			if (zone)
383689e004eaSLee Schermerhorn 				spin_unlock_irq(&zone->lru_lock);
383789e004eaSLee Schermerhorn 			zone = pagezone;
383889e004eaSLee Schermerhorn 			spin_lock_irq(&zone->lru_lock);
383989e004eaSLee Schermerhorn 		}
3840fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
384189e004eaSLee Schermerhorn 
384224513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
384324513264SHugh Dickins 			continue;
384489e004eaSLee Schermerhorn 
384539b5f29aSHugh Dickins 		if (page_evictable(page)) {
384624513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
384724513264SHugh Dickins 
3848309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
384924513264SHugh Dickins 			ClearPageUnevictable(page);
3850fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3851fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
385224513264SHugh Dickins 			pgrescued++;
385389e004eaSLee Schermerhorn 		}
385489e004eaSLee Schermerhorn 	}
385524513264SHugh Dickins 
385624513264SHugh Dickins 	if (zone) {
385724513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
385824513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
385924513264SHugh Dickins 		spin_unlock_irq(&zone->lru_lock);
386024513264SHugh Dickins 	}
386185046579SHugh Dickins }
386285046579SHugh Dickins #endif /* CONFIG_SHMEM */
3863