xref: /openbmc/linux/mm/vmscan.c (revision 8612c6639b70c59308cf37ae4790817df9621281)
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 
94ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
95ee814fe2SJohannes Weiner 
96ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
97ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
98ee814fe2SJohannes Weiner 
99ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
100ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
101ee814fe2SJohannes Weiner 
102ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
103ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
1041da177e4SLinus Torvalds };
1051da177e4SLinus Torvalds 
1061da177e4SLinus Torvalds #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
1071da177e4SLinus Torvalds 
1081da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCH
1091da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field)			\
1101da177e4SLinus Torvalds 	do {								\
1111da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1121da177e4SLinus Torvalds 			struct page *prev;				\
1131da177e4SLinus Torvalds 									\
1141da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1151da177e4SLinus Torvalds 			prefetch(&prev->_field);			\
1161da177e4SLinus Torvalds 		}							\
1171da177e4SLinus Torvalds 	} while (0)
1181da177e4SLinus Torvalds #else
1191da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
1201da177e4SLinus Torvalds #endif
1211da177e4SLinus Torvalds 
1221da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1231da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1241da177e4SLinus Torvalds 	do {								\
1251da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1261da177e4SLinus Torvalds 			struct page *prev;				\
1271da177e4SLinus Torvalds 									\
1281da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1291da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1301da177e4SLinus Torvalds 		}							\
1311da177e4SLinus Torvalds 	} while (0)
1321da177e4SLinus Torvalds #else
1331da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1341da177e4SLinus Torvalds #endif
1351da177e4SLinus Torvalds 
1361da177e4SLinus Torvalds /*
1371da177e4SLinus Torvalds  * From 0 .. 100.  Higher means more swappy.
1381da177e4SLinus Torvalds  */
1391da177e4SLinus Torvalds int vm_swappiness = 60;
140d0480be4SWang Sheng-Hui /*
141d0480be4SWang Sheng-Hui  * The total number of pages which are beyond the high watermark within all
142d0480be4SWang Sheng-Hui  * zones.
143d0480be4SWang Sheng-Hui  */
144d0480be4SWang Sheng-Hui unsigned long vm_total_pages;
1451da177e4SLinus Torvalds 
1461da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1471da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1481da177e4SLinus Torvalds 
149c255a458SAndrew Morton #ifdef CONFIG_MEMCG
15089b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
15189b5fae5SJohannes Weiner {
152f16015fbSJohannes Weiner 	return !sc->target_mem_cgroup;
15389b5fae5SJohannes Weiner }
15491a45470SKAMEZAWA Hiroyuki #else
15589b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
15689b5fae5SJohannes Weiner {
15789b5fae5SJohannes Weiner 	return true;
15889b5fae5SJohannes Weiner }
15991a45470SKAMEZAWA Hiroyuki #endif
16091a45470SKAMEZAWA Hiroyuki 
161a1c3bfb2SJohannes Weiner static unsigned long zone_reclaimable_pages(struct zone *zone)
1626e543d57SLisa Du {
1636e543d57SLisa Du 	int nr;
1646e543d57SLisa Du 
1656e543d57SLisa Du 	nr = zone_page_state(zone, NR_ACTIVE_FILE) +
1666e543d57SLisa Du 	     zone_page_state(zone, NR_INACTIVE_FILE);
1676e543d57SLisa Du 
1686e543d57SLisa Du 	if (get_nr_swap_pages() > 0)
1696e543d57SLisa Du 		nr += zone_page_state(zone, NR_ACTIVE_ANON) +
1706e543d57SLisa Du 		      zone_page_state(zone, NR_INACTIVE_ANON);
1716e543d57SLisa Du 
1726e543d57SLisa Du 	return nr;
1736e543d57SLisa Du }
1746e543d57SLisa Du 
1756e543d57SLisa Du bool zone_reclaimable(struct zone *zone)
1766e543d57SLisa Du {
1770d5d823aSMel Gorman 	return zone_page_state(zone, NR_PAGES_SCANNED) <
1780d5d823aSMel Gorman 		zone_reclaimable_pages(zone) * 6;
1796e543d57SLisa Du }
1806e543d57SLisa Du 
1814d7dcca2SHugh Dickins static unsigned long get_lru_size(struct lruvec *lruvec, enum lru_list lru)
182c9f299d9SKOSAKI Motohiro {
183c3c787e8SHugh Dickins 	if (!mem_cgroup_disabled())
1844d7dcca2SHugh Dickins 		return mem_cgroup_get_lru_size(lruvec, lru);
185a3d8e054SKOSAKI Motohiro 
186074291feSKonstantin Khlebnikov 	return zone_page_state(lruvec_zone(lruvec), NR_LRU_BASE + lru);
187c9f299d9SKOSAKI Motohiro }
188c9f299d9SKOSAKI Motohiro 
1891da177e4SLinus Torvalds /*
1901d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
1911da177e4SLinus Torvalds  */
1921d3d4437SGlauber Costa int register_shrinker(struct shrinker *shrinker)
1931da177e4SLinus Torvalds {
1941d3d4437SGlauber Costa 	size_t size = sizeof(*shrinker->nr_deferred);
1951d3d4437SGlauber Costa 
1961d3d4437SGlauber Costa 	/*
1971d3d4437SGlauber Costa 	 * If we only have one possible node in the system anyway, save
1981d3d4437SGlauber Costa 	 * ourselves the trouble and disable NUMA aware behavior. This way we
1991d3d4437SGlauber Costa 	 * will save memory and some small loop time later.
2001d3d4437SGlauber Costa 	 */
2011d3d4437SGlauber Costa 	if (nr_node_ids == 1)
2021d3d4437SGlauber Costa 		shrinker->flags &= ~SHRINKER_NUMA_AWARE;
2031d3d4437SGlauber Costa 
2041d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
2051d3d4437SGlauber Costa 		size *= nr_node_ids;
2061d3d4437SGlauber Costa 
2071d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
2081d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
2091d3d4437SGlauber Costa 		return -ENOMEM;
2101d3d4437SGlauber Costa 
2111da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2121da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
2131da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
2141d3d4437SGlauber Costa 	return 0;
2151da177e4SLinus Torvalds }
2168e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
2171da177e4SLinus Torvalds 
2181da177e4SLinus Torvalds /*
2191da177e4SLinus Torvalds  * Remove one
2201da177e4SLinus Torvalds  */
2218e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
2221da177e4SLinus Torvalds {
2231da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2241da177e4SLinus Torvalds 	list_del(&shrinker->list);
2251da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
226ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
2271da177e4SLinus Torvalds }
2288e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
2291da177e4SLinus Torvalds 
2301da177e4SLinus Torvalds #define SHRINK_BATCH 128
2311d3d4437SGlauber Costa 
2321d3d4437SGlauber Costa static unsigned long
2331d3d4437SGlauber Costa shrink_slab_node(struct shrink_control *shrinkctl, struct shrinker *shrinker,
2341d3d4437SGlauber Costa 		 unsigned long nr_pages_scanned, unsigned long lru_pages)
2351da177e4SLinus Torvalds {
23624f7c6b9SDave Chinner 	unsigned long freed = 0;
2371da177e4SLinus Torvalds 	unsigned long long delta;
238635697c6SKonstantin Khlebnikov 	long total_scan;
239d5bc5fd3SVladimir Davydov 	long freeable;
240acf92b48SDave Chinner 	long nr;
241acf92b48SDave Chinner 	long new_nr;
2421d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
243e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
244e9299f50SDave Chinner 					  : SHRINK_BATCH;
2451da177e4SLinus Torvalds 
246d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
247d5bc5fd3SVladimir Davydov 	if (freeable == 0)
2481d3d4437SGlauber Costa 		return 0;
249635697c6SKonstantin Khlebnikov 
250acf92b48SDave Chinner 	/*
251acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
252acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
253acf92b48SDave Chinner 	 * don't also do this scanning work.
254acf92b48SDave Chinner 	 */
2551d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
256acf92b48SDave Chinner 
257acf92b48SDave Chinner 	total_scan = nr;
2581495f230SYing Han 	delta = (4 * nr_pages_scanned) / shrinker->seeks;
259d5bc5fd3SVladimir Davydov 	delta *= freeable;
2601da177e4SLinus Torvalds 	do_div(delta, lru_pages + 1);
261acf92b48SDave Chinner 	total_scan += delta;
262acf92b48SDave Chinner 	if (total_scan < 0) {
263*8612c663SPintu Kumar 		pr_err("shrink_slab: %pF negative objects to delete nr=%ld\n",
264a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
265d5bc5fd3SVladimir Davydov 		total_scan = freeable;
266ea164d73SAndrea Arcangeli 	}
267ea164d73SAndrea Arcangeli 
268ea164d73SAndrea Arcangeli 	/*
2693567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
2703567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
2713567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
2723567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
2733567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
274d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
2753567b59aSDave Chinner 	 * memory.
2763567b59aSDave Chinner 	 *
2773567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
2783567b59aSDave Chinner 	 * a large delta change is calculated directly.
2793567b59aSDave Chinner 	 */
280d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
281d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
2823567b59aSDave Chinner 
2833567b59aSDave Chinner 	/*
284ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
285ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
286ea164d73SAndrea Arcangeli 	 * freeable entries.
287ea164d73SAndrea Arcangeli 	 */
288d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
289d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
2901da177e4SLinus Torvalds 
29124f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
29209576073SDave Chinner 				nr_pages_scanned, lru_pages,
293d5bc5fd3SVladimir Davydov 				freeable, delta, total_scan);
29409576073SDave Chinner 
2950b1fb40aSVladimir Davydov 	/*
2960b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
2970b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
2980b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
2990b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
3000b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
3010b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
3020b1fb40aSVladimir Davydov 	 * batch_size.
3030b1fb40aSVladimir Davydov 	 *
3040b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
3050b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
306d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
3070b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
3080b1fb40aSVladimir Davydov 	 * possible.
3090b1fb40aSVladimir Davydov 	 */
3100b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
311d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
31224f7c6b9SDave Chinner 		unsigned long ret;
3130b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
3141da177e4SLinus Torvalds 
3150b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
31624f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
31724f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
3181da177e4SLinus Torvalds 			break;
31924f7c6b9SDave Chinner 		freed += ret;
32024f7c6b9SDave Chinner 
3210b1fb40aSVladimir Davydov 		count_vm_events(SLABS_SCANNED, nr_to_scan);
3220b1fb40aSVladimir Davydov 		total_scan -= nr_to_scan;
3231da177e4SLinus Torvalds 
3241da177e4SLinus Torvalds 		cond_resched();
3251da177e4SLinus Torvalds 	}
3261da177e4SLinus Torvalds 
327acf92b48SDave Chinner 	/*
328acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
329acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
330acf92b48SDave Chinner 	 * scan, there is no need to do an update.
331acf92b48SDave Chinner 	 */
33283aeeadaSKonstantin Khlebnikov 	if (total_scan > 0)
33383aeeadaSKonstantin Khlebnikov 		new_nr = atomic_long_add_return(total_scan,
3341d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
33583aeeadaSKonstantin Khlebnikov 	else
3361d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
337acf92b48SDave Chinner 
338df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
3391d3d4437SGlauber Costa 	return freed;
3401d3d4437SGlauber Costa }
3411d3d4437SGlauber Costa 
3421d3d4437SGlauber Costa /*
3431d3d4437SGlauber Costa  * Call the shrink functions to age shrinkable caches
3441d3d4437SGlauber Costa  *
3451d3d4437SGlauber Costa  * Here we assume it costs one seek to replace a lru page and that it also
3461d3d4437SGlauber Costa  * takes a seek to recreate a cache object.  With this in mind we age equal
3471d3d4437SGlauber Costa  * percentages of the lru and ageable caches.  This should balance the seeks
3481d3d4437SGlauber Costa  * generated by these structures.
3491d3d4437SGlauber Costa  *
3501d3d4437SGlauber Costa  * If the vm encountered mapped pages on the LRU it increase the pressure on
3511d3d4437SGlauber Costa  * slab to avoid swapping.
3521d3d4437SGlauber Costa  *
3531d3d4437SGlauber Costa  * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
3541d3d4437SGlauber Costa  *
3551d3d4437SGlauber Costa  * `lru_pages' represents the number of on-LRU pages in all the zones which
3561d3d4437SGlauber Costa  * are eligible for the caller's allocation attempt.  It is used for balancing
3571d3d4437SGlauber Costa  * slab reclaim versus page reclaim.
3581d3d4437SGlauber Costa  *
3591d3d4437SGlauber Costa  * Returns the number of slab objects which we shrunk.
3601d3d4437SGlauber Costa  */
3611d3d4437SGlauber Costa unsigned long shrink_slab(struct shrink_control *shrinkctl,
3621d3d4437SGlauber Costa 			  unsigned long nr_pages_scanned,
3631d3d4437SGlauber Costa 			  unsigned long lru_pages)
3641d3d4437SGlauber Costa {
3651d3d4437SGlauber Costa 	struct shrinker *shrinker;
3661d3d4437SGlauber Costa 	unsigned long freed = 0;
3671d3d4437SGlauber Costa 
3681d3d4437SGlauber Costa 	if (nr_pages_scanned == 0)
3691d3d4437SGlauber Costa 		nr_pages_scanned = SWAP_CLUSTER_MAX;
3701d3d4437SGlauber Costa 
3711d3d4437SGlauber Costa 	if (!down_read_trylock(&shrinker_rwsem)) {
3721d3d4437SGlauber Costa 		/*
3731d3d4437SGlauber Costa 		 * If we would return 0, our callers would understand that we
3741d3d4437SGlauber Costa 		 * have nothing else to shrink and give up trying. By returning
3751d3d4437SGlauber Costa 		 * 1 we keep it going and assume we'll be able to shrink next
3761d3d4437SGlauber Costa 		 * time.
3771d3d4437SGlauber Costa 		 */
3781d3d4437SGlauber Costa 		freed = 1;
3791d3d4437SGlauber Costa 		goto out;
3801d3d4437SGlauber Costa 	}
3811d3d4437SGlauber Costa 
3821d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
383ec97097bSVladimir Davydov 		if (!(shrinker->flags & SHRINKER_NUMA_AWARE)) {
384ec97097bSVladimir Davydov 			shrinkctl->nid = 0;
385ec97097bSVladimir Davydov 			freed += shrink_slab_node(shrinkctl, shrinker,
386ec97097bSVladimir Davydov 					nr_pages_scanned, lru_pages);
3871d3d4437SGlauber Costa 			continue;
388ec97097bSVladimir Davydov 		}
3891d3d4437SGlauber Costa 
390ec97097bSVladimir Davydov 		for_each_node_mask(shrinkctl->nid, shrinkctl->nodes_to_scan) {
391ec97097bSVladimir Davydov 			if (node_online(shrinkctl->nid))
3921d3d4437SGlauber Costa 				freed += shrink_slab_node(shrinkctl, shrinker,
3931d3d4437SGlauber Costa 						nr_pages_scanned, lru_pages);
3941d3d4437SGlauber Costa 
3951d3d4437SGlauber Costa 		}
3961da177e4SLinus Torvalds 	}
3971da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
398f06590bdSMinchan Kim out:
399f06590bdSMinchan Kim 	cond_resched();
40024f7c6b9SDave Chinner 	return freed;
4011da177e4SLinus Torvalds }
4021da177e4SLinus Torvalds 
4031da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
4041da177e4SLinus Torvalds {
405ceddc3a5SJohannes Weiner 	/*
406ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
407ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
408ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
409ceddc3a5SJohannes Weiner 	 */
410edcf4748SJohannes Weiner 	return page_count(page) - page_has_private(page) == 2;
4111da177e4SLinus Torvalds }
4121da177e4SLinus Torvalds 
4137d3579e8SKOSAKI Motohiro static int may_write_to_queue(struct backing_dev_info *bdi,
4147d3579e8SKOSAKI Motohiro 			      struct scan_control *sc)
4151da177e4SLinus Torvalds {
416930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
4171da177e4SLinus Torvalds 		return 1;
4181da177e4SLinus Torvalds 	if (!bdi_write_congested(bdi))
4191da177e4SLinus Torvalds 		return 1;
4201da177e4SLinus Torvalds 	if (bdi == current->backing_dev_info)
4211da177e4SLinus Torvalds 		return 1;
4221da177e4SLinus Torvalds 	return 0;
4231da177e4SLinus Torvalds }
4241da177e4SLinus Torvalds 
4251da177e4SLinus Torvalds /*
4261da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
4271da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
4281da177e4SLinus Torvalds  * fsync(), msync() or close().
4291da177e4SLinus Torvalds  *
4301da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
4311da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
4321da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
4331da177e4SLinus Torvalds  *
4341da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
4351da177e4SLinus Torvalds  * __GFP_FS.
4361da177e4SLinus Torvalds  */
4371da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
4381da177e4SLinus Torvalds 				struct page *page, int error)
4391da177e4SLinus Torvalds {
4407eaceaccSJens Axboe 	lock_page(page);
4413e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
4423e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
4431da177e4SLinus Torvalds 	unlock_page(page);
4441da177e4SLinus Torvalds }
4451da177e4SLinus Torvalds 
44604e62a29SChristoph Lameter /* possible outcome of pageout() */
44704e62a29SChristoph Lameter typedef enum {
44804e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
44904e62a29SChristoph Lameter 	PAGE_KEEP,
45004e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
45104e62a29SChristoph Lameter 	PAGE_ACTIVATE,
45204e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
45304e62a29SChristoph Lameter 	PAGE_SUCCESS,
45404e62a29SChristoph Lameter 	/* page is clean and locked */
45504e62a29SChristoph Lameter 	PAGE_CLEAN,
45604e62a29SChristoph Lameter } pageout_t;
45704e62a29SChristoph Lameter 
4581da177e4SLinus Torvalds /*
4591742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
4601742f19fSAndrew Morton  * Calls ->writepage().
4611da177e4SLinus Torvalds  */
462c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
4637d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
4641da177e4SLinus Torvalds {
4651da177e4SLinus Torvalds 	/*
4661da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
4671da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
4681da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
4691da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
4701da177e4SLinus Torvalds 	 * PagePrivate for that.
4711da177e4SLinus Torvalds 	 *
4728174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
4731da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
4741da177e4SLinus Torvalds 	 * will block.
4751da177e4SLinus Torvalds 	 *
4761da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
4771da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
4781da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
4791da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
4801da177e4SLinus Torvalds 	 */
4811da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
4821da177e4SLinus Torvalds 		return PAGE_KEEP;
4831da177e4SLinus Torvalds 	if (!mapping) {
4841da177e4SLinus Torvalds 		/*
4851da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
4861da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
4871da177e4SLinus Torvalds 		 */
488266cf658SDavid Howells 		if (page_has_private(page)) {
4891da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
4901da177e4SLinus Torvalds 				ClearPageDirty(page);
491b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
4921da177e4SLinus Torvalds 				return PAGE_CLEAN;
4931da177e4SLinus Torvalds 			}
4941da177e4SLinus Torvalds 		}
4951da177e4SLinus Torvalds 		return PAGE_KEEP;
4961da177e4SLinus Torvalds 	}
4971da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
4981da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
4990e093d99SMel Gorman 	if (!may_write_to_queue(mapping->backing_dev_info, sc))
5001da177e4SLinus Torvalds 		return PAGE_KEEP;
5011da177e4SLinus Torvalds 
5021da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
5031da177e4SLinus Torvalds 		int res;
5041da177e4SLinus Torvalds 		struct writeback_control wbc = {
5051da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
5061da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
507111ebb6eSOGAWA Hirofumi 			.range_start = 0,
508111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
5091da177e4SLinus Torvalds 			.for_reclaim = 1,
5101da177e4SLinus Torvalds 		};
5111da177e4SLinus Torvalds 
5121da177e4SLinus Torvalds 		SetPageReclaim(page);
5131da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
5141da177e4SLinus Torvalds 		if (res < 0)
5151da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
516994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
5171da177e4SLinus Torvalds 			ClearPageReclaim(page);
5181da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
5191da177e4SLinus Torvalds 		}
520c661b078SAndy Whitcroft 
5211da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
5221da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
5231da177e4SLinus Torvalds 			ClearPageReclaim(page);
5241da177e4SLinus Torvalds 		}
52523b9da55SMel Gorman 		trace_mm_vmscan_writepage(page, trace_reclaim_flags(page));
526e129b5c2SAndrew Morton 		inc_zone_page_state(page, NR_VMSCAN_WRITE);
5271da177e4SLinus Torvalds 		return PAGE_SUCCESS;
5281da177e4SLinus Torvalds 	}
5291da177e4SLinus Torvalds 
5301da177e4SLinus Torvalds 	return PAGE_CLEAN;
5311da177e4SLinus Torvalds }
5321da177e4SLinus Torvalds 
533a649fd92SAndrew Morton /*
534e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
535e286781dSNick Piggin  * gets returned with a refcount of 0.
536a649fd92SAndrew Morton  */
537a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
538a528910eSJohannes Weiner 			    bool reclaimed)
53949d2e9ccSChristoph Lameter {
54028e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
54128e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
54249d2e9ccSChristoph Lameter 
54319fd6231SNick Piggin 	spin_lock_irq(&mapping->tree_lock);
54449d2e9ccSChristoph Lameter 	/*
5450fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
5460fd0e6b0SNick Piggin 	 *
5470fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
5480fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
5490fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
5500fd0e6b0SNick Piggin 	 * here, then the following race may occur:
5510fd0e6b0SNick Piggin 	 *
5520fd0e6b0SNick Piggin 	 * get_user_pages(&page);
5530fd0e6b0SNick Piggin 	 * [user mapping goes away]
5540fd0e6b0SNick Piggin 	 * write_to(page);
5550fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
5560fd0e6b0SNick Piggin 	 * SetPageDirty(page);
5570fd0e6b0SNick Piggin 	 * put_page(page);
5580fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
5590fd0e6b0SNick Piggin 	 *
5600fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
5610fd0e6b0SNick Piggin 	 *
5620fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
5630fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
5640fd0e6b0SNick Piggin 	 * load is not satisfied before that of page->_count.
5650fd0e6b0SNick Piggin 	 *
5660fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
5670fd0e6b0SNick Piggin 	 * and thus under tree_lock, then this ordering is not required.
56849d2e9ccSChristoph Lameter 	 */
569e286781dSNick Piggin 	if (!page_freeze_refs(page, 2))
57049d2e9ccSChristoph Lameter 		goto cannot_free;
571e286781dSNick Piggin 	/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
572e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
573e286781dSNick Piggin 		page_unfreeze_refs(page, 2);
57449d2e9ccSChristoph Lameter 		goto cannot_free;
575e286781dSNick Piggin 	}
57649d2e9ccSChristoph Lameter 
57749d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
57849d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
5790a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
58049d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
58119fd6231SNick Piggin 		spin_unlock_irq(&mapping->tree_lock);
5820a31bc97SJohannes Weiner 		swapcache_free(swap);
583e286781dSNick Piggin 	} else {
5846072d13cSLinus Torvalds 		void (*freepage)(struct page *);
585a528910eSJohannes Weiner 		void *shadow = NULL;
5866072d13cSLinus Torvalds 
5876072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
588a528910eSJohannes Weiner 		/*
589a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
590a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
591a528910eSJohannes Weiner 		 *
592a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
593a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
594a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
595a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
596a528910eSJohannes Weiner 		 * back.
597a528910eSJohannes Weiner 		 */
598a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
599a528910eSJohannes Weiner 		    !mapping_exiting(mapping))
600a528910eSJohannes Weiner 			shadow = workingset_eviction(mapping, page);
601a528910eSJohannes Weiner 		__delete_from_page_cache(page, shadow);
60219fd6231SNick Piggin 		spin_unlock_irq(&mapping->tree_lock);
6036072d13cSLinus Torvalds 
6046072d13cSLinus Torvalds 		if (freepage != NULL)
6056072d13cSLinus Torvalds 			freepage(page);
606e286781dSNick Piggin 	}
607e286781dSNick Piggin 
60849d2e9ccSChristoph Lameter 	return 1;
60949d2e9ccSChristoph Lameter 
61049d2e9ccSChristoph Lameter cannot_free:
61119fd6231SNick Piggin 	spin_unlock_irq(&mapping->tree_lock);
61249d2e9ccSChristoph Lameter 	return 0;
61349d2e9ccSChristoph Lameter }
61449d2e9ccSChristoph Lameter 
6151da177e4SLinus Torvalds /*
616e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
617e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
618e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
619e286781dSNick Piggin  * this page.
620e286781dSNick Piggin  */
621e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
622e286781dSNick Piggin {
623a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
624e286781dSNick Piggin 		/*
625e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
626e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
627e286781dSNick Piggin 		 * atomic operation.
628e286781dSNick Piggin 		 */
629e286781dSNick Piggin 		page_unfreeze_refs(page, 1);
630e286781dSNick Piggin 		return 1;
631e286781dSNick Piggin 	}
632e286781dSNick Piggin 	return 0;
633e286781dSNick Piggin }
634e286781dSNick Piggin 
635894bc310SLee Schermerhorn /**
636894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
637894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
638894bc310SLee Schermerhorn  *
639894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
640894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
641894bc310SLee Schermerhorn  *
642894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
643894bc310SLee Schermerhorn  */
644894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
645894bc310SLee Schermerhorn {
6460ec3b74cSVlastimil Babka 	bool is_unevictable;
647bbfd28eeSLee Schermerhorn 	int was_unevictable = PageUnevictable(page);
648894bc310SLee Schermerhorn 
649309381feSSasha Levin 	VM_BUG_ON_PAGE(PageLRU(page), page);
650894bc310SLee Schermerhorn 
651894bc310SLee Schermerhorn redo:
652894bc310SLee Schermerhorn 	ClearPageUnevictable(page);
653894bc310SLee Schermerhorn 
65439b5f29aSHugh Dickins 	if (page_evictable(page)) {
655894bc310SLee Schermerhorn 		/*
656894bc310SLee Schermerhorn 		 * For evictable pages, we can use the cache.
657894bc310SLee Schermerhorn 		 * In event of a race, worst case is we end up with an
658894bc310SLee Schermerhorn 		 * unevictable page on [in]active list.
659894bc310SLee Schermerhorn 		 * We know how to handle that.
660894bc310SLee Schermerhorn 		 */
6610ec3b74cSVlastimil Babka 		is_unevictable = false;
662c53954a0SMel Gorman 		lru_cache_add(page);
663894bc310SLee Schermerhorn 	} else {
664894bc310SLee Schermerhorn 		/*
665894bc310SLee Schermerhorn 		 * Put unevictable pages directly on zone's unevictable
666894bc310SLee Schermerhorn 		 * list.
667894bc310SLee Schermerhorn 		 */
6680ec3b74cSVlastimil Babka 		is_unevictable = true;
669894bc310SLee Schermerhorn 		add_page_to_unevictable_list(page);
6706a7b9548SJohannes Weiner 		/*
67121ee9f39SMinchan Kim 		 * When racing with an mlock or AS_UNEVICTABLE clearing
67221ee9f39SMinchan Kim 		 * (page is unlocked) make sure that if the other thread
67321ee9f39SMinchan Kim 		 * does not observe our setting of PG_lru and fails
67424513264SHugh Dickins 		 * isolation/check_move_unevictable_pages,
67521ee9f39SMinchan Kim 		 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
6766a7b9548SJohannes Weiner 		 * the page back to the evictable list.
6776a7b9548SJohannes Weiner 		 *
67821ee9f39SMinchan Kim 		 * The other side is TestClearPageMlocked() or shmem_lock().
6796a7b9548SJohannes Weiner 		 */
6806a7b9548SJohannes Weiner 		smp_mb();
681894bc310SLee Schermerhorn 	}
682894bc310SLee Schermerhorn 
683894bc310SLee Schermerhorn 	/*
684894bc310SLee Schermerhorn 	 * page's status can change while we move it among lru. If an evictable
685894bc310SLee Schermerhorn 	 * page is on unevictable list, it never be freed. To avoid that,
686894bc310SLee Schermerhorn 	 * check after we added it to the list, again.
687894bc310SLee Schermerhorn 	 */
6880ec3b74cSVlastimil Babka 	if (is_unevictable && page_evictable(page)) {
689894bc310SLee Schermerhorn 		if (!isolate_lru_page(page)) {
690894bc310SLee Schermerhorn 			put_page(page);
691894bc310SLee Schermerhorn 			goto redo;
692894bc310SLee Schermerhorn 		}
693894bc310SLee Schermerhorn 		/* This means someone else dropped this page from LRU
694894bc310SLee Schermerhorn 		 * So, it will be freed or putback to LRU again. There is
695894bc310SLee Schermerhorn 		 * nothing to do here.
696894bc310SLee Schermerhorn 		 */
697894bc310SLee Schermerhorn 	}
698894bc310SLee Schermerhorn 
6990ec3b74cSVlastimil Babka 	if (was_unevictable && !is_unevictable)
700bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGRESCUED);
7010ec3b74cSVlastimil Babka 	else if (!was_unevictable && is_unevictable)
702bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGCULLED);
703bbfd28eeSLee Schermerhorn 
704894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
705894bc310SLee Schermerhorn }
706894bc310SLee Schermerhorn 
707dfc8d636SJohannes Weiner enum page_references {
708dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
709dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
71064574746SJohannes Weiner 	PAGEREF_KEEP,
711dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
712dfc8d636SJohannes Weiner };
713dfc8d636SJohannes Weiner 
714dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
715dfc8d636SJohannes Weiner 						  struct scan_control *sc)
716dfc8d636SJohannes Weiner {
71764574746SJohannes Weiner 	int referenced_ptes, referenced_page;
718dfc8d636SJohannes Weiner 	unsigned long vm_flags;
719dfc8d636SJohannes Weiner 
720c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
721c3ac9a8aSJohannes Weiner 					  &vm_flags);
72264574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
723dfc8d636SJohannes Weiner 
724dfc8d636SJohannes Weiner 	/*
725dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
726dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
727dfc8d636SJohannes Weiner 	 */
728dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
729dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
730dfc8d636SJohannes Weiner 
73164574746SJohannes Weiner 	if (referenced_ptes) {
732e4898273SMichal Hocko 		if (PageSwapBacked(page))
73364574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
73464574746SJohannes Weiner 		/*
73564574746SJohannes Weiner 		 * All mapped pages start out with page table
73664574746SJohannes Weiner 		 * references from the instantiating fault, so we need
73764574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
73864574746SJohannes Weiner 		 * than once.
73964574746SJohannes Weiner 		 *
74064574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
74164574746SJohannes Weiner 		 * inactive list.  Another page table reference will
74264574746SJohannes Weiner 		 * lead to its activation.
74364574746SJohannes Weiner 		 *
74464574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
74564574746SJohannes Weiner 		 * so that recently deactivated but used pages are
74664574746SJohannes Weiner 		 * quickly recovered.
74764574746SJohannes Weiner 		 */
74864574746SJohannes Weiner 		SetPageReferenced(page);
74964574746SJohannes Weiner 
75034dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
751dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
752dfc8d636SJohannes Weiner 
753c909e993SKonstantin Khlebnikov 		/*
754c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
755c909e993SKonstantin Khlebnikov 		 */
756c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
757c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
758c909e993SKonstantin Khlebnikov 
75964574746SJohannes Weiner 		return PAGEREF_KEEP;
76064574746SJohannes Weiner 	}
76164574746SJohannes Weiner 
762dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
7632e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
764dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
76564574746SJohannes Weiner 
76664574746SJohannes Weiner 	return PAGEREF_RECLAIM;
767dfc8d636SJohannes Weiner }
768dfc8d636SJohannes Weiner 
769e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
770e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
771e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
772e2be15f6SMel Gorman {
773b4597226SMel Gorman 	struct address_space *mapping;
774b4597226SMel Gorman 
775e2be15f6SMel Gorman 	/*
776e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
777e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
778e2be15f6SMel Gorman 	 */
779e2be15f6SMel Gorman 	if (!page_is_file_cache(page)) {
780e2be15f6SMel Gorman 		*dirty = false;
781e2be15f6SMel Gorman 		*writeback = false;
782e2be15f6SMel Gorman 		return;
783e2be15f6SMel Gorman 	}
784e2be15f6SMel Gorman 
785e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
786e2be15f6SMel Gorman 	*dirty = PageDirty(page);
787e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
788b4597226SMel Gorman 
789b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
790b4597226SMel Gorman 	if (!page_has_private(page))
791b4597226SMel Gorman 		return;
792b4597226SMel Gorman 
793b4597226SMel Gorman 	mapping = page_mapping(page);
794b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
795b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
796e2be15f6SMel Gorman }
797e2be15f6SMel Gorman 
798e286781dSNick Piggin /*
7991742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
8001da177e4SLinus Torvalds  */
8011742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
8026a18adb3SKonstantin Khlebnikov 				      struct zone *zone,
803f84f6e2bSMel Gorman 				      struct scan_control *sc,
80402c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
8058e950282SMel Gorman 				      unsigned long *ret_nr_dirty,
806d43006d5SMel Gorman 				      unsigned long *ret_nr_unqueued_dirty,
8078e950282SMel Gorman 				      unsigned long *ret_nr_congested,
80802c6de8dSMinchan Kim 				      unsigned long *ret_nr_writeback,
809b1a6f21eSMel Gorman 				      unsigned long *ret_nr_immediate,
81002c6de8dSMinchan Kim 				      bool force_reclaim)
8111da177e4SLinus Torvalds {
8121da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
813abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
8141da177e4SLinus Torvalds 	int pgactivate = 0;
815d43006d5SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
8160e093d99SMel Gorman 	unsigned long nr_dirty = 0;
8170e093d99SMel Gorman 	unsigned long nr_congested = 0;
81805ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
81992df3a72SMel Gorman 	unsigned long nr_writeback = 0;
820b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
8211da177e4SLinus Torvalds 
8221da177e4SLinus Torvalds 	cond_resched();
8231da177e4SLinus Torvalds 
8241da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
8251da177e4SLinus Torvalds 		struct address_space *mapping;
8261da177e4SLinus Torvalds 		struct page *page;
8271da177e4SLinus Torvalds 		int may_enter_fs;
82802c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
829e2be15f6SMel Gorman 		bool dirty, writeback;
8301da177e4SLinus Torvalds 
8311da177e4SLinus Torvalds 		cond_resched();
8321da177e4SLinus Torvalds 
8331da177e4SLinus Torvalds 		page = lru_to_page(page_list);
8341da177e4SLinus Torvalds 		list_del(&page->lru);
8351da177e4SLinus Torvalds 
836529ae9aaSNick Piggin 		if (!trylock_page(page))
8371da177e4SLinus Torvalds 			goto keep;
8381da177e4SLinus Torvalds 
839309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
840309381feSSasha Levin 		VM_BUG_ON_PAGE(page_zone(page) != zone, page);
8411da177e4SLinus Torvalds 
8421da177e4SLinus Torvalds 		sc->nr_scanned++;
84380e43426SChristoph Lameter 
84439b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
845b291f000SNick Piggin 			goto cull_mlocked;
846894bc310SLee Schermerhorn 
847a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
84880e43426SChristoph Lameter 			goto keep_locked;
84980e43426SChristoph Lameter 
8501da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
8511da177e4SLinus Torvalds 		if (page_mapped(page) || PageSwapCache(page))
8521da177e4SLinus Torvalds 			sc->nr_scanned++;
8531da177e4SLinus Torvalds 
854c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
855c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
856c661b078SAndy Whitcroft 
857e62e384eSMichal Hocko 		/*
858e2be15f6SMel Gorman 		 * The number of dirty pages determines if a zone is marked
859e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
860e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
861e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
862e2be15f6SMel Gorman 		 */
863e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
864e2be15f6SMel Gorman 		if (dirty || writeback)
865e2be15f6SMel Gorman 			nr_dirty++;
866e2be15f6SMel Gorman 
867e2be15f6SMel Gorman 		if (dirty && !writeback)
868e2be15f6SMel Gorman 			nr_unqueued_dirty++;
869e2be15f6SMel Gorman 
870d04e8acdSMel Gorman 		/*
871d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
872d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
873d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
874d04e8acdSMel Gorman 		 * end of the LRU a second time.
875d04e8acdSMel Gorman 		 */
876e2be15f6SMel Gorman 		mapping = page_mapping(page);
877d04e8acdSMel Gorman 		if ((mapping && bdi_write_congested(mapping->backing_dev_info)) ||
878d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
879e2be15f6SMel Gorman 			nr_congested++;
880e2be15f6SMel Gorman 
881e2be15f6SMel Gorman 		/*
882283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
883283aba9fSMel Gorman 		 * are three cases to consider.
884e62e384eSMichal Hocko 		 *
885283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
886283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
887283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
888283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
889283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
890283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
891283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
892b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
893b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
894c3b94f44SHugh Dickins 		 *
895283aba9fSMel Gorman 		 * 2) Global reclaim encounters a page, memcg encounters a
896283aba9fSMel Gorman 		 *    page that is not marked for immediate reclaim or
897283aba9fSMel Gorman 		 *    the caller does not have __GFP_IO. In this case mark
898283aba9fSMel Gorman 		 *    the page for immediate reclaim and continue scanning.
899283aba9fSMel Gorman 		 *
900283aba9fSMel Gorman 		 *    __GFP_IO is checked  because a loop driver thread might
901283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
902283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
903283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
904283aba9fSMel Gorman 		 *    would probably show more reasons.
905283aba9fSMel Gorman 		 *
906283aba9fSMel Gorman 		 *    Don't require __GFP_FS, since we're not going into the
907283aba9fSMel Gorman 		 *    FS, just waiting on its writeback completion. Worryingly,
908283aba9fSMel Gorman 		 *    ext4 gfs2 and xfs allocate pages with
909283aba9fSMel Gorman 		 *    grab_cache_page_write_begin(,,AOP_FLAG_NOFS), so testing
910283aba9fSMel Gorman 		 *    may_enter_fs here is liable to OOM on them.
911283aba9fSMel Gorman 		 *
912283aba9fSMel Gorman 		 * 3) memcg encounters a page that is not already marked
913283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
914283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
915283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
916283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
917e62e384eSMichal Hocko 		 */
918283aba9fSMel Gorman 		if (PageWriteback(page)) {
919283aba9fSMel Gorman 			/* Case 1 above */
920283aba9fSMel Gorman 			if (current_is_kswapd() &&
921283aba9fSMel Gorman 			    PageReclaim(page) &&
92257054651SJohannes Weiner 			    test_bit(ZONE_WRITEBACK, &zone->flags)) {
923b1a6f21eSMel Gorman 				nr_immediate++;
924b1a6f21eSMel Gorman 				goto keep_locked;
925283aba9fSMel Gorman 
926283aba9fSMel Gorman 			/* Case 2 above */
927283aba9fSMel Gorman 			} else if (global_reclaim(sc) ||
928c3b94f44SHugh Dickins 			    !PageReclaim(page) || !(sc->gfp_mask & __GFP_IO)) {
929c3b94f44SHugh Dickins 				/*
930c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
931c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
932c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
933c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
934c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
935c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
936c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
937c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
938c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
939c3b94f44SHugh Dickins 				 */
940c3b94f44SHugh Dickins 				SetPageReclaim(page);
94192df3a72SMel Gorman 				nr_writeback++;
942283aba9fSMel Gorman 
943c3b94f44SHugh Dickins 				goto keep_locked;
944283aba9fSMel Gorman 
945283aba9fSMel Gorman 			/* Case 3 above */
946283aba9fSMel Gorman 			} else {
947c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
948e62e384eSMichal Hocko 			}
949283aba9fSMel Gorman 		}
9501da177e4SLinus Torvalds 
95102c6de8dSMinchan Kim 		if (!force_reclaim)
9526a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
95302c6de8dSMinchan Kim 
954dfc8d636SJohannes Weiner 		switch (references) {
955dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
9561da177e4SLinus Torvalds 			goto activate_locked;
95764574746SJohannes Weiner 		case PAGEREF_KEEP:
95864574746SJohannes Weiner 			goto keep_locked;
959dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
960dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
961dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
962dfc8d636SJohannes Weiner 		}
9631da177e4SLinus Torvalds 
9641da177e4SLinus Torvalds 		/*
9651da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
9661da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
9671da177e4SLinus Torvalds 		 */
968b291f000SNick Piggin 		if (PageAnon(page) && !PageSwapCache(page)) {
96963eb6b93SHugh Dickins 			if (!(sc->gfp_mask & __GFP_IO))
97063eb6b93SHugh Dickins 				goto keep_locked;
9715bc7b8acSShaohua Li 			if (!add_to_swap(page, page_list))
9721da177e4SLinus Torvalds 				goto activate_locked;
97363eb6b93SHugh Dickins 			may_enter_fs = 1;
9741da177e4SLinus Torvalds 
975e2be15f6SMel Gorman 			/* Adding to swap updated mapping */
9761da177e4SLinus Torvalds 			mapping = page_mapping(page);
977e2be15f6SMel Gorman 		}
9781da177e4SLinus Torvalds 
9791da177e4SLinus Torvalds 		/*
9801da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
9811da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
9821da177e4SLinus Torvalds 		 */
9831da177e4SLinus Torvalds 		if (page_mapped(page) && mapping) {
98402c6de8dSMinchan Kim 			switch (try_to_unmap(page, ttu_flags)) {
9851da177e4SLinus Torvalds 			case SWAP_FAIL:
9861da177e4SLinus Torvalds 				goto activate_locked;
9871da177e4SLinus Torvalds 			case SWAP_AGAIN:
9881da177e4SLinus Torvalds 				goto keep_locked;
989b291f000SNick Piggin 			case SWAP_MLOCK:
990b291f000SNick Piggin 				goto cull_mlocked;
9911da177e4SLinus Torvalds 			case SWAP_SUCCESS:
9921da177e4SLinus Torvalds 				; /* try to free the page below */
9931da177e4SLinus Torvalds 			}
9941da177e4SLinus Torvalds 		}
9951da177e4SLinus Torvalds 
9961da177e4SLinus Torvalds 		if (PageDirty(page)) {
997ee72886dSMel Gorman 			/*
998ee72886dSMel Gorman 			 * Only kswapd can writeback filesystem pages to
999d43006d5SMel Gorman 			 * avoid risk of stack overflow but only writeback
1000d43006d5SMel Gorman 			 * if many dirty pages have been encountered.
1001ee72886dSMel Gorman 			 */
1002f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
10039e3b2f8cSKonstantin Khlebnikov 					(!current_is_kswapd() ||
100457054651SJohannes Weiner 					 !test_bit(ZONE_DIRTY, &zone->flags))) {
100549ea7eb6SMel Gorman 				/*
100649ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
100749ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
100849ea7eb6SMel Gorman 				 * except we already have the page isolated
100949ea7eb6SMel Gorman 				 * and know it's dirty
101049ea7eb6SMel Gorman 				 */
101149ea7eb6SMel Gorman 				inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE);
101249ea7eb6SMel Gorman 				SetPageReclaim(page);
101349ea7eb6SMel Gorman 
1014ee72886dSMel Gorman 				goto keep_locked;
1015ee72886dSMel Gorman 			}
1016ee72886dSMel Gorman 
1017dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
10181da177e4SLinus Torvalds 				goto keep_locked;
10194dd4b920SAndrew Morton 			if (!may_enter_fs)
10201da177e4SLinus Torvalds 				goto keep_locked;
102152a8363eSChristoph Lameter 			if (!sc->may_writepage)
10221da177e4SLinus Torvalds 				goto keep_locked;
10231da177e4SLinus Torvalds 
10241da177e4SLinus Torvalds 			/* Page is dirty, try to write it out here */
10257d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
10261da177e4SLinus Torvalds 			case PAGE_KEEP:
10271da177e4SLinus Torvalds 				goto keep_locked;
10281da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
10291da177e4SLinus Torvalds 				goto activate_locked;
10301da177e4SLinus Torvalds 			case PAGE_SUCCESS:
10317d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
103241ac1999SMel Gorman 					goto keep;
10337d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
10341da177e4SLinus Torvalds 					goto keep;
10357d3579e8SKOSAKI Motohiro 
10361da177e4SLinus Torvalds 				/*
10371da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
10381da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
10391da177e4SLinus Torvalds 				 */
1040529ae9aaSNick Piggin 				if (!trylock_page(page))
10411da177e4SLinus Torvalds 					goto keep;
10421da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
10431da177e4SLinus Torvalds 					goto keep_locked;
10441da177e4SLinus Torvalds 				mapping = page_mapping(page);
10451da177e4SLinus Torvalds 			case PAGE_CLEAN:
10461da177e4SLinus Torvalds 				; /* try to free the page below */
10471da177e4SLinus Torvalds 			}
10481da177e4SLinus Torvalds 		}
10491da177e4SLinus Torvalds 
10501da177e4SLinus Torvalds 		/*
10511da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
10521da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
10531da177e4SLinus Torvalds 		 * the page as well.
10541da177e4SLinus Torvalds 		 *
10551da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
10561da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
10571da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
10581da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
10591da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
10601da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
10611da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
10621da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
10631da177e4SLinus Torvalds 		 *
10641da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
10651da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
10661da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
10671da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
10681da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
10691da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
10701da177e4SLinus Torvalds 		 */
1071266cf658SDavid Howells 		if (page_has_private(page)) {
10721da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
10731da177e4SLinus Torvalds 				goto activate_locked;
1074e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1075e286781dSNick Piggin 				unlock_page(page);
1076e286781dSNick Piggin 				if (put_page_testzero(page))
10771da177e4SLinus Torvalds 					goto free_it;
1078e286781dSNick Piggin 				else {
1079e286781dSNick Piggin 					/*
1080e286781dSNick Piggin 					 * rare race with speculative reference.
1081e286781dSNick Piggin 					 * the speculative reference will free
1082e286781dSNick Piggin 					 * this page shortly, so we may
1083e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1084e286781dSNick Piggin 					 * leave it off the LRU).
1085e286781dSNick Piggin 					 */
1086e286781dSNick Piggin 					nr_reclaimed++;
1087e286781dSNick Piggin 					continue;
1088e286781dSNick Piggin 				}
1089e286781dSNick Piggin 			}
10901da177e4SLinus Torvalds 		}
10911da177e4SLinus Torvalds 
1092a528910eSJohannes Weiner 		if (!mapping || !__remove_mapping(mapping, page, true))
109349d2e9ccSChristoph Lameter 			goto keep_locked;
10941da177e4SLinus Torvalds 
1095a978d6f5SNick Piggin 		/*
1096a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
1097a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
1098a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
1099a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
1100a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
1101a978d6f5SNick Piggin 		 */
1102a978d6f5SNick Piggin 		__clear_page_locked(page);
1103e286781dSNick Piggin free_it:
110405ff5137SAndrew Morton 		nr_reclaimed++;
1105abe4c3b5SMel Gorman 
1106abe4c3b5SMel Gorman 		/*
1107abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1108abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1109abe4c3b5SMel Gorman 		 */
1110abe4c3b5SMel Gorman 		list_add(&page->lru, &free_pages);
11111da177e4SLinus Torvalds 		continue;
11121da177e4SLinus Torvalds 
1113b291f000SNick Piggin cull_mlocked:
111463d6c5adSHugh Dickins 		if (PageSwapCache(page))
111563d6c5adSHugh Dickins 			try_to_free_swap(page);
1116b291f000SNick Piggin 		unlock_page(page);
1117b291f000SNick Piggin 		putback_lru_page(page);
1118b291f000SNick Piggin 		continue;
1119b291f000SNick Piggin 
11201da177e4SLinus Torvalds activate_locked:
112168a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
112268a22394SRik van Riel 		if (PageSwapCache(page) && vm_swap_full())
1123a2c43eedSHugh Dickins 			try_to_free_swap(page);
1124309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
11251da177e4SLinus Torvalds 		SetPageActive(page);
11261da177e4SLinus Torvalds 		pgactivate++;
11271da177e4SLinus Torvalds keep_locked:
11281da177e4SLinus Torvalds 		unlock_page(page);
11291da177e4SLinus Torvalds keep:
11301da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1131309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
11321da177e4SLinus Torvalds 	}
1133abe4c3b5SMel Gorman 
1134747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
1135b745bc85SMel Gorman 	free_hot_cold_page_list(&free_pages, true);
1136abe4c3b5SMel Gorman 
11371da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1138f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
11390a31bc97SJohannes Weiner 
11408e950282SMel Gorman 	*ret_nr_dirty += nr_dirty;
11418e950282SMel Gorman 	*ret_nr_congested += nr_congested;
1142d43006d5SMel Gorman 	*ret_nr_unqueued_dirty += nr_unqueued_dirty;
114392df3a72SMel Gorman 	*ret_nr_writeback += nr_writeback;
1144b1a6f21eSMel Gorman 	*ret_nr_immediate += nr_immediate;
114505ff5137SAndrew Morton 	return nr_reclaimed;
11461da177e4SLinus Torvalds }
11471da177e4SLinus Torvalds 
114802c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
114902c6de8dSMinchan Kim 					    struct list_head *page_list)
115002c6de8dSMinchan Kim {
115102c6de8dSMinchan Kim 	struct scan_control sc = {
115202c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
115302c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
115402c6de8dSMinchan Kim 		.may_unmap = 1,
115502c6de8dSMinchan Kim 	};
11568e950282SMel Gorman 	unsigned long ret, dummy1, dummy2, dummy3, dummy4, dummy5;
115702c6de8dSMinchan Kim 	struct page *page, *next;
115802c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
115902c6de8dSMinchan Kim 
116002c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1161117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1162117aad1eSRafael Aquini 		    !isolated_balloon_page(page)) {
116302c6de8dSMinchan Kim 			ClearPageActive(page);
116402c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
116502c6de8dSMinchan Kim 		}
116602c6de8dSMinchan Kim 	}
116702c6de8dSMinchan Kim 
116802c6de8dSMinchan Kim 	ret = shrink_page_list(&clean_pages, zone, &sc,
116902c6de8dSMinchan Kim 			TTU_UNMAP|TTU_IGNORE_ACCESS,
11708e950282SMel Gorman 			&dummy1, &dummy2, &dummy3, &dummy4, &dummy5, true);
117102c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
117283da7510SChristoph Lameter 	mod_zone_page_state(zone, NR_ISOLATED_FILE, -ret);
117302c6de8dSMinchan Kim 	return ret;
117402c6de8dSMinchan Kim }
117502c6de8dSMinchan Kim 
11765ad333ebSAndy Whitcroft /*
11775ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
11785ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
11795ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
11805ad333ebSAndy Whitcroft  *
11815ad333ebSAndy Whitcroft  * page:	page to consider
11825ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
11835ad333ebSAndy Whitcroft  *
11845ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
11855ad333ebSAndy Whitcroft  */
1186f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
11875ad333ebSAndy Whitcroft {
11885ad333ebSAndy Whitcroft 	int ret = -EINVAL;
11895ad333ebSAndy Whitcroft 
11905ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
11915ad333ebSAndy Whitcroft 	if (!PageLRU(page))
11925ad333ebSAndy Whitcroft 		return ret;
11935ad333ebSAndy Whitcroft 
1194e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1195e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1196894bc310SLee Schermerhorn 		return ret;
1197894bc310SLee Schermerhorn 
11985ad333ebSAndy Whitcroft 	ret = -EBUSY;
119908e552c6SKAMEZAWA Hiroyuki 
1200c8244935SMel Gorman 	/*
1201c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1202c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1203c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1204c8244935SMel Gorman 	 *
1205c8244935SMel Gorman 	 * ISOLATE_CLEAN means that only clean pages should be isolated. This
1206c8244935SMel Gorman 	 * is used by reclaim when it is cannot write to backing storage
1207c8244935SMel Gorman 	 *
1208c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1209c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1210c8244935SMel Gorman 	 */
1211c8244935SMel Gorman 	if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
1212c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1213c8244935SMel Gorman 		if (PageWriteback(page))
121439deaf85SMinchan Kim 			return ret;
121539deaf85SMinchan Kim 
1216c8244935SMel Gorman 		if (PageDirty(page)) {
1217c8244935SMel Gorman 			struct address_space *mapping;
1218c8244935SMel Gorman 
1219c8244935SMel Gorman 			/* ISOLATE_CLEAN means only clean pages */
1220c8244935SMel Gorman 			if (mode & ISOLATE_CLEAN)
1221c8244935SMel Gorman 				return ret;
1222c8244935SMel Gorman 
1223c8244935SMel Gorman 			/*
1224c8244935SMel Gorman 			 * Only pages without mappings or that have a
1225c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
1226c8244935SMel Gorman 			 * without blocking
1227c8244935SMel Gorman 			 */
1228c8244935SMel Gorman 			mapping = page_mapping(page);
1229c8244935SMel Gorman 			if (mapping && !mapping->a_ops->migratepage)
1230c8244935SMel Gorman 				return ret;
1231c8244935SMel Gorman 		}
1232c8244935SMel Gorman 	}
1233c8244935SMel Gorman 
1234f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1235f80c0673SMinchan Kim 		return ret;
1236f80c0673SMinchan Kim 
12375ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
12385ad333ebSAndy Whitcroft 		/*
12395ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
12405ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
12415ad333ebSAndy Whitcroft 		 * page release code relies on it.
12425ad333ebSAndy Whitcroft 		 */
12435ad333ebSAndy Whitcroft 		ClearPageLRU(page);
12445ad333ebSAndy Whitcroft 		ret = 0;
12455ad333ebSAndy Whitcroft 	}
12465ad333ebSAndy Whitcroft 
12475ad333ebSAndy Whitcroft 	return ret;
12485ad333ebSAndy Whitcroft }
12495ad333ebSAndy Whitcroft 
125049d2e9ccSChristoph Lameter /*
12511da177e4SLinus Torvalds  * zone->lru_lock is heavily contended.  Some of the functions that
12521da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
12531da177e4SLinus Torvalds  * and working on them outside the LRU lock.
12541da177e4SLinus Torvalds  *
12551da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
12561da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
12571da177e4SLinus Torvalds  *
12581da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
12591da177e4SLinus Torvalds  *
12601da177e4SLinus Torvalds  * @nr_to_scan:	The number of pages to look through on the list.
12615dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
12621da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1263f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1264fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
12655ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
12663cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
12671da177e4SLinus Torvalds  *
12681da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
12691da177e4SLinus Torvalds  */
127069e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
12715dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1272fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
12733cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
12741da177e4SLinus Torvalds {
127575b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
127669e05944SAndrew Morton 	unsigned long nr_taken = 0;
1277c9b02d97SWu Fengguang 	unsigned long scan;
12781da177e4SLinus Torvalds 
1279c9b02d97SWu Fengguang 	for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
12805ad333ebSAndy Whitcroft 		struct page *page;
1281fa9add64SHugh Dickins 		int nr_pages;
12825ad333ebSAndy Whitcroft 
12831da177e4SLinus Torvalds 		page = lru_to_page(src);
12841da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
12851da177e4SLinus Torvalds 
1286309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
12878d438f96SNick Piggin 
1288f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
12895ad333ebSAndy Whitcroft 		case 0:
1290fa9add64SHugh Dickins 			nr_pages = hpage_nr_pages(page);
1291fa9add64SHugh Dickins 			mem_cgroup_update_lru_size(lruvec, lru, -nr_pages);
12925ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
1293fa9add64SHugh Dickins 			nr_taken += nr_pages;
12945ad333ebSAndy Whitcroft 			break;
12957c8ee9a8SNick Piggin 
12965ad333ebSAndy Whitcroft 		case -EBUSY:
12975ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
12985ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
12995ad333ebSAndy Whitcroft 			continue;
13005ad333ebSAndy Whitcroft 
13015ad333ebSAndy Whitcroft 		default:
13025ad333ebSAndy Whitcroft 			BUG();
13035ad333ebSAndy Whitcroft 		}
13045ad333ebSAndy Whitcroft 	}
13051da177e4SLinus Torvalds 
1306f626012dSHugh Dickins 	*nr_scanned = scan;
130775b00af7SHugh Dickins 	trace_mm_vmscan_lru_isolate(sc->order, nr_to_scan, scan,
130875b00af7SHugh Dickins 				    nr_taken, mode, is_file_lru(lru));
13091da177e4SLinus Torvalds 	return nr_taken;
13101da177e4SLinus Torvalds }
13111da177e4SLinus Torvalds 
131262695a84SNick Piggin /**
131362695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
131462695a84SNick Piggin  * @page: page to isolate from its LRU list
131562695a84SNick Piggin  *
131662695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
131762695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
131862695a84SNick Piggin  *
131962695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
132062695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
132162695a84SNick Piggin  *
132262695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1323894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1324894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1325894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
132662695a84SNick Piggin  *
132762695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
132862695a84SNick Piggin  * found will be decremented.
132962695a84SNick Piggin  *
133062695a84SNick Piggin  * Restrictions:
133162695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
133262695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
133362695a84SNick Piggin  *     without a stable reference).
133462695a84SNick Piggin  * (2) the lru_lock must not be held.
133562695a84SNick Piggin  * (3) interrupts must be enabled.
133662695a84SNick Piggin  */
133762695a84SNick Piggin int isolate_lru_page(struct page *page)
133862695a84SNick Piggin {
133962695a84SNick Piggin 	int ret = -EBUSY;
134062695a84SNick Piggin 
1341309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
13420c917313SKonstantin Khlebnikov 
134362695a84SNick Piggin 	if (PageLRU(page)) {
134462695a84SNick Piggin 		struct zone *zone = page_zone(page);
1345fa9add64SHugh Dickins 		struct lruvec *lruvec;
134662695a84SNick Piggin 
134762695a84SNick Piggin 		spin_lock_irq(&zone->lru_lock);
1348fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
13490c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1350894bc310SLee Schermerhorn 			int lru = page_lru(page);
13510c917313SKonstantin Khlebnikov 			get_page(page);
135262695a84SNick Piggin 			ClearPageLRU(page);
1353fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1354fa9add64SHugh Dickins 			ret = 0;
135562695a84SNick Piggin 		}
135662695a84SNick Piggin 		spin_unlock_irq(&zone->lru_lock);
135762695a84SNick Piggin 	}
135862695a84SNick Piggin 	return ret;
135962695a84SNick Piggin }
136062695a84SNick Piggin 
13615ad333ebSAndy Whitcroft /*
1362d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1363d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1364d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1365d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1366d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
136735cd7815SRik van Riel  */
136835cd7815SRik van Riel static int too_many_isolated(struct zone *zone, int file,
136935cd7815SRik van Riel 		struct scan_control *sc)
137035cd7815SRik van Riel {
137135cd7815SRik van Riel 	unsigned long inactive, isolated;
137235cd7815SRik van Riel 
137335cd7815SRik van Riel 	if (current_is_kswapd())
137435cd7815SRik van Riel 		return 0;
137535cd7815SRik van Riel 
137689b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
137735cd7815SRik van Riel 		return 0;
137835cd7815SRik van Riel 
137935cd7815SRik van Riel 	if (file) {
138035cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_FILE);
138135cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_FILE);
138235cd7815SRik van Riel 	} else {
138335cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_ANON);
138435cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_ANON);
138535cd7815SRik van Riel 	}
138635cd7815SRik van Riel 
13873cf23841SFengguang Wu 	/*
13883cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
13893cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
13903cf23841SFengguang Wu 	 * deadlock.
13913cf23841SFengguang Wu 	 */
13923cf23841SFengguang Wu 	if ((sc->gfp_mask & GFP_IOFS) == GFP_IOFS)
13933cf23841SFengguang Wu 		inactive >>= 3;
13943cf23841SFengguang Wu 
139535cd7815SRik van Riel 	return isolated > inactive;
139635cd7815SRik van Riel }
139735cd7815SRik van Riel 
139866635629SMel Gorman static noinline_for_stack void
139975b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
140066635629SMel Gorman {
140127ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
140227ac81d8SKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
14033f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
140466635629SMel Gorman 
140566635629SMel Gorman 	/*
140666635629SMel Gorman 	 * Put back any unfreeable pages.
140766635629SMel Gorman 	 */
140866635629SMel Gorman 	while (!list_empty(page_list)) {
14093f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
141066635629SMel Gorman 		int lru;
14113f79768fSHugh Dickins 
1412309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
141366635629SMel Gorman 		list_del(&page->lru);
141439b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
141566635629SMel Gorman 			spin_unlock_irq(&zone->lru_lock);
141666635629SMel Gorman 			putback_lru_page(page);
141766635629SMel Gorman 			spin_lock_irq(&zone->lru_lock);
141866635629SMel Gorman 			continue;
141966635629SMel Gorman 		}
1420fa9add64SHugh Dickins 
1421fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
1422fa9add64SHugh Dickins 
14237a608572SLinus Torvalds 		SetPageLRU(page);
142466635629SMel Gorman 		lru = page_lru(page);
1425fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1426fa9add64SHugh Dickins 
142766635629SMel Gorman 		if (is_active_lru(lru)) {
142866635629SMel Gorman 			int file = is_file_lru(lru);
14299992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
14309992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
143166635629SMel Gorman 		}
14322bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
14332bcf8879SHugh Dickins 			__ClearPageLRU(page);
14342bcf8879SHugh Dickins 			__ClearPageActive(page);
1435fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
14362bcf8879SHugh Dickins 
14372bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
143866635629SMel Gorman 				spin_unlock_irq(&zone->lru_lock);
1439747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
14402bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
144166635629SMel Gorman 				spin_lock_irq(&zone->lru_lock);
14422bcf8879SHugh Dickins 			} else
14432bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
144466635629SMel Gorman 		}
144566635629SMel Gorman 	}
144666635629SMel Gorman 
14473f79768fSHugh Dickins 	/*
14483f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
14493f79768fSHugh Dickins 	 */
14503f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
145166635629SMel Gorman }
145266635629SMel Gorman 
145366635629SMel Gorman /*
1454399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1455399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1456399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1457399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1458399ba0b9SNeilBrown  */
1459399ba0b9SNeilBrown static int current_may_throttle(void)
1460399ba0b9SNeilBrown {
1461399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1462399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1463399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1464399ba0b9SNeilBrown }
1465399ba0b9SNeilBrown 
1466399ba0b9SNeilBrown /*
14671742f19fSAndrew Morton  * shrink_inactive_list() is a helper for shrink_zone().  It returns the number
14681742f19fSAndrew Morton  * of reclaimed pages
14691da177e4SLinus Torvalds  */
147066635629SMel Gorman static noinline_for_stack unsigned long
14711a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
14729e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
14731da177e4SLinus Torvalds {
14741da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1475e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
147605ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1477e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
14788e950282SMel Gorman 	unsigned long nr_dirty = 0;
14798e950282SMel Gorman 	unsigned long nr_congested = 0;
1480e2be15f6SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
148192df3a72SMel Gorman 	unsigned long nr_writeback = 0;
1482b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
1483f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
14843cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
14851a93be0eSKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
14861a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
148778dc583dSKOSAKI Motohiro 
148835cd7815SRik van Riel 	while (unlikely(too_many_isolated(zone, file, sc))) {
148958355c78SKOSAKI Motohiro 		congestion_wait(BLK_RW_ASYNC, HZ/10);
149035cd7815SRik van Riel 
149135cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
149235cd7815SRik van Riel 		if (fatal_signal_pending(current))
149335cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
149435cd7815SRik van Riel 	}
149535cd7815SRik van Riel 
14961da177e4SLinus Torvalds 	lru_add_drain();
1497f80c0673SMinchan Kim 
1498f80c0673SMinchan Kim 	if (!sc->may_unmap)
149961317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1500f80c0673SMinchan Kim 	if (!sc->may_writepage)
150161317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1502f80c0673SMinchan Kim 
15031da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
15041da177e4SLinus Torvalds 
15055dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
15065dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
150795d918fcSKonstantin Khlebnikov 
150895d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
150995d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
151095d918fcSKonstantin Khlebnikov 
151189b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
15120d5d823aSMel Gorman 		__mod_zone_page_state(zone, NR_PAGES_SCANNED, nr_scanned);
1513b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
151475b00af7SHugh Dickins 			__count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scanned);
1515b35ea17bSKOSAKI Motohiro 		else
151675b00af7SHugh Dickins 			__count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scanned);
1517b35ea17bSKOSAKI Motohiro 	}
151866635629SMel Gorman 	spin_unlock_irq(&zone->lru_lock);
1519d563c050SHillf Danton 
1520d563c050SHillf Danton 	if (nr_taken == 0)
152166635629SMel Gorman 		return 0;
1522b35ea17bSKOSAKI Motohiro 
152302c6de8dSMinchan Kim 	nr_reclaimed = shrink_page_list(&page_list, zone, sc, TTU_UNMAP,
15248e950282SMel Gorman 				&nr_dirty, &nr_unqueued_dirty, &nr_congested,
15258e950282SMel Gorman 				&nr_writeback, &nr_immediate,
1526b1a6f21eSMel Gorman 				false);
1527c661b078SAndy Whitcroft 
15283f79768fSHugh Dickins 	spin_lock_irq(&zone->lru_lock);
15293f79768fSHugh Dickins 
153095d918fcSKonstantin Khlebnikov 	reclaim_stat->recent_scanned[file] += nr_taken;
1531d563c050SHillf Danton 
1532904249aaSYing Han 	if (global_reclaim(sc)) {
1533b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1534904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_KSWAPD, zone,
1535904249aaSYing Han 					       nr_reclaimed);
1536904249aaSYing Han 		else
1537904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_DIRECT, zone,
1538904249aaSYing Han 					       nr_reclaimed);
1539904249aaSYing Han 	}
1540a74609faSNick Piggin 
154127ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
15423f79768fSHugh Dickins 
154395d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
15443f79768fSHugh Dickins 
15453f79768fSHugh Dickins 	spin_unlock_irq(&zone->lru_lock);
15463f79768fSHugh Dickins 
1547747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
1548b745bc85SMel Gorman 	free_hot_cold_page_list(&page_list, true);
1549e11da5b4SMel Gorman 
155092df3a72SMel Gorman 	/*
155192df3a72SMel Gorman 	 * If reclaim is isolating dirty pages under writeback, it implies
155292df3a72SMel Gorman 	 * that the long-lived page allocation rate is exceeding the page
155392df3a72SMel Gorman 	 * laundering rate. Either the global limits are not being effective
155492df3a72SMel Gorman 	 * at throttling processes due to the page distribution throughout
155592df3a72SMel Gorman 	 * zones or there is heavy usage of a slow backing device. The
155692df3a72SMel Gorman 	 * only option is to throttle from reclaim context which is not ideal
155792df3a72SMel Gorman 	 * as there is no guarantee the dirtying process is throttled in the
155892df3a72SMel Gorman 	 * same way balance_dirty_pages() manages.
155992df3a72SMel Gorman 	 *
15608e950282SMel Gorman 	 * Once a zone is flagged ZONE_WRITEBACK, kswapd will count the number
15618e950282SMel Gorman 	 * of pages under pages flagged for immediate reclaim and stall if any
15628e950282SMel Gorman 	 * are encountered in the nr_immediate check below.
156392df3a72SMel Gorman 	 */
1564918fc718SMel Gorman 	if (nr_writeback && nr_writeback == nr_taken)
156557054651SJohannes Weiner 		set_bit(ZONE_WRITEBACK, &zone->flags);
156692df3a72SMel Gorman 
1567d43006d5SMel Gorman 	/*
1568b1a6f21eSMel Gorman 	 * memcg will stall in page writeback so only consider forcibly
1569b1a6f21eSMel Gorman 	 * stalling for global reclaim
1570d43006d5SMel Gorman 	 */
1571b1a6f21eSMel Gorman 	if (global_reclaim(sc)) {
1572b1a6f21eSMel Gorman 		/*
15738e950282SMel Gorman 		 * Tag a zone as congested if all the dirty pages scanned were
15748e950282SMel Gorman 		 * backed by a congested BDI and wait_iff_congested will stall.
15758e950282SMel Gorman 		 */
15768e950282SMel Gorman 		if (nr_dirty && nr_dirty == nr_congested)
157757054651SJohannes Weiner 			set_bit(ZONE_CONGESTED, &zone->flags);
15788e950282SMel Gorman 
15798e950282SMel Gorman 		/*
1580b1a6f21eSMel Gorman 		 * If dirty pages are scanned that are not queued for IO, it
1581b1a6f21eSMel Gorman 		 * implies that flushers are not keeping up. In this case, flag
158257054651SJohannes Weiner 		 * the zone ZONE_DIRTY and kswapd will start writing pages from
158357054651SJohannes Weiner 		 * reclaim context.
1584b1a6f21eSMel Gorman 		 */
1585b1a6f21eSMel Gorman 		if (nr_unqueued_dirty == nr_taken)
158657054651SJohannes Weiner 			set_bit(ZONE_DIRTY, &zone->flags);
1587b1a6f21eSMel Gorman 
1588b1a6f21eSMel Gorman 		/*
1589b738d764SLinus Torvalds 		 * If kswapd scans pages marked marked for immediate
1590b738d764SLinus Torvalds 		 * reclaim and under writeback (nr_immediate), it implies
1591b738d764SLinus Torvalds 		 * that pages are cycling through the LRU faster than
1592b1a6f21eSMel Gorman 		 * they are written so also forcibly stall.
1593b1a6f21eSMel Gorman 		 */
1594b738d764SLinus Torvalds 		if (nr_immediate && current_may_throttle())
1595b1a6f21eSMel Gorman 			congestion_wait(BLK_RW_ASYNC, HZ/10);
1596e2be15f6SMel Gorman 	}
1597d43006d5SMel Gorman 
15988e950282SMel Gorman 	/*
15998e950282SMel Gorman 	 * Stall direct reclaim for IO completions if underlying BDIs or zone
16008e950282SMel Gorman 	 * is congested. Allow kswapd to continue until it starts encountering
16018e950282SMel Gorman 	 * unqueued dirty pages or cycling through the LRU too quickly.
16028e950282SMel Gorman 	 */
1603399ba0b9SNeilBrown 	if (!sc->hibernation_mode && !current_is_kswapd() &&
1604399ba0b9SNeilBrown 	    current_may_throttle())
16058e950282SMel Gorman 		wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10);
16068e950282SMel Gorman 
1607e11da5b4SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(zone->zone_pgdat->node_id,
1608e11da5b4SMel Gorman 		zone_idx(zone),
1609e11da5b4SMel Gorman 		nr_scanned, nr_reclaimed,
16109e3b2f8cSKonstantin Khlebnikov 		sc->priority,
161123b9da55SMel Gorman 		trace_shrink_flags(file));
161205ff5137SAndrew Morton 	return nr_reclaimed;
16131da177e4SLinus Torvalds }
16141da177e4SLinus Torvalds 
16153bb1a852SMartin Bligh /*
16161cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
16171cfb419bSKAMEZAWA Hiroyuki  *
16181cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
16191cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
16201cfb419bSKAMEZAWA Hiroyuki  *
16211cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
16221cfb419bSKAMEZAWA Hiroyuki  * appropriate to hold zone->lru_lock across the whole operation.  But if
16231cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
16241cfb419bSKAMEZAWA Hiroyuki  * should drop zone->lru_lock around each page.  It's impossible to balance
16251cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
16261cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
16271cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
16281cfb419bSKAMEZAWA Hiroyuki  *
16291cfb419bSKAMEZAWA Hiroyuki  * The downside is that we have to touch page->_count against each page.
16301cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
16311cfb419bSKAMEZAWA Hiroyuki  */
16321cfb419bSKAMEZAWA Hiroyuki 
1633fa9add64SHugh Dickins static void move_active_pages_to_lru(struct lruvec *lruvec,
16343eb4140fSWu Fengguang 				     struct list_head *list,
16352bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
16363eb4140fSWu Fengguang 				     enum lru_list lru)
16373eb4140fSWu Fengguang {
1638fa9add64SHugh Dickins 	struct zone *zone = lruvec_zone(lruvec);
16393eb4140fSWu Fengguang 	unsigned long pgmoved = 0;
16403eb4140fSWu Fengguang 	struct page *page;
1641fa9add64SHugh Dickins 	int nr_pages;
16423eb4140fSWu Fengguang 
16433eb4140fSWu Fengguang 	while (!list_empty(list)) {
16443eb4140fSWu Fengguang 		page = lru_to_page(list);
1645fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
16463eb4140fSWu Fengguang 
1647309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
16483eb4140fSWu Fengguang 		SetPageLRU(page);
16493eb4140fSWu Fengguang 
1650fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
1651fa9add64SHugh Dickins 		mem_cgroup_update_lru_size(lruvec, lru, nr_pages);
1652925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
1653fa9add64SHugh Dickins 		pgmoved += nr_pages;
16543eb4140fSWu Fengguang 
16552bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
16562bcf8879SHugh Dickins 			__ClearPageLRU(page);
16572bcf8879SHugh Dickins 			__ClearPageActive(page);
1658fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
16592bcf8879SHugh Dickins 
16602bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
16613eb4140fSWu Fengguang 				spin_unlock_irq(&zone->lru_lock);
1662747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
16632bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
16643eb4140fSWu Fengguang 				spin_lock_irq(&zone->lru_lock);
16652bcf8879SHugh Dickins 			} else
16662bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
16673eb4140fSWu Fengguang 		}
16683eb4140fSWu Fengguang 	}
16693eb4140fSWu Fengguang 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved);
16703eb4140fSWu Fengguang 	if (!is_active_lru(lru))
16713eb4140fSWu Fengguang 		__count_vm_events(PGDEACTIVATE, pgmoved);
16723eb4140fSWu Fengguang }
16731cfb419bSKAMEZAWA Hiroyuki 
1674f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
16751a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1676f16015fbSJohannes Weiner 			       struct scan_control *sc,
16779e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
16781cfb419bSKAMEZAWA Hiroyuki {
167944c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1680f626012dSHugh Dickins 	unsigned long nr_scanned;
16816fe6b7e3SWu Fengguang 	unsigned long vm_flags;
16821cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
16838cab4754SWu Fengguang 	LIST_HEAD(l_active);
1684b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
16851cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
16861a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
168744c241f1SKOSAKI Motohiro 	unsigned long nr_rotated = 0;
1688f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
16893cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
16901a93be0eSKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
16911cfb419bSKAMEZAWA Hiroyuki 
16921da177e4SLinus Torvalds 	lru_add_drain();
1693f80c0673SMinchan Kim 
1694f80c0673SMinchan Kim 	if (!sc->may_unmap)
169561317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1696f80c0673SMinchan Kim 	if (!sc->may_writepage)
169761317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1698f80c0673SMinchan Kim 
16991da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
1700925b7673SJohannes Weiner 
17015dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
17025dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
170389b5fae5SJohannes Weiner 	if (global_reclaim(sc))
17040d5d823aSMel Gorman 		__mod_zone_page_state(zone, NR_PAGES_SCANNED, nr_scanned);
170589b5fae5SJohannes Weiner 
1706b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
17071cfb419bSKAMEZAWA Hiroyuki 
1708f626012dSHugh Dickins 	__count_zone_vm_events(PGREFILL, zone, nr_scanned);
17093cb99451SKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
1710a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
17111da177e4SLinus Torvalds 	spin_unlock_irq(&zone->lru_lock);
17121da177e4SLinus Torvalds 
17131da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
17141da177e4SLinus Torvalds 		cond_resched();
17151da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
17161da177e4SLinus Torvalds 		list_del(&page->lru);
17177e9cd484SRik van Riel 
171839b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1719894bc310SLee Schermerhorn 			putback_lru_page(page);
1720894bc310SLee Schermerhorn 			continue;
1721894bc310SLee Schermerhorn 		}
1722894bc310SLee Schermerhorn 
1723cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
1724cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
1725cc715d99SMel Gorman 				if (page_has_private(page))
1726cc715d99SMel Gorman 					try_to_release_page(page, 0);
1727cc715d99SMel Gorman 				unlock_page(page);
1728cc715d99SMel Gorman 			}
1729cc715d99SMel Gorman 		}
1730cc715d99SMel Gorman 
1731c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
1732c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
17339992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
17348cab4754SWu Fengguang 			/*
17358cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
17368cab4754SWu Fengguang 			 * give them one more trip around the active list. So
17378cab4754SWu Fengguang 			 * that executable code get better chances to stay in
17388cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
17398cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
17408cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
17418cab4754SWu Fengguang 			 * so we ignore them here.
17428cab4754SWu Fengguang 			 */
174341e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
17448cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
17458cab4754SWu Fengguang 				continue;
17468cab4754SWu Fengguang 			}
17478cab4754SWu Fengguang 		}
17487e9cd484SRik van Riel 
17495205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
17501da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
17511da177e4SLinus Torvalds 	}
17521da177e4SLinus Torvalds 
1753b555749aSAndrew Morton 	/*
17548cab4754SWu Fengguang 	 * Move pages back to the lru list.
1755b555749aSAndrew Morton 	 */
17562a1dc509SJohannes Weiner 	spin_lock_irq(&zone->lru_lock);
17574f98a2feSRik van Riel 	/*
17588cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
17598cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
17608cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
17617c0db9e9SJerome Marchand 	 * get_scan_count.
1762556adecbSRik van Riel 	 */
1763b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
1764556adecbSRik van Riel 
1765fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
1766fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1767a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1768f8891e5eSChristoph Lameter 	spin_unlock_irq(&zone->lru_lock);
17692bcf8879SHugh Dickins 
1770747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&l_hold);
1771b745bc85SMel Gorman 	free_hot_cold_page_list(&l_hold, true);
17721da177e4SLinus Torvalds }
17731da177e4SLinus Torvalds 
177474e3f3c3SMinchan Kim #ifdef CONFIG_SWAP
177514797e23SKOSAKI Motohiro static int inactive_anon_is_low_global(struct zone *zone)
1776f89eb90eSKOSAKI Motohiro {
1777f89eb90eSKOSAKI Motohiro 	unsigned long active, inactive;
1778f89eb90eSKOSAKI Motohiro 
1779f89eb90eSKOSAKI Motohiro 	active = zone_page_state(zone, NR_ACTIVE_ANON);
1780f89eb90eSKOSAKI Motohiro 	inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1781f89eb90eSKOSAKI Motohiro 
1782f89eb90eSKOSAKI Motohiro 	if (inactive * zone->inactive_ratio < active)
1783f89eb90eSKOSAKI Motohiro 		return 1;
1784f89eb90eSKOSAKI Motohiro 
1785f89eb90eSKOSAKI Motohiro 	return 0;
1786f89eb90eSKOSAKI Motohiro }
1787f89eb90eSKOSAKI Motohiro 
178814797e23SKOSAKI Motohiro /**
178914797e23SKOSAKI Motohiro  * inactive_anon_is_low - check if anonymous pages need to be deactivated
1790c56d5c7dSKonstantin Khlebnikov  * @lruvec: LRU vector to check
179114797e23SKOSAKI Motohiro  *
179214797e23SKOSAKI Motohiro  * Returns true if the zone does not have enough inactive anon pages,
179314797e23SKOSAKI Motohiro  * meaning some active anon pages need to be deactivated.
179414797e23SKOSAKI Motohiro  */
1795c56d5c7dSKonstantin Khlebnikov static int inactive_anon_is_low(struct lruvec *lruvec)
179614797e23SKOSAKI Motohiro {
179774e3f3c3SMinchan Kim 	/*
179874e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
179974e3f3c3SMinchan Kim 	 * is pointless.
180074e3f3c3SMinchan Kim 	 */
180174e3f3c3SMinchan Kim 	if (!total_swap_pages)
180274e3f3c3SMinchan Kim 		return 0;
180374e3f3c3SMinchan Kim 
1804c3c787e8SHugh Dickins 	if (!mem_cgroup_disabled())
1805c56d5c7dSKonstantin Khlebnikov 		return mem_cgroup_inactive_anon_is_low(lruvec);
1806f16015fbSJohannes Weiner 
1807c56d5c7dSKonstantin Khlebnikov 	return inactive_anon_is_low_global(lruvec_zone(lruvec));
180814797e23SKOSAKI Motohiro }
180974e3f3c3SMinchan Kim #else
1810c56d5c7dSKonstantin Khlebnikov static inline int inactive_anon_is_low(struct lruvec *lruvec)
181174e3f3c3SMinchan Kim {
181274e3f3c3SMinchan Kim 	return 0;
181374e3f3c3SMinchan Kim }
181474e3f3c3SMinchan Kim #endif
181514797e23SKOSAKI Motohiro 
181656e49d21SRik van Riel /**
181756e49d21SRik van Riel  * inactive_file_is_low - check if file pages need to be deactivated
1818c56d5c7dSKonstantin Khlebnikov  * @lruvec: LRU vector to check
181956e49d21SRik van Riel  *
182056e49d21SRik van Riel  * When the system is doing streaming IO, memory pressure here
182156e49d21SRik van Riel  * ensures that active file pages get deactivated, until more
182256e49d21SRik van Riel  * than half of the file pages are on the inactive list.
182356e49d21SRik van Riel  *
182456e49d21SRik van Riel  * Once we get to that situation, protect the system's working
182556e49d21SRik van Riel  * set from being evicted by disabling active file page aging.
182656e49d21SRik van Riel  *
182756e49d21SRik van Riel  * This uses a different ratio than the anonymous pages, because
182856e49d21SRik van Riel  * the page cache uses a use-once replacement algorithm.
182956e49d21SRik van Riel  */
1830c56d5c7dSKonstantin Khlebnikov static int inactive_file_is_low(struct lruvec *lruvec)
183156e49d21SRik van Riel {
1832e3790144SJohannes Weiner 	unsigned long inactive;
1833e3790144SJohannes Weiner 	unsigned long active;
183456e49d21SRik van Riel 
1835e3790144SJohannes Weiner 	inactive = get_lru_size(lruvec, LRU_INACTIVE_FILE);
1836e3790144SJohannes Weiner 	active = get_lru_size(lruvec, LRU_ACTIVE_FILE);
1837e3790144SJohannes Weiner 
1838e3790144SJohannes Weiner 	return active > inactive;
183956e49d21SRik van Riel }
184056e49d21SRik van Riel 
184175b00af7SHugh Dickins static int inactive_list_is_low(struct lruvec *lruvec, enum lru_list lru)
1842b39415b2SRik van Riel {
184375b00af7SHugh Dickins 	if (is_file_lru(lru))
1844c56d5c7dSKonstantin Khlebnikov 		return inactive_file_is_low(lruvec);
1845b39415b2SRik van Riel 	else
1846c56d5c7dSKonstantin Khlebnikov 		return inactive_anon_is_low(lruvec);
1847b39415b2SRik van Riel }
1848b39415b2SRik van Riel 
18494f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
18501a93be0eSKonstantin Khlebnikov 				 struct lruvec *lruvec, struct scan_control *sc)
1851b69408e8SChristoph Lameter {
1852b39415b2SRik van Riel 	if (is_active_lru(lru)) {
185375b00af7SHugh Dickins 		if (inactive_list_is_low(lruvec, lru))
18541a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
1855556adecbSRik van Riel 		return 0;
1856556adecbSRik van Riel 	}
1857556adecbSRik van Riel 
18581a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
1859b69408e8SChristoph Lameter }
1860b69408e8SChristoph Lameter 
18619a265114SJohannes Weiner enum scan_balance {
18629a265114SJohannes Weiner 	SCAN_EQUAL,
18639a265114SJohannes Weiner 	SCAN_FRACT,
18649a265114SJohannes Weiner 	SCAN_ANON,
18659a265114SJohannes Weiner 	SCAN_FILE,
18669a265114SJohannes Weiner };
18679a265114SJohannes Weiner 
18681da177e4SLinus Torvalds /*
18694f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
18704f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
18714f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
18724f98a2feSRik van Riel  * onto the active list instead of evict.
18734f98a2feSRik van Riel  *
1874be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
1875be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
18764f98a2feSRik van Riel  */
187702695175SJohannes Weiner static void get_scan_count(struct lruvec *lruvec, int swappiness,
187802695175SJohannes Weiner 			   struct scan_control *sc, unsigned long *nr)
18794f98a2feSRik van Riel {
188090126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
18819a265114SJohannes Weiner 	u64 fraction[2];
18829a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
188390126375SKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
18849a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
18859a265114SJohannes Weiner 	enum scan_balance scan_balance;
18860bf1457fSJohannes Weiner 	unsigned long anon, file;
18879a265114SJohannes Weiner 	bool force_scan = false;
18889a265114SJohannes Weiner 	unsigned long ap, fp;
18899a265114SJohannes Weiner 	enum lru_list lru;
18906f04f48dSSuleiman Souhlal 	bool some_scanned;
18916f04f48dSSuleiman Souhlal 	int pass;
1892246e87a9SKAMEZAWA Hiroyuki 
1893f11c0ca5SJohannes Weiner 	/*
1894f11c0ca5SJohannes Weiner 	 * If the zone or memcg is small, nr[l] can be 0.  This
1895f11c0ca5SJohannes Weiner 	 * results in no scanning on this priority and a potential
1896f11c0ca5SJohannes Weiner 	 * priority drop.  Global direct reclaim can go to the next
1897f11c0ca5SJohannes Weiner 	 * zone and tends to have no problems. Global kswapd is for
1898f11c0ca5SJohannes Weiner 	 * zone balancing and it needs to scan a minimum amount. When
1899f11c0ca5SJohannes Weiner 	 * reclaiming for a memcg, a priority drop can cause high
1900f11c0ca5SJohannes Weiner 	 * latencies, so it's better to scan a minimum amount there as
1901f11c0ca5SJohannes Weiner 	 * well.
1902f11c0ca5SJohannes Weiner 	 */
19036e543d57SLisa Du 	if (current_is_kswapd() && !zone_reclaimable(zone))
1904a4d3e9e7SJohannes Weiner 		force_scan = true;
190589b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
1906a4d3e9e7SJohannes Weiner 		force_scan = true;
190776a33fc3SShaohua Li 
190876a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
1909ec8acf20SShaohua Li 	if (!sc->may_swap || (get_nr_swap_pages() <= 0)) {
19109a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
191176a33fc3SShaohua Li 		goto out;
191276a33fc3SShaohua Li 	}
19134f98a2feSRik van Riel 
191410316b31SJohannes Weiner 	/*
191510316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
191610316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
191710316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
191810316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
191910316b31SJohannes Weiner 	 * too expensive.
192010316b31SJohannes Weiner 	 */
192102695175SJohannes Weiner 	if (!global_reclaim(sc) && !swappiness) {
19229a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
192310316b31SJohannes Weiner 		goto out;
192410316b31SJohannes Weiner 	}
192510316b31SJohannes Weiner 
192610316b31SJohannes Weiner 	/*
192710316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
192810316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
192910316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
193010316b31SJohannes Weiner 	 */
193102695175SJohannes Weiner 	if (!sc->priority && swappiness) {
19329a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
193310316b31SJohannes Weiner 		goto out;
193410316b31SJohannes Weiner 	}
193510316b31SJohannes Weiner 
193611d16c25SJohannes Weiner 	/*
193762376251SJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
193862376251SJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
193962376251SJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
194062376251SJohannes Weiner 	 * shrinks, so does the window for rotation from references.
194162376251SJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
194262376251SJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
194362376251SJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
194462376251SJohannes Weiner 	 */
194562376251SJohannes Weiner 	if (global_reclaim(sc)) {
19462ab051e1SJerome Marchand 		unsigned long zonefile;
19472ab051e1SJerome Marchand 		unsigned long zonefree;
194862376251SJohannes Weiner 
19492ab051e1SJerome Marchand 		zonefree = zone_page_state(zone, NR_FREE_PAGES);
19502ab051e1SJerome Marchand 		zonefile = zone_page_state(zone, NR_ACTIVE_FILE) +
19512ab051e1SJerome Marchand 			   zone_page_state(zone, NR_INACTIVE_FILE);
19522ab051e1SJerome Marchand 
19532ab051e1SJerome Marchand 		if (unlikely(zonefile + zonefree <= high_wmark_pages(zone))) {
195462376251SJohannes Weiner 			scan_balance = SCAN_ANON;
195562376251SJohannes Weiner 			goto out;
195662376251SJohannes Weiner 		}
195762376251SJohannes Weiner 	}
195862376251SJohannes Weiner 
195962376251SJohannes Weiner 	/*
19607c5bd705SJohannes Weiner 	 * There is enough inactive page cache, do not reclaim
19617c5bd705SJohannes Weiner 	 * anything from the anonymous working set right now.
1962e9868505SRik van Riel 	 */
19637c5bd705SJohannes Weiner 	if (!inactive_file_is_low(lruvec)) {
19649a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
1965e9868505SRik van Riel 		goto out;
19664f98a2feSRik van Riel 	}
19674f98a2feSRik van Riel 
19689a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
19699a265114SJohannes Weiner 
19704f98a2feSRik van Riel 	/*
197158c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
197258c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
197358c37f6eSKOSAKI Motohiro 	 */
197402695175SJohannes Weiner 	anon_prio = swappiness;
197575b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
197658c37f6eSKOSAKI Motohiro 
197758c37f6eSKOSAKI Motohiro 	/*
19784f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
19794f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
19804f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
19814f98a2feSRik van Riel 	 *
19824f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
19834f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
19844f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
19854f98a2feSRik van Riel 	 *
19864f98a2feSRik van Riel 	 * anon in [0], file in [1]
19874f98a2feSRik van Riel 	 */
19882ab051e1SJerome Marchand 
19892ab051e1SJerome Marchand 	anon  = get_lru_size(lruvec, LRU_ACTIVE_ANON) +
19902ab051e1SJerome Marchand 		get_lru_size(lruvec, LRU_INACTIVE_ANON);
19912ab051e1SJerome Marchand 	file  = get_lru_size(lruvec, LRU_ACTIVE_FILE) +
19922ab051e1SJerome Marchand 		get_lru_size(lruvec, LRU_INACTIVE_FILE);
19932ab051e1SJerome Marchand 
199490126375SKonstantin Khlebnikov 	spin_lock_irq(&zone->lru_lock);
199558c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
19966e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
19976e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
19984f98a2feSRik van Riel 	}
19994f98a2feSRik van Riel 
20006e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
20016e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
20026e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
20034f98a2feSRik van Riel 	}
20044f98a2feSRik van Riel 
20054f98a2feSRik van Riel 	/*
200600d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
200700d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
200800d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
20094f98a2feSRik van Riel 	 */
2010fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
20116e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
20124f98a2feSRik van Riel 
2013fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
20146e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
201590126375SKonstantin Khlebnikov 	spin_unlock_irq(&zone->lru_lock);
20164f98a2feSRik van Riel 
201776a33fc3SShaohua Li 	fraction[0] = ap;
201876a33fc3SShaohua Li 	fraction[1] = fp;
201976a33fc3SShaohua Li 	denominator = ap + fp + 1;
202076a33fc3SShaohua Li out:
20216f04f48dSSuleiman Souhlal 	some_scanned = false;
20226f04f48dSSuleiman Souhlal 	/* Only use force_scan on second pass. */
20236f04f48dSSuleiman Souhlal 	for (pass = 0; !some_scanned && pass < 2; pass++) {
20244111304dSHugh Dickins 		for_each_evictable_lru(lru) {
20254111304dSHugh Dickins 			int file = is_file_lru(lru);
2026d778df51SJohannes Weiner 			unsigned long size;
202776a33fc3SShaohua Li 			unsigned long scan;
202876a33fc3SShaohua Li 
2029d778df51SJohannes Weiner 			size = get_lru_size(lruvec, lru);
2030d778df51SJohannes Weiner 			scan = size >> sc->priority;
20319a265114SJohannes Weiner 
20326f04f48dSSuleiman Souhlal 			if (!scan && pass && force_scan)
2033d778df51SJohannes Weiner 				scan = min(size, SWAP_CLUSTER_MAX);
20349a265114SJohannes Weiner 
20359a265114SJohannes Weiner 			switch (scan_balance) {
20369a265114SJohannes Weiner 			case SCAN_EQUAL:
20379a265114SJohannes Weiner 				/* Scan lists relative to size */
20389a265114SJohannes Weiner 				break;
20399a265114SJohannes Weiner 			case SCAN_FRACT:
20409a265114SJohannes Weiner 				/*
20419a265114SJohannes Weiner 				 * Scan types proportional to swappiness and
20429a265114SJohannes Weiner 				 * their relative recent reclaim efficiency.
20439a265114SJohannes Weiner 				 */
20446f04f48dSSuleiman Souhlal 				scan = div64_u64(scan * fraction[file],
20456f04f48dSSuleiman Souhlal 							denominator);
20469a265114SJohannes Weiner 				break;
20479a265114SJohannes Weiner 			case SCAN_FILE:
20489a265114SJohannes Weiner 			case SCAN_ANON:
20499a265114SJohannes Weiner 				/* Scan one type exclusively */
20509a265114SJohannes Weiner 				if ((scan_balance == SCAN_FILE) != file)
20519a265114SJohannes Weiner 					scan = 0;
20529a265114SJohannes Weiner 				break;
20539a265114SJohannes Weiner 			default:
20549a265114SJohannes Weiner 				/* Look ma, no brain */
20559a265114SJohannes Weiner 				BUG();
20569a265114SJohannes Weiner 			}
20574111304dSHugh Dickins 			nr[lru] = scan;
20586f04f48dSSuleiman Souhlal 			/*
20596f04f48dSSuleiman Souhlal 			 * Skip the second pass and don't force_scan,
20606f04f48dSSuleiman Souhlal 			 * if we found something to scan.
20616f04f48dSSuleiman Souhlal 			 */
20626f04f48dSSuleiman Souhlal 			some_scanned |= !!scan;
20636f04f48dSSuleiman Souhlal 		}
206476a33fc3SShaohua Li 	}
20656e08a369SWu Fengguang }
20664f98a2feSRik van Riel 
20679b4f98cdSJohannes Weiner /*
20689b4f98cdSJohannes Weiner  * This is a basic per-zone page freer.  Used by both kswapd and direct reclaim.
20699b4f98cdSJohannes Weiner  */
207002695175SJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, int swappiness,
207102695175SJohannes Weiner 			  struct scan_control *sc)
20729b4f98cdSJohannes Weiner {
20739b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2074e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
20759b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
20769b4f98cdSJohannes Weiner 	enum lru_list lru;
20779b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
20789b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
20799b4f98cdSJohannes Weiner 	struct blk_plug plug;
20801a501907SMel Gorman 	bool scan_adjusted;
20819b4f98cdSJohannes Weiner 
208202695175SJohannes Weiner 	get_scan_count(lruvec, swappiness, sc, nr);
20839b4f98cdSJohannes Weiner 
2084e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2085e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2086e82e0561SMel Gorman 
20871a501907SMel Gorman 	/*
20881a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
20891a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
20901a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
20911a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
20921a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
20931a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
20941a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
20951a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
20961a501907SMel Gorman 	 * dropped to zero at the first pass.
20971a501907SMel Gorman 	 */
20981a501907SMel Gorman 	scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
20991a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
21001a501907SMel Gorman 
21019b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
21029b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
21039b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2104e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2105e82e0561SMel Gorman 		unsigned long nr_scanned;
2106e82e0561SMel Gorman 
21079b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
21089b4f98cdSJohannes Weiner 			if (nr[lru]) {
21099b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
21109b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
21119b4f98cdSJohannes Weiner 
21129b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
21139b4f98cdSJohannes Weiner 							    lruvec, sc);
21149b4f98cdSJohannes Weiner 			}
21159b4f98cdSJohannes Weiner 		}
2116e82e0561SMel Gorman 
2117e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2118e82e0561SMel Gorman 			continue;
2119e82e0561SMel Gorman 
21209b4f98cdSJohannes Weiner 		/*
2121e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
21221a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2123e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2124e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2125e82e0561SMel Gorman 		 * proportional to the original scan target.
2126e82e0561SMel Gorman 		 */
2127e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2128e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2129e82e0561SMel Gorman 
21301a501907SMel Gorman 		/*
21311a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
21321a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
21331a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
21341a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
21351a501907SMel Gorman 		 */
21361a501907SMel Gorman 		if (!nr_file || !nr_anon)
21371a501907SMel Gorman 			break;
21381a501907SMel Gorman 
2139e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2140e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2141e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2142e82e0561SMel Gorman 			lru = LRU_BASE;
2143e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2144e82e0561SMel Gorman 		} else {
2145e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2146e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2147e82e0561SMel Gorman 			lru = LRU_FILE;
2148e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2149e82e0561SMel Gorman 		}
2150e82e0561SMel Gorman 
2151e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2152e82e0561SMel Gorman 		nr[lru] = 0;
2153e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2154e82e0561SMel Gorman 
2155e82e0561SMel Gorman 		/*
2156e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2157e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2158e82e0561SMel Gorman 		 */
2159e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2160e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2161e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2162e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2163e82e0561SMel Gorman 
2164e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2165e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2166e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2167e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2168e82e0561SMel Gorman 
2169e82e0561SMel Gorman 		scan_adjusted = true;
21709b4f98cdSJohannes Weiner 	}
21719b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
21729b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
21739b4f98cdSJohannes Weiner 
21749b4f98cdSJohannes Weiner 	/*
21759b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
21769b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
21779b4f98cdSJohannes Weiner 	 */
21789b4f98cdSJohannes Weiner 	if (inactive_anon_is_low(lruvec))
21799b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
21809b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
21819b4f98cdSJohannes Weiner 
21829b4f98cdSJohannes Weiner 	throttle_vm_writeout(sc->gfp_mask);
21839b4f98cdSJohannes Weiner }
21849b4f98cdSJohannes Weiner 
218523b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
21869e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
218723b9da55SMel Gorman {
2188d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
218923b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
21909e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
219123b9da55SMel Gorman 		return true;
219223b9da55SMel Gorman 
219323b9da55SMel Gorman 	return false;
219423b9da55SMel Gorman }
219523b9da55SMel Gorman 
21964f98a2feSRik van Riel /*
219723b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
219823b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
219923b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
220023b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
220123b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
22023e7d3449SMel Gorman  */
22039b4f98cdSJohannes Weiner static inline bool should_continue_reclaim(struct zone *zone,
22043e7d3449SMel Gorman 					unsigned long nr_reclaimed,
22053e7d3449SMel Gorman 					unsigned long nr_scanned,
22063e7d3449SMel Gorman 					struct scan_control *sc)
22073e7d3449SMel Gorman {
22083e7d3449SMel Gorman 	unsigned long pages_for_compaction;
22093e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
22103e7d3449SMel Gorman 
22113e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
22129e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
22133e7d3449SMel Gorman 		return false;
22143e7d3449SMel Gorman 
22152876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
22162876592fSMel Gorman 	if (sc->gfp_mask & __GFP_REPEAT) {
22173e7d3449SMel Gorman 		/*
22182876592fSMel Gorman 		 * For __GFP_REPEAT allocations, stop reclaiming if the
22192876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
22202876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
22212876592fSMel Gorman 		 * expensive but a __GFP_REPEAT caller really wants to succeed
22223e7d3449SMel Gorman 		 */
22233e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
22243e7d3449SMel Gorman 			return false;
22252876592fSMel Gorman 	} else {
22262876592fSMel Gorman 		/*
22272876592fSMel Gorman 		 * For non-__GFP_REPEAT allocations which can presumably
22282876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
22292876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
22302876592fSMel Gorman 		 * pages that were scanned. This will return to the
22312876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
22322876592fSMel Gorman 		 * the resulting allocation attempt fails
22332876592fSMel Gorman 		 */
22342876592fSMel Gorman 		if (!nr_reclaimed)
22352876592fSMel Gorman 			return false;
22362876592fSMel Gorman 	}
22373e7d3449SMel Gorman 
22383e7d3449SMel Gorman 	/*
22393e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
22403e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
22413e7d3449SMel Gorman 	 */
22423e7d3449SMel Gorman 	pages_for_compaction = (2UL << sc->order);
22439b4f98cdSJohannes Weiner 	inactive_lru_pages = zone_page_state(zone, NR_INACTIVE_FILE);
2244ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
22459b4f98cdSJohannes Weiner 		inactive_lru_pages += zone_page_state(zone, NR_INACTIVE_ANON);
22463e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
22473e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
22483e7d3449SMel Gorman 		return true;
22493e7d3449SMel Gorman 
22503e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
22519b4f98cdSJohannes Weiner 	switch (compaction_suitable(zone, sc->order)) {
22523e7d3449SMel Gorman 	case COMPACT_PARTIAL:
22533e7d3449SMel Gorman 	case COMPACT_CONTINUE:
22543e7d3449SMel Gorman 		return false;
22553e7d3449SMel Gorman 	default:
22563e7d3449SMel Gorman 		return true;
22573e7d3449SMel Gorman 	}
22583e7d3449SMel Gorman }
22593e7d3449SMel Gorman 
22602344d7e4SJohannes Weiner static bool shrink_zone(struct zone *zone, struct scan_control *sc)
2261f16015fbSJohannes Weiner {
22629b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
22632344d7e4SJohannes Weiner 	bool reclaimable = false;
22649b4f98cdSJohannes Weiner 
22659b4f98cdSJohannes Weiner 	do {
22665660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
22675660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
22685660048cSJohannes Weiner 			.zone = zone,
22699e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
22705660048cSJohannes Weiner 		};
2271694fbc0fSAndrew Morton 		struct mem_cgroup *memcg;
22725660048cSJohannes Weiner 
22739b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
22749b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
22759b4f98cdSJohannes Weiner 
2276694fbc0fSAndrew Morton 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
2277694fbc0fSAndrew Morton 		do {
22789b4f98cdSJohannes Weiner 			struct lruvec *lruvec;
227902695175SJohannes Weiner 			int swappiness;
22809b4f98cdSJohannes Weiner 
22819b4f98cdSJohannes Weiner 			lruvec = mem_cgroup_zone_lruvec(zone, memcg);
228202695175SJohannes Weiner 			swappiness = mem_cgroup_swappiness(memcg);
22835660048cSJohannes Weiner 
228402695175SJohannes Weiner 			shrink_lruvec(lruvec, swappiness, sc);
2285f9be23d6SKonstantin Khlebnikov 
22865660048cSJohannes Weiner 			/*
2287a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2288a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
22899b4f98cdSJohannes Weiner 			 * zone.
2290a394cb8eSMichal Hocko 			 *
2291a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2292a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2293a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2294a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
22955660048cSJohannes Weiner 			 */
2296a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2297a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
22985660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
22995660048cSJohannes Weiner 				break;
23005660048cSJohannes Weiner 			}
2301694fbc0fSAndrew Morton 			memcg = mem_cgroup_iter(root, memcg, &reclaim);
2302694fbc0fSAndrew Morton 		} while (memcg);
230370ddf637SAnton Vorontsov 
230470ddf637SAnton Vorontsov 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup,
230570ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
230670ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
230770ddf637SAnton Vorontsov 
23082344d7e4SJohannes Weiner 		if (sc->nr_reclaimed - nr_reclaimed)
23092344d7e4SJohannes Weiner 			reclaimable = true;
23102344d7e4SJohannes Weiner 
23119b4f98cdSJohannes Weiner 	} while (should_continue_reclaim(zone, sc->nr_reclaimed - nr_reclaimed,
23129b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
23132344d7e4SJohannes Weiner 
23142344d7e4SJohannes Weiner 	return reclaimable;
2315f16015fbSJohannes Weiner }
2316f16015fbSJohannes Weiner 
231753853e2dSVlastimil Babka /*
231853853e2dSVlastimil Babka  * Returns true if compaction should go ahead for a high-order request, or
231953853e2dSVlastimil Babka  * the high-order allocation would succeed without compaction.
232053853e2dSVlastimil Babka  */
23210b06496aSJohannes Weiner static inline bool compaction_ready(struct zone *zone, int order)
2322fe4b1b24SMel Gorman {
2323fe4b1b24SMel Gorman 	unsigned long balance_gap, watermark;
2324fe4b1b24SMel Gorman 	bool watermark_ok;
2325fe4b1b24SMel Gorman 
2326fe4b1b24SMel Gorman 	/*
2327fe4b1b24SMel Gorman 	 * Compaction takes time to run and there are potentially other
2328fe4b1b24SMel Gorman 	 * callers using the pages just freed. Continue reclaiming until
2329fe4b1b24SMel Gorman 	 * there is a buffer of free pages available to give compaction
2330fe4b1b24SMel Gorman 	 * a reasonable chance of completing and allocating the page
2331fe4b1b24SMel Gorman 	 */
23324be89a34SJianyu Zhan 	balance_gap = min(low_wmark_pages(zone), DIV_ROUND_UP(
23334be89a34SJianyu Zhan 			zone->managed_pages, KSWAPD_ZONE_BALANCE_GAP_RATIO));
23340b06496aSJohannes Weiner 	watermark = high_wmark_pages(zone) + balance_gap + (2UL << order);
2335fe4b1b24SMel Gorman 	watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, 0, 0);
2336fe4b1b24SMel Gorman 
2337fe4b1b24SMel Gorman 	/*
2338fe4b1b24SMel Gorman 	 * If compaction is deferred, reclaim up to a point where
2339fe4b1b24SMel Gorman 	 * compaction will have a chance of success when re-enabled
2340fe4b1b24SMel Gorman 	 */
23410b06496aSJohannes Weiner 	if (compaction_deferred(zone, order))
2342fe4b1b24SMel Gorman 		return watermark_ok;
2343fe4b1b24SMel Gorman 
234453853e2dSVlastimil Babka 	/*
234553853e2dSVlastimil Babka 	 * If compaction is not ready to start and allocation is not likely
234653853e2dSVlastimil Babka 	 * to succeed without it, then keep reclaiming.
234753853e2dSVlastimil Babka 	 */
234853853e2dSVlastimil Babka 	if (compaction_suitable(zone, order) == COMPACT_SKIPPED)
2349fe4b1b24SMel Gorman 		return false;
2350fe4b1b24SMel Gorman 
2351fe4b1b24SMel Gorman 	return watermark_ok;
2352fe4b1b24SMel Gorman }
2353fe4b1b24SMel Gorman 
23541da177e4SLinus Torvalds /*
23551da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
23561da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
23571da177e4SLinus Torvalds  * request.
23581da177e4SLinus Torvalds  *
235941858966SMel Gorman  * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
236041858966SMel Gorman  * Because:
23611da177e4SLinus Torvalds  * a) The caller may be trying to free *extra* pages to satisfy a higher-order
23621da177e4SLinus Torvalds  *    allocation or
236341858966SMel Gorman  * b) The target zone may be at high_wmark_pages(zone) but the lower zones
236441858966SMel Gorman  *    must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
236541858966SMel Gorman  *    zone defense algorithm.
23661da177e4SLinus Torvalds  *
23671da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
23681da177e4SLinus Torvalds  * scan then give up on it.
23692344d7e4SJohannes Weiner  *
23702344d7e4SJohannes Weiner  * Returns true if a zone was reclaimable.
23711da177e4SLinus Torvalds  */
23722344d7e4SJohannes Weiner static bool shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
23731da177e4SLinus Torvalds {
2374dd1a239fSMel Gorman 	struct zoneref *z;
237554a6eb5cSMel Gorman 	struct zone *zone;
23760608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
23770608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
237865ec02cbSVladimir Davydov 	unsigned long lru_pages = 0;
237965ec02cbSVladimir Davydov 	struct reclaim_state *reclaim_state = current->reclaim_state;
2380619d0d76SWeijie Yang 	gfp_t orig_mask;
23813115cd91SVladimir Davydov 	struct shrink_control shrink = {
23823115cd91SVladimir Davydov 		.gfp_mask = sc->gfp_mask,
23833115cd91SVladimir Davydov 	};
23849bbc04eeSWeijie Yang 	enum zone_type requested_highidx = gfp_zone(sc->gfp_mask);
23852344d7e4SJohannes Weiner 	bool reclaimable = false;
23861cfb419bSKAMEZAWA Hiroyuki 
2387cc715d99SMel Gorman 	/*
2388cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2389cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2390cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2391cc715d99SMel Gorman 	 */
2392619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2393cc715d99SMel Gorman 	if (buffer_heads_over_limit)
2394cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
2395cc715d99SMel Gorman 
23963115cd91SVladimir Davydov 	nodes_clear(shrink.nodes_to_scan);
239765ec02cbSVladimir Davydov 
2398d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2399d4debc66SMel Gorman 					gfp_zone(sc->gfp_mask), sc->nodemask) {
2400f3fe6512SCon Kolivas 		if (!populated_zone(zone))
24011da177e4SLinus Torvalds 			continue;
24021cfb419bSKAMEZAWA Hiroyuki 		/*
24031cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
24041cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
24051cfb419bSKAMEZAWA Hiroyuki 		 */
240689b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
240702a0e53dSPaul Jackson 			if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
24081da177e4SLinus Torvalds 				continue;
240965ec02cbSVladimir Davydov 
241065ec02cbSVladimir Davydov 			lru_pages += zone_reclaimable_pages(zone);
24113115cd91SVladimir Davydov 			node_set(zone_to_nid(zone), shrink.nodes_to_scan);
241265ec02cbSVladimir Davydov 
24136e543d57SLisa Du 			if (sc->priority != DEF_PRIORITY &&
24146e543d57SLisa Du 			    !zone_reclaimable(zone))
24151da177e4SLinus Torvalds 				continue;	/* Let kswapd poll it */
24160b06496aSJohannes Weiner 
2417e0887c19SRik van Riel 			/*
2418e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2419e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2420e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2421e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2422e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2423c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2424c7cfa37bSCopot Alexandru 			 * page allocations.
2425e0887c19SRik van Riel 			 */
24260b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
24270b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
24280b06496aSJohannes Weiner 			    zonelist_zone_idx(z) <= requested_highidx &&
24290b06496aSJohannes Weiner 			    compaction_ready(zone, sc->order)) {
24300b06496aSJohannes Weiner 				sc->compaction_ready = true;
2431e0887c19SRik van Riel 				continue;
2432e0887c19SRik van Riel 			}
24330b06496aSJohannes Weiner 
24340608f43dSAndrew Morton 			/*
24350608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
24360608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
24370608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
24380608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
24390608f43dSAndrew Morton 			 */
24400608f43dSAndrew Morton 			nr_soft_scanned = 0;
24410608f43dSAndrew Morton 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
24420608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
24430608f43dSAndrew Morton 						&nr_soft_scanned);
24440608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
24450608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
24462344d7e4SJohannes Weiner 			if (nr_soft_reclaimed)
24472344d7e4SJohannes Weiner 				reclaimable = true;
2448ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2449ac34a1a3SKAMEZAWA Hiroyuki 		}
2450d149e3b2SYing Han 
24512344d7e4SJohannes Weiner 		if (shrink_zone(zone, sc))
24522344d7e4SJohannes Weiner 			reclaimable = true;
24532344d7e4SJohannes Weiner 
24542344d7e4SJohannes Weiner 		if (global_reclaim(sc) &&
24552344d7e4SJohannes Weiner 		    !reclaimable && zone_reclaimable(zone))
24562344d7e4SJohannes Weiner 			reclaimable = true;
24571da177e4SLinus Torvalds 	}
2458e0c23279SMel Gorman 
245965ec02cbSVladimir Davydov 	/*
246065ec02cbSVladimir Davydov 	 * Don't shrink slabs when reclaiming memory from over limit cgroups
246165ec02cbSVladimir Davydov 	 * but do shrink slab at least once when aborting reclaim for
246265ec02cbSVladimir Davydov 	 * compaction to avoid unevenly scanning file/anon LRU pages over slab
246365ec02cbSVladimir Davydov 	 * pages.
246465ec02cbSVladimir Davydov 	 */
246565ec02cbSVladimir Davydov 	if (global_reclaim(sc)) {
24663115cd91SVladimir Davydov 		shrink_slab(&shrink, sc->nr_scanned, lru_pages);
246765ec02cbSVladimir Davydov 		if (reclaim_state) {
246865ec02cbSVladimir Davydov 			sc->nr_reclaimed += reclaim_state->reclaimed_slab;
246965ec02cbSVladimir Davydov 			reclaim_state->reclaimed_slab = 0;
247065ec02cbSVladimir Davydov 		}
247165ec02cbSVladimir Davydov 	}
247265ec02cbSVladimir Davydov 
2473619d0d76SWeijie Yang 	/*
2474619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2475619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
2476619d0d76SWeijie Yang 	 */
2477619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
2478d1908362SMinchan Kim 
24792344d7e4SJohannes Weiner 	return reclaimable;
24801da177e4SLinus Torvalds }
24811da177e4SLinus Torvalds 
24821da177e4SLinus Torvalds /*
24831da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
24841da177e4SLinus Torvalds  *
24851da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
24861da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
24871da177e4SLinus Torvalds  *
24881da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
24891da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
24905b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
24915b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
24925b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
24935b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2494a41f24eaSNishanth Aravamudan  *
2495a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2496a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
24971da177e4SLinus Torvalds  */
2498dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
24993115cd91SVladimir Davydov 					  struct scan_control *sc)
25001da177e4SLinus Torvalds {
250169e05944SAndrew Morton 	unsigned long total_scanned = 0;
250222fba335SKOSAKI Motohiro 	unsigned long writeback_threshold;
25032344d7e4SJohannes Weiner 	bool zones_reclaimable;
25041da177e4SLinus Torvalds 
2505873b4771SKeika Kobayashi 	delayacct_freepages_start();
2506873b4771SKeika Kobayashi 
250789b5fae5SJohannes Weiner 	if (global_reclaim(sc))
2508f8891e5eSChristoph Lameter 		count_vm_event(ALLOCSTALL);
25091da177e4SLinus Torvalds 
25109e3b2f8cSKonstantin Khlebnikov 	do {
251170ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
251270ddf637SAnton Vorontsov 				sc->priority);
251366e1707bSBalbir Singh 		sc->nr_scanned = 0;
25142344d7e4SJohannes Weiner 		zones_reclaimable = shrink_zones(zonelist, sc);
2515e0c23279SMel Gorman 
251666e1707bSBalbir Singh 		total_scanned += sc->nr_scanned;
2517bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
25180b06496aSJohannes Weiner 			break;
25190b06496aSJohannes Weiner 
25200b06496aSJohannes Weiner 		if (sc->compaction_ready)
25210b06496aSJohannes Weiner 			break;
25221da177e4SLinus Torvalds 
25231da177e4SLinus Torvalds 		/*
25240e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
25250e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
25260e50ce3bSMinchan Kim 		 */
25270e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
25280e50ce3bSMinchan Kim 			sc->may_writepage = 1;
25290e50ce3bSMinchan Kim 
25300e50ce3bSMinchan Kim 		/*
25311da177e4SLinus Torvalds 		 * Try to write back as many pages as we just scanned.  This
25321da177e4SLinus Torvalds 		 * tends to cause slow streaming writers to write data to the
25331da177e4SLinus Torvalds 		 * disk smoothly, at the dirtying rate, which is nice.   But
25341da177e4SLinus Torvalds 		 * that's undesirable in laptop mode, where we *want* lumpy
25351da177e4SLinus Torvalds 		 * writeout.  So in laptop mode, write out the whole world.
25361da177e4SLinus Torvalds 		 */
253722fba335SKOSAKI Motohiro 		writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
253822fba335SKOSAKI Motohiro 		if (total_scanned > writeback_threshold) {
25390e175a18SCurt Wohlgemuth 			wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
25400e175a18SCurt Wohlgemuth 						WB_REASON_TRY_TO_FREE_PAGES);
254166e1707bSBalbir Singh 			sc->may_writepage = 1;
25421da177e4SLinus Torvalds 		}
25430b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
2544bb21c7ceSKOSAKI Motohiro 
2545873b4771SKeika Kobayashi 	delayacct_freepages_end();
2546873b4771SKeika Kobayashi 
2547bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2548bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2549bb21c7ceSKOSAKI Motohiro 
25500cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
25510b06496aSJohannes Weiner 	if (sc->compaction_ready)
25527335084dSMel Gorman 		return 1;
25537335084dSMel Gorman 
25542344d7e4SJohannes Weiner 	/* Any of the zones still reclaimable?  Don't OOM. */
25552344d7e4SJohannes Weiner 	if (zones_reclaimable)
2556bb21c7ceSKOSAKI Motohiro 		return 1;
2557bb21c7ceSKOSAKI Motohiro 
2558bb21c7ceSKOSAKI Motohiro 	return 0;
25591da177e4SLinus Torvalds }
25601da177e4SLinus Torvalds 
25615515061dSMel Gorman static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
25625515061dSMel Gorman {
25635515061dSMel Gorman 	struct zone *zone;
25645515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
25655515061dSMel Gorman 	unsigned long free_pages = 0;
25665515061dSMel Gorman 	int i;
25675515061dSMel Gorman 	bool wmark_ok;
25685515061dSMel Gorman 
25695515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
25705515061dSMel Gorman 		zone = &pgdat->node_zones[i];
2571675becceSMel Gorman 		if (!populated_zone(zone))
2572675becceSMel Gorman 			continue;
2573675becceSMel Gorman 
25745515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
25755515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
25765515061dSMel Gorman 	}
25775515061dSMel Gorman 
2578675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
2579675becceSMel Gorman 	if (!pfmemalloc_reserve)
2580675becceSMel Gorman 		return true;
2581675becceSMel Gorman 
25825515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
25835515061dSMel Gorman 
25845515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
25855515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
25865515061dSMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx,
25875515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
25885515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
25895515061dSMel Gorman 	}
25905515061dSMel Gorman 
25915515061dSMel Gorman 	return wmark_ok;
25925515061dSMel Gorman }
25935515061dSMel Gorman 
25945515061dSMel Gorman /*
25955515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
25965515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
25975515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
259850694c28SMel Gorman  * when the low watermark is reached.
259950694c28SMel Gorman  *
260050694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
260150694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
26025515061dSMel Gorman  */
260350694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
26045515061dSMel Gorman 					nodemask_t *nodemask)
26055515061dSMel Gorman {
2606675becceSMel Gorman 	struct zoneref *z;
26075515061dSMel Gorman 	struct zone *zone;
2608675becceSMel Gorman 	pg_data_t *pgdat = NULL;
26095515061dSMel Gorman 
26105515061dSMel Gorman 	/*
26115515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
26125515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
26135515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
26145515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
26155515061dSMel Gorman 	 * processes to block on log_wait_commit().
26165515061dSMel Gorman 	 */
26175515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
261850694c28SMel Gorman 		goto out;
261950694c28SMel Gorman 
262050694c28SMel Gorman 	/*
262150694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
262250694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
262350694c28SMel Gorman 	 */
262450694c28SMel Gorman 	if (fatal_signal_pending(current))
262550694c28SMel Gorman 		goto out;
26265515061dSMel Gorman 
2627675becceSMel Gorman 	/*
2628675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
2629675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
2630675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
2631675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
2632675becceSMel Gorman 	 *
2633675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
2634675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
2635675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
2636675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
2637675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
2638675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
2639675becceSMel Gorman 	 * should make reasonable progress.
2640675becceSMel Gorman 	 */
2641675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2642675becceSMel Gorman 					gfp_mask, nodemask) {
2643675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
2644675becceSMel Gorman 			continue;
2645675becceSMel Gorman 
2646675becceSMel Gorman 		/* Throttle based on the first usable node */
26475515061dSMel Gorman 		pgdat = zone->zone_pgdat;
26485515061dSMel Gorman 		if (pfmemalloc_watermark_ok(pgdat))
264950694c28SMel Gorman 			goto out;
2650675becceSMel Gorman 		break;
2651675becceSMel Gorman 	}
2652675becceSMel Gorman 
2653675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
2654675becceSMel Gorman 	if (!pgdat)
2655675becceSMel Gorman 		goto out;
26565515061dSMel Gorman 
265768243e76SMel Gorman 	/* Account for the throttling */
265868243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
265968243e76SMel Gorman 
26605515061dSMel Gorman 	/*
26615515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
26625515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
26635515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
26645515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
26655515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
26665515061dSMel Gorman 	 * second before continuing.
26675515061dSMel Gorman 	 */
26685515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
26695515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
26705515061dSMel Gorman 			pfmemalloc_watermark_ok(pgdat), HZ);
267150694c28SMel Gorman 
267250694c28SMel Gorman 		goto check_pending;
26735515061dSMel Gorman 	}
26745515061dSMel Gorman 
26755515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
26765515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
26775515061dSMel Gorman 		pfmemalloc_watermark_ok(pgdat));
267850694c28SMel Gorman 
267950694c28SMel Gorman check_pending:
268050694c28SMel Gorman 	if (fatal_signal_pending(current))
268150694c28SMel Gorman 		return true;
268250694c28SMel Gorman 
268350694c28SMel Gorman out:
268450694c28SMel Gorman 	return false;
26855515061dSMel Gorman }
26865515061dSMel Gorman 
2687dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2688327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
268966e1707bSBalbir Singh {
269033906bc5SMel Gorman 	unsigned long nr_reclaimed;
269166e1707bSBalbir Singh 	struct scan_control sc = {
269222fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2693ee814fe2SJohannes Weiner 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
2694ee814fe2SJohannes Weiner 		.order = order,
2695ee814fe2SJohannes Weiner 		.nodemask = nodemask,
2696ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
2697ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
2698a6dc60f8SJohannes Weiner 		.may_unmap = 1,
26992e2e4259SKOSAKI Motohiro 		.may_swap = 1,
270066e1707bSBalbir Singh 	};
270166e1707bSBalbir Singh 
27025515061dSMel Gorman 	/*
270350694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
270450694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
270550694c28SMel Gorman 	 * point.
27065515061dSMel Gorman 	 */
270750694c28SMel Gorman 	if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
27085515061dSMel Gorman 		return 1;
27095515061dSMel Gorman 
271033906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
271133906bc5SMel Gorman 				sc.may_writepage,
271233906bc5SMel Gorman 				gfp_mask);
271333906bc5SMel Gorman 
27143115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
271533906bc5SMel Gorman 
271633906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
271733906bc5SMel Gorman 
271833906bc5SMel Gorman 	return nr_reclaimed;
271966e1707bSBalbir Singh }
272066e1707bSBalbir Singh 
2721c255a458SAndrew Morton #ifdef CONFIG_MEMCG
272266e1707bSBalbir Singh 
272372835c86SJohannes Weiner unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg,
27244e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
27250ae5e89cSYing Han 						struct zone *zone,
27260ae5e89cSYing Han 						unsigned long *nr_scanned)
27274e416953SBalbir Singh {
27284e416953SBalbir Singh 	struct scan_control sc = {
2729b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2730ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
27314e416953SBalbir Singh 		.may_writepage = !laptop_mode,
27324e416953SBalbir Singh 		.may_unmap = 1,
27334e416953SBalbir Singh 		.may_swap = !noswap,
27344e416953SBalbir Singh 	};
2735f9be23d6SKonstantin Khlebnikov 	struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
273602695175SJohannes Weiner 	int swappiness = mem_cgroup_swappiness(memcg);
27370ae5e89cSYing Han 
27384e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
27394e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2740bdce6d9eSKOSAKI Motohiro 
27419e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
2742bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
2743bdce6d9eSKOSAKI Motohiro 						      sc.gfp_mask);
2744bdce6d9eSKOSAKI Motohiro 
27454e416953SBalbir Singh 	/*
27464e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
27474e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
27484e416953SBalbir Singh 	 * if we don't reclaim here, the shrink_zone from balance_pgdat
27494e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
27504e416953SBalbir Singh 	 * the priority and make it zero.
27514e416953SBalbir Singh 	 */
275202695175SJohannes Weiner 	shrink_lruvec(lruvec, swappiness, &sc);
2753bdce6d9eSKOSAKI Motohiro 
2754bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
2755bdce6d9eSKOSAKI Motohiro 
27560ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
27574e416953SBalbir Singh 	return sc.nr_reclaimed;
27584e416953SBalbir Singh }
27594e416953SBalbir Singh 
276072835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
2761b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
27628c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
2763b70a2a21SJohannes Weiner 					   bool may_swap)
276466e1707bSBalbir Singh {
27654e416953SBalbir Singh 	struct zonelist *zonelist;
2766bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
2767889976dbSYing Han 	int nid;
276866e1707bSBalbir Singh 	struct scan_control sc = {
2769b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
2770ee814fe2SJohannes Weiner 		.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2771ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
2772ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
2773ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
277466e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
2775a6dc60f8SJohannes Weiner 		.may_unmap = 1,
2776b70a2a21SJohannes Weiner 		.may_swap = may_swap,
2777a09ed5e0SYing Han 	};
277866e1707bSBalbir Singh 
2779889976dbSYing Han 	/*
2780889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
2781889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
2782889976dbSYing Han 	 * scan does not need to be the current node.
2783889976dbSYing Han 	 */
278472835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
2785889976dbSYing Han 
2786889976dbSYing Han 	zonelist = NODE_DATA(nid)->node_zonelists;
2787bdce6d9eSKOSAKI Motohiro 
2788bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
2789bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
2790bdce6d9eSKOSAKI Motohiro 					    sc.gfp_mask);
2791bdce6d9eSKOSAKI Motohiro 
27923115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
2793bdce6d9eSKOSAKI Motohiro 
2794bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
2795bdce6d9eSKOSAKI Motohiro 
2796bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
279766e1707bSBalbir Singh }
279866e1707bSBalbir Singh #endif
279966e1707bSBalbir Singh 
28009e3b2f8cSKonstantin Khlebnikov static void age_active_anon(struct zone *zone, struct scan_control *sc)
2801f16015fbSJohannes Weiner {
2802b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
2803b95a2f2dSJohannes Weiner 
2804b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
2805b95a2f2dSJohannes Weiner 		return;
2806b95a2f2dSJohannes Weiner 
2807b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
2808b95a2f2dSJohannes Weiner 	do {
2809c56d5c7dSKonstantin Khlebnikov 		struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
2810f16015fbSJohannes Weiner 
2811c56d5c7dSKonstantin Khlebnikov 		if (inactive_anon_is_low(lruvec))
28121a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
28139e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
2814b95a2f2dSJohannes Weiner 
2815b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
2816b95a2f2dSJohannes Weiner 	} while (memcg);
2817f16015fbSJohannes Weiner }
2818f16015fbSJohannes Weiner 
281960cefed4SJohannes Weiner static bool zone_balanced(struct zone *zone, int order,
282060cefed4SJohannes Weiner 			  unsigned long balance_gap, int classzone_idx)
282160cefed4SJohannes Weiner {
282260cefed4SJohannes Weiner 	if (!zone_watermark_ok_safe(zone, order, high_wmark_pages(zone) +
282360cefed4SJohannes Weiner 				    balance_gap, classzone_idx, 0))
282460cefed4SJohannes Weiner 		return false;
282560cefed4SJohannes Weiner 
2826d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && order &&
282753853e2dSVlastimil Babka 	    compaction_suitable(zone, order) == COMPACT_SKIPPED)
282860cefed4SJohannes Weiner 		return false;
282960cefed4SJohannes Weiner 
283060cefed4SJohannes Weiner 	return true;
283160cefed4SJohannes Weiner }
283260cefed4SJohannes Weiner 
28331741c877SMel Gorman /*
28344ae0a48bSZlatko Calusic  * pgdat_balanced() is used when checking if a node is balanced.
28354ae0a48bSZlatko Calusic  *
28364ae0a48bSZlatko Calusic  * For order-0, all zones must be balanced!
28374ae0a48bSZlatko Calusic  *
28384ae0a48bSZlatko Calusic  * For high-order allocations only zones that meet watermarks and are in a
28394ae0a48bSZlatko Calusic  * zone allowed by the callers classzone_idx are added to balanced_pages. The
28404ae0a48bSZlatko Calusic  * total of balanced pages must be at least 25% of the zones allowed by
28414ae0a48bSZlatko Calusic  * classzone_idx for the node to be considered balanced. Forcing all zones to
28424ae0a48bSZlatko Calusic  * be balanced for high orders can cause excessive reclaim when there are
28434ae0a48bSZlatko Calusic  * imbalanced zones.
28441741c877SMel Gorman  * The choice of 25% is due to
28451741c877SMel Gorman  *   o a 16M DMA zone that is balanced will not balance a zone on any
28461741c877SMel Gorman  *     reasonable sized machine
28471741c877SMel Gorman  *   o On all other machines, the top zone must be at least a reasonable
284825985edcSLucas De Marchi  *     percentage of the middle zones. For example, on 32-bit x86, highmem
28491741c877SMel Gorman  *     would need to be at least 256M for it to be balance a whole node.
28501741c877SMel Gorman  *     Similarly, on x86-64 the Normal zone would need to be at least 1G
28511741c877SMel Gorman  *     to balance a node on its own. These seemed like reasonable ratios.
28521741c877SMel Gorman  */
28534ae0a48bSZlatko Calusic static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
28541741c877SMel Gorman {
2855b40da049SJiang Liu 	unsigned long managed_pages = 0;
28564ae0a48bSZlatko Calusic 	unsigned long balanced_pages = 0;
28571741c877SMel Gorman 	int i;
28581741c877SMel Gorman 
28594ae0a48bSZlatko Calusic 	/* Check the watermark levels */
28604ae0a48bSZlatko Calusic 	for (i = 0; i <= classzone_idx; i++) {
28614ae0a48bSZlatko Calusic 		struct zone *zone = pgdat->node_zones + i;
28621741c877SMel Gorman 
28634ae0a48bSZlatko Calusic 		if (!populated_zone(zone))
28644ae0a48bSZlatko Calusic 			continue;
28654ae0a48bSZlatko Calusic 
2866b40da049SJiang Liu 		managed_pages += zone->managed_pages;
28674ae0a48bSZlatko Calusic 
28684ae0a48bSZlatko Calusic 		/*
28694ae0a48bSZlatko Calusic 		 * A special case here:
28704ae0a48bSZlatko Calusic 		 *
28714ae0a48bSZlatko Calusic 		 * balance_pgdat() skips over all_unreclaimable after
28724ae0a48bSZlatko Calusic 		 * DEF_PRIORITY. Effectively, it considers them balanced so
28734ae0a48bSZlatko Calusic 		 * they must be considered balanced here as well!
28744ae0a48bSZlatko Calusic 		 */
28756e543d57SLisa Du 		if (!zone_reclaimable(zone)) {
2876b40da049SJiang Liu 			balanced_pages += zone->managed_pages;
28774ae0a48bSZlatko Calusic 			continue;
28784ae0a48bSZlatko Calusic 		}
28794ae0a48bSZlatko Calusic 
28804ae0a48bSZlatko Calusic 		if (zone_balanced(zone, order, 0, i))
2881b40da049SJiang Liu 			balanced_pages += zone->managed_pages;
28824ae0a48bSZlatko Calusic 		else if (!order)
28834ae0a48bSZlatko Calusic 			return false;
28844ae0a48bSZlatko Calusic 	}
28854ae0a48bSZlatko Calusic 
28864ae0a48bSZlatko Calusic 	if (order)
2887b40da049SJiang Liu 		return balanced_pages >= (managed_pages >> 2);
28884ae0a48bSZlatko Calusic 	else
28894ae0a48bSZlatko Calusic 		return true;
28901741c877SMel Gorman }
28911741c877SMel Gorman 
28925515061dSMel Gorman /*
28935515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
28945515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
28955515061dSMel Gorman  *
28965515061dSMel Gorman  * Returns true if kswapd is ready to sleep
28975515061dSMel Gorman  */
28985515061dSMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, long remaining,
2899dc83edd9SMel Gorman 					int classzone_idx)
2900f50de2d3SMel Gorman {
2901f50de2d3SMel Gorman 	/* If a direct reclaimer woke kswapd within HZ/10, it's premature */
2902f50de2d3SMel Gorman 	if (remaining)
29035515061dSMel Gorman 		return false;
29045515061dSMel Gorman 
29055515061dSMel Gorman 	/*
29065515061dSMel Gorman 	 * There is a potential race between when kswapd checks its watermarks
29075515061dSMel Gorman 	 * and a process gets throttled. There is also a potential race if
29085515061dSMel Gorman 	 * processes get throttled, kswapd wakes, a large process exits therby
29095515061dSMel Gorman 	 * balancing the zones that causes kswapd to miss a wakeup. If kswapd
29105515061dSMel Gorman 	 * is going to sleep, no process should be sleeping on pfmemalloc_wait
29115515061dSMel Gorman 	 * so wake them now if necessary. If necessary, processes will wake
29125515061dSMel Gorman 	 * kswapd and get throttled again
29135515061dSMel Gorman 	 */
29145515061dSMel Gorman 	if (waitqueue_active(&pgdat->pfmemalloc_wait)) {
29155515061dSMel Gorman 		wake_up(&pgdat->pfmemalloc_wait);
29165515061dSMel Gorman 		return false;
29175515061dSMel Gorman 	}
2918f50de2d3SMel Gorman 
29194ae0a48bSZlatko Calusic 	return pgdat_balanced(pgdat, order, classzone_idx);
2920f50de2d3SMel Gorman }
2921f50de2d3SMel Gorman 
29221da177e4SLinus Torvalds /*
292375485363SMel Gorman  * kswapd shrinks the zone by the number of pages required to reach
292475485363SMel Gorman  * the high watermark.
2925b8e83b94SMel Gorman  *
2926b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
2927283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
2928283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
292975485363SMel Gorman  */
2930b8e83b94SMel Gorman static bool kswapd_shrink_zone(struct zone *zone,
29317c954f6dSMel Gorman 			       int classzone_idx,
293275485363SMel Gorman 			       struct scan_control *sc,
29332ab44f43SMel Gorman 			       unsigned long lru_pages,
29342ab44f43SMel Gorman 			       unsigned long *nr_attempted)
293575485363SMel Gorman {
29367c954f6dSMel Gorman 	int testorder = sc->order;
29377c954f6dSMel Gorman 	unsigned long balance_gap;
293875485363SMel Gorman 	struct reclaim_state *reclaim_state = current->reclaim_state;
293975485363SMel Gorman 	struct shrink_control shrink = {
294075485363SMel Gorman 		.gfp_mask = sc->gfp_mask,
294175485363SMel Gorman 	};
29427c954f6dSMel Gorman 	bool lowmem_pressure;
294375485363SMel Gorman 
294475485363SMel Gorman 	/* Reclaim above the high watermark. */
294575485363SMel Gorman 	sc->nr_to_reclaim = max(SWAP_CLUSTER_MAX, high_wmark_pages(zone));
29467c954f6dSMel Gorman 
29477c954f6dSMel Gorman 	/*
29487c954f6dSMel Gorman 	 * Kswapd reclaims only single pages with compaction enabled. Trying
29497c954f6dSMel Gorman 	 * too hard to reclaim until contiguous free pages have become
29507c954f6dSMel Gorman 	 * available can hurt performance by evicting too much useful data
29517c954f6dSMel Gorman 	 * from memory. Do not reclaim more than needed for compaction.
29527c954f6dSMel Gorman 	 */
29537c954f6dSMel Gorman 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
29547c954f6dSMel Gorman 			compaction_suitable(zone, sc->order) !=
29557c954f6dSMel Gorman 				COMPACT_SKIPPED)
29567c954f6dSMel Gorman 		testorder = 0;
29577c954f6dSMel Gorman 
29587c954f6dSMel Gorman 	/*
29597c954f6dSMel Gorman 	 * We put equal pressure on every zone, unless one zone has way too
29607c954f6dSMel Gorman 	 * many pages free already. The "too many pages" is defined as the
29617c954f6dSMel Gorman 	 * high wmark plus a "gap" where the gap is either the low
29627c954f6dSMel Gorman 	 * watermark or 1% of the zone, whichever is smaller.
29637c954f6dSMel Gorman 	 */
29644be89a34SJianyu Zhan 	balance_gap = min(low_wmark_pages(zone), DIV_ROUND_UP(
29654be89a34SJianyu Zhan 			zone->managed_pages, KSWAPD_ZONE_BALANCE_GAP_RATIO));
29667c954f6dSMel Gorman 
29677c954f6dSMel Gorman 	/*
29687c954f6dSMel Gorman 	 * If there is no low memory pressure or the zone is balanced then no
29697c954f6dSMel Gorman 	 * reclaim is necessary
29707c954f6dSMel Gorman 	 */
29717c954f6dSMel Gorman 	lowmem_pressure = (buffer_heads_over_limit && is_highmem(zone));
29727c954f6dSMel Gorman 	if (!lowmem_pressure && zone_balanced(zone, testorder,
29737c954f6dSMel Gorman 						balance_gap, classzone_idx))
29747c954f6dSMel Gorman 		return true;
29757c954f6dSMel Gorman 
297675485363SMel Gorman 	shrink_zone(zone, sc);
29770ce3d744SDave Chinner 	nodes_clear(shrink.nodes_to_scan);
29780ce3d744SDave Chinner 	node_set(zone_to_nid(zone), shrink.nodes_to_scan);
297975485363SMel Gorman 
298075485363SMel Gorman 	reclaim_state->reclaimed_slab = 0;
29816e543d57SLisa Du 	shrink_slab(&shrink, sc->nr_scanned, lru_pages);
298275485363SMel Gorman 	sc->nr_reclaimed += reclaim_state->reclaimed_slab;
298375485363SMel Gorman 
29842ab44f43SMel Gorman 	/* Account for the number of pages attempted to reclaim */
29852ab44f43SMel Gorman 	*nr_attempted += sc->nr_to_reclaim;
29862ab44f43SMel Gorman 
298757054651SJohannes Weiner 	clear_bit(ZONE_WRITEBACK, &zone->flags);
2988283aba9fSMel Gorman 
29897c954f6dSMel Gorman 	/*
29907c954f6dSMel Gorman 	 * If a zone reaches its high watermark, consider it to be no longer
29917c954f6dSMel Gorman 	 * congested. It's possible there are dirty pages backed by congested
29927c954f6dSMel Gorman 	 * BDIs but as pressure is relieved, speculatively avoid congestion
29937c954f6dSMel Gorman 	 * waits.
29947c954f6dSMel Gorman 	 */
29956e543d57SLisa Du 	if (zone_reclaimable(zone) &&
29967c954f6dSMel Gorman 	    zone_balanced(zone, testorder, 0, classzone_idx)) {
299757054651SJohannes Weiner 		clear_bit(ZONE_CONGESTED, &zone->flags);
299857054651SJohannes Weiner 		clear_bit(ZONE_DIRTY, &zone->flags);
29997c954f6dSMel Gorman 	}
30007c954f6dSMel Gorman 
3001b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
300275485363SMel Gorman }
300375485363SMel Gorman 
300475485363SMel Gorman /*
30051da177e4SLinus Torvalds  * For kswapd, balance_pgdat() will work across all this node's zones until
300641858966SMel Gorman  * they are all at high_wmark_pages(zone).
30071da177e4SLinus Torvalds  *
30080abdee2bSMel Gorman  * Returns the final order kswapd was reclaiming at
30091da177e4SLinus Torvalds  *
30101da177e4SLinus Torvalds  * There is special handling here for zones which are full of pinned pages.
30111da177e4SLinus Torvalds  * This can happen if the pages are all mlocked, or if they are all used by
30121da177e4SLinus Torvalds  * device drivers (say, ZONE_DMA).  Or if they are all in use by hugetlb.
30131da177e4SLinus Torvalds  * What we do is to detect the case where all pages in the zone have been
30141da177e4SLinus Torvalds  * scanned twice and there has been zero successful reclaim.  Mark the zone as
30151da177e4SLinus Torvalds  * dead and from now on, only perform a short scan.  Basically we're polling
30161da177e4SLinus Torvalds  * the zone for when the problem goes away.
30171da177e4SLinus Torvalds  *
30181da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
301941858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
302041858966SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
302141858966SMel Gorman  * lower zones regardless of the number of free pages in the lower zones. This
302241858966SMel Gorman  * interoperates with the page allocator fallback scheme to ensure that aging
302341858966SMel Gorman  * of pages is balanced across the zones.
30241da177e4SLinus Torvalds  */
302599504748SMel Gorman static unsigned long balance_pgdat(pg_data_t *pgdat, int order,
3026dc83edd9SMel Gorman 							int *classzone_idx)
30271da177e4SLinus Torvalds {
30281da177e4SLinus Torvalds 	int i;
302999504748SMel Gorman 	int end_zone = 0;	/* Inclusive.  0 = ZONE_DMA */
30300608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
30310608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3032179e9639SAndrew Morton 	struct scan_control sc = {
3033179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3034ee814fe2SJohannes Weiner 		.order = order,
3035b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
3036ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3037a6dc60f8SJohannes Weiner 		.may_unmap = 1,
30382e2e4259SKOSAKI Motohiro 		.may_swap = 1,
3039179e9639SAndrew Morton 	};
3040f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
30411da177e4SLinus Torvalds 
30429e3b2f8cSKonstantin Khlebnikov 	do {
30431da177e4SLinus Torvalds 		unsigned long lru_pages = 0;
30442ab44f43SMel Gorman 		unsigned long nr_attempted = 0;
3045b8e83b94SMel Gorman 		bool raise_priority = true;
30462ab44f43SMel Gorman 		bool pgdat_needs_compaction = (order > 0);
3047b8e83b94SMel Gorman 
3048b8e83b94SMel Gorman 		sc.nr_reclaimed = 0;
30491da177e4SLinus Torvalds 
30501da177e4SLinus Torvalds 		/*
30511da177e4SLinus Torvalds 		 * Scan in the highmem->dma direction for the highest
30521da177e4SLinus Torvalds 		 * zone which needs scanning
30531da177e4SLinus Torvalds 		 */
30541da177e4SLinus Torvalds 		for (i = pgdat->nr_zones - 1; i >= 0; i--) {
30551da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
30561da177e4SLinus Torvalds 
3057f3fe6512SCon Kolivas 			if (!populated_zone(zone))
30581da177e4SLinus Torvalds 				continue;
30591da177e4SLinus Torvalds 
30606e543d57SLisa Du 			if (sc.priority != DEF_PRIORITY &&
30616e543d57SLisa Du 			    !zone_reclaimable(zone))
30621da177e4SLinus Torvalds 				continue;
30631da177e4SLinus Torvalds 
3064556adecbSRik van Riel 			/*
3065556adecbSRik van Riel 			 * Do some background aging of the anon list, to give
3066556adecbSRik van Riel 			 * pages a chance to be referenced before reclaiming.
3067556adecbSRik van Riel 			 */
30689e3b2f8cSKonstantin Khlebnikov 			age_active_anon(zone, &sc);
3069556adecbSRik van Riel 
3070cc715d99SMel Gorman 			/*
3071cc715d99SMel Gorman 			 * If the number of buffer_heads in the machine
3072cc715d99SMel Gorman 			 * exceeds the maximum allowed level and this node
3073cc715d99SMel Gorman 			 * has a highmem zone, force kswapd to reclaim from
3074cc715d99SMel Gorman 			 * it to relieve lowmem pressure.
3075cc715d99SMel Gorman 			 */
3076cc715d99SMel Gorman 			if (buffer_heads_over_limit && is_highmem_idx(i)) {
3077cc715d99SMel Gorman 				end_zone = i;
3078cc715d99SMel Gorman 				break;
3079cc715d99SMel Gorman 			}
3080cc715d99SMel Gorman 
308160cefed4SJohannes Weiner 			if (!zone_balanced(zone, order, 0, 0)) {
30821da177e4SLinus Torvalds 				end_zone = i;
3083e1dbeda6SAndrew Morton 				break;
3084439423f6SShaohua Li 			} else {
3085d43006d5SMel Gorman 				/*
3086d43006d5SMel Gorman 				 * If balanced, clear the dirty and congested
3087d43006d5SMel Gorman 				 * flags
3088d43006d5SMel Gorman 				 */
308957054651SJohannes Weiner 				clear_bit(ZONE_CONGESTED, &zone->flags);
309057054651SJohannes Weiner 				clear_bit(ZONE_DIRTY, &zone->flags);
30911da177e4SLinus Torvalds 			}
30921da177e4SLinus Torvalds 		}
3093dafcb73eSZlatko Calusic 
3094b8e83b94SMel Gorman 		if (i < 0)
30951da177e4SLinus Torvalds 			goto out;
3096e1dbeda6SAndrew Morton 
30971da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
30981da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
30991da177e4SLinus Torvalds 
31002ab44f43SMel Gorman 			if (!populated_zone(zone))
31012ab44f43SMel Gorman 				continue;
31022ab44f43SMel Gorman 
3103adea02a1SWu Fengguang 			lru_pages += zone_reclaimable_pages(zone);
31042ab44f43SMel Gorman 
31052ab44f43SMel Gorman 			/*
31062ab44f43SMel Gorman 			 * If any zone is currently balanced then kswapd will
31072ab44f43SMel Gorman 			 * not call compaction as it is expected that the
31082ab44f43SMel Gorman 			 * necessary pages are already available.
31092ab44f43SMel Gorman 			 */
31102ab44f43SMel Gorman 			if (pgdat_needs_compaction &&
31112ab44f43SMel Gorman 					zone_watermark_ok(zone, order,
31122ab44f43SMel Gorman 						low_wmark_pages(zone),
31132ab44f43SMel Gorman 						*classzone_idx, 0))
31142ab44f43SMel Gorman 				pgdat_needs_compaction = false;
31151da177e4SLinus Torvalds 		}
31161da177e4SLinus Torvalds 
31171da177e4SLinus Torvalds 		/*
3118b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3119b7ea3c41SMel Gorman 		 * even in laptop mode.
3120b7ea3c41SMel Gorman 		 */
3121b7ea3c41SMel Gorman 		if (sc.priority < DEF_PRIORITY - 2)
3122b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3123b7ea3c41SMel Gorman 
3124b7ea3c41SMel Gorman 		/*
31251da177e4SLinus Torvalds 		 * Now scan the zone in the dma->highmem direction, stopping
31261da177e4SLinus Torvalds 		 * at the last zone which needs scanning.
31271da177e4SLinus Torvalds 		 *
31281da177e4SLinus Torvalds 		 * We do this because the page allocator works in the opposite
31291da177e4SLinus Torvalds 		 * direction.  This prevents the page allocator from allocating
31301da177e4SLinus Torvalds 		 * pages behind kswapd's direction of progress, which would
31311da177e4SLinus Torvalds 		 * cause too much scanning of the lower zones.
31321da177e4SLinus Torvalds 		 */
31331da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
31341da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
31351da177e4SLinus Torvalds 
3136f3fe6512SCon Kolivas 			if (!populated_zone(zone))
31371da177e4SLinus Torvalds 				continue;
31381da177e4SLinus Torvalds 
31396e543d57SLisa Du 			if (sc.priority != DEF_PRIORITY &&
31406e543d57SLisa Du 			    !zone_reclaimable(zone))
31411da177e4SLinus Torvalds 				continue;
31421da177e4SLinus Torvalds 
31431da177e4SLinus Torvalds 			sc.nr_scanned = 0;
31444e416953SBalbir Singh 
31450608f43dSAndrew Morton 			nr_soft_scanned = 0;
31460608f43dSAndrew Morton 			/*
31470608f43dSAndrew Morton 			 * Call soft limit reclaim before calling shrink_zone.
31480608f43dSAndrew Morton 			 */
31490608f43dSAndrew Morton 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
31500608f43dSAndrew Morton 							order, sc.gfp_mask,
31510608f43dSAndrew Morton 							&nr_soft_scanned);
31520608f43dSAndrew Morton 			sc.nr_reclaimed += nr_soft_reclaimed;
31530608f43dSAndrew Morton 
315432a4330dSRik van Riel 			/*
31557c954f6dSMel Gorman 			 * There should be no need to raise the scanning
31567c954f6dSMel Gorman 			 * priority if enough pages are already being scanned
31577c954f6dSMel Gorman 			 * that that high watermark would be met at 100%
31587c954f6dSMel Gorman 			 * efficiency.
315932a4330dSRik van Riel 			 */
31607c954f6dSMel Gorman 			if (kswapd_shrink_zone(zone, end_zone, &sc,
31617c954f6dSMel Gorman 					lru_pages, &nr_attempted))
3162b8e83b94SMel Gorman 				raise_priority = false;
3163b8e83b94SMel Gorman 		}
3164d7868daeSMel Gorman 
31655515061dSMel Gorman 		/*
31665515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
31675515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
31685515061dSMel Gorman 		 * able to safely make forward progress. Wake them
31695515061dSMel Gorman 		 */
31705515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
31715515061dSMel Gorman 				pfmemalloc_watermark_ok(pgdat))
31725515061dSMel Gorman 			wake_up(&pgdat->pfmemalloc_wait);
31735515061dSMel Gorman 
31741da177e4SLinus Torvalds 		/*
3175b8e83b94SMel Gorman 		 * Fragmentation may mean that the system cannot be rebalanced
3176b8e83b94SMel Gorman 		 * for high-order allocations in all zones. If twice the
3177b8e83b94SMel Gorman 		 * allocation size has been reclaimed and the zones are still
3178b8e83b94SMel Gorman 		 * not balanced then recheck the watermarks at order-0 to
3179b8e83b94SMel Gorman 		 * prevent kswapd reclaiming excessively. Assume that a
3180b8e83b94SMel Gorman 		 * process requested a high-order can direct reclaim/compact.
31811da177e4SLinus Torvalds 		 */
3182b8e83b94SMel Gorman 		if (order && sc.nr_reclaimed >= 2UL << order)
318373ce02e9SKOSAKI Motohiro 			order = sc.order = 0;
318473ce02e9SKOSAKI Motohiro 
3185b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
3186b8e83b94SMel Gorman 		if (try_to_freeze() || kthread_should_stop())
3187b8e83b94SMel Gorman 			break;
3188b8e83b94SMel Gorman 
3189b8e83b94SMel Gorman 		/*
31902ab44f43SMel Gorman 		 * Compact if necessary and kswapd is reclaiming at least the
31912ab44f43SMel Gorman 		 * high watermark number of pages as requsted
31922ab44f43SMel Gorman 		 */
31932ab44f43SMel Gorman 		if (pgdat_needs_compaction && sc.nr_reclaimed > nr_attempted)
31942ab44f43SMel Gorman 			compact_pgdat(pgdat, order);
31952ab44f43SMel Gorman 
31962ab44f43SMel Gorman 		/*
3197b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3198b8e83b94SMel Gorman 		 * progress in reclaiming pages
3199b8e83b94SMel Gorman 		 */
3200b8e83b94SMel Gorman 		if (raise_priority || !sc.nr_reclaimed)
3201b8e83b94SMel Gorman 			sc.priority--;
32029aa41348SMel Gorman 	} while (sc.priority >= 1 &&
3203b8e83b94SMel Gorman 		 !pgdat_balanced(pgdat, order, *classzone_idx));
32041da177e4SLinus Torvalds 
3205b8e83b94SMel Gorman out:
32060abdee2bSMel Gorman 	/*
32075515061dSMel Gorman 	 * Return the order we were reclaiming at so prepare_kswapd_sleep()
32080abdee2bSMel Gorman 	 * makes a decision on the order we were last reclaiming at. However,
32090abdee2bSMel Gorman 	 * if another caller entered the allocator slow path while kswapd
32100abdee2bSMel Gorman 	 * was awake, order will remain at the higher level
32110abdee2bSMel Gorman 	 */
3212dc83edd9SMel Gorman 	*classzone_idx = end_zone;
32130abdee2bSMel Gorman 	return order;
32141da177e4SLinus Torvalds }
32151da177e4SLinus Torvalds 
3216dc83edd9SMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3217f0bc0a60SKOSAKI Motohiro {
3218f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3219f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3220f0bc0a60SKOSAKI Motohiro 
3221f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3222f0bc0a60SKOSAKI Motohiro 		return;
3223f0bc0a60SKOSAKI Motohiro 
3224f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3225f0bc0a60SKOSAKI Motohiro 
3226f0bc0a60SKOSAKI Motohiro 	/* Try to sleep for a short interval */
32275515061dSMel Gorman 	if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
3228f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
3229f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3230f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3231f0bc0a60SKOSAKI Motohiro 	}
3232f0bc0a60SKOSAKI Motohiro 
3233f0bc0a60SKOSAKI Motohiro 	/*
3234f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3235f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3236f0bc0a60SKOSAKI Motohiro 	 */
32375515061dSMel Gorman 	if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
3238f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3239f0bc0a60SKOSAKI Motohiro 
3240f0bc0a60SKOSAKI Motohiro 		/*
3241f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3242f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3243f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3244f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3245f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3246f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3247f0bc0a60SKOSAKI Motohiro 		 */
3248f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
32491c7e7f6cSAaditya Kumar 
325062997027SMel Gorman 		/*
325162997027SMel Gorman 		 * Compaction records what page blocks it recently failed to
325262997027SMel Gorman 		 * isolate pages from and skips them in the future scanning.
325362997027SMel Gorman 		 * When kswapd is going to sleep, it is reasonable to assume
325462997027SMel Gorman 		 * that pages and compaction may succeed so reset the cache.
325562997027SMel Gorman 		 */
325662997027SMel Gorman 		reset_isolation_suitable(pgdat);
325762997027SMel Gorman 
32581c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3259f0bc0a60SKOSAKI Motohiro 			schedule();
32601c7e7f6cSAaditya Kumar 
3261f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3262f0bc0a60SKOSAKI Motohiro 	} else {
3263f0bc0a60SKOSAKI Motohiro 		if (remaining)
3264f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3265f0bc0a60SKOSAKI Motohiro 		else
3266f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3267f0bc0a60SKOSAKI Motohiro 	}
3268f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3269f0bc0a60SKOSAKI Motohiro }
3270f0bc0a60SKOSAKI Motohiro 
32711da177e4SLinus Torvalds /*
32721da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
32731da177e4SLinus Torvalds  * from the init process.
32741da177e4SLinus Torvalds  *
32751da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
32761da177e4SLinus Torvalds  * free memory available even if there is no other activity
32771da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
32781da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
32791da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
32801da177e4SLinus Torvalds  *
32811da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
32821da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
32831da177e4SLinus Torvalds  */
32841da177e4SLinus Torvalds static int kswapd(void *p)
32851da177e4SLinus Torvalds {
3286215ddd66SMel Gorman 	unsigned long order, new_order;
3287d2ebd0f6SAlex,Shi 	unsigned balanced_order;
3288215ddd66SMel Gorman 	int classzone_idx, new_classzone_idx;
3289d2ebd0f6SAlex,Shi 	int balanced_classzone_idx;
32901da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
32911da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3292f0bc0a60SKOSAKI Motohiro 
32931da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
32941da177e4SLinus Torvalds 		.reclaimed_slab = 0,
32951da177e4SLinus Torvalds 	};
3296a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
32971da177e4SLinus Torvalds 
3298cf40bd16SNick Piggin 	lockdep_set_current_reclaim_state(GFP_KERNEL);
3299cf40bd16SNick Piggin 
3300174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3301c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
33021da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
33031da177e4SLinus Torvalds 
33041da177e4SLinus Torvalds 	/*
33051da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
33061da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
33071da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
33081da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
33091da177e4SLinus Torvalds 	 *
33101da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
33111da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
33121da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
33131da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
33141da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
33151da177e4SLinus Torvalds 	 */
3316930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
331783144186SRafael J. Wysocki 	set_freezable();
33181da177e4SLinus Torvalds 
3319215ddd66SMel Gorman 	order = new_order = 0;
3320d2ebd0f6SAlex,Shi 	balanced_order = 0;
3321215ddd66SMel Gorman 	classzone_idx = new_classzone_idx = pgdat->nr_zones - 1;
3322d2ebd0f6SAlex,Shi 	balanced_classzone_idx = classzone_idx;
33231da177e4SLinus Torvalds 	for ( ; ; ) {
33246f6313d4SJeff Liu 		bool ret;
33253e1d1d28SChristoph Lameter 
3326215ddd66SMel Gorman 		/*
3327215ddd66SMel Gorman 		 * If the last balance_pgdat was unsuccessful it's unlikely a
3328215ddd66SMel Gorman 		 * new request of a similar or harder type will succeed soon
3329215ddd66SMel Gorman 		 * so consider going to sleep on the basis we reclaimed at
3330215ddd66SMel Gorman 		 */
3331d2ebd0f6SAlex,Shi 		if (balanced_classzone_idx >= new_classzone_idx &&
3332d2ebd0f6SAlex,Shi 					balanced_order == new_order) {
33331da177e4SLinus Torvalds 			new_order = pgdat->kswapd_max_order;
333499504748SMel Gorman 			new_classzone_idx = pgdat->classzone_idx;
33351da177e4SLinus Torvalds 			pgdat->kswapd_max_order =  0;
3336215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
3337215ddd66SMel Gorman 		}
3338215ddd66SMel Gorman 
333999504748SMel Gorman 		if (order < new_order || classzone_idx > new_classzone_idx) {
33401da177e4SLinus Torvalds 			/*
33411da177e4SLinus Torvalds 			 * Don't sleep if someone wants a larger 'order'
334299504748SMel Gorman 			 * allocation or has tigher zone constraints
33431da177e4SLinus Torvalds 			 */
33441da177e4SLinus Torvalds 			order = new_order;
334599504748SMel Gorman 			classzone_idx = new_classzone_idx;
33461da177e4SLinus Torvalds 		} else {
3347d2ebd0f6SAlex,Shi 			kswapd_try_to_sleep(pgdat, balanced_order,
3348d2ebd0f6SAlex,Shi 						balanced_classzone_idx);
33491da177e4SLinus Torvalds 			order = pgdat->kswapd_max_order;
335099504748SMel Gorman 			classzone_idx = pgdat->classzone_idx;
3351f0dfcde0SAlex,Shi 			new_order = order;
3352f0dfcde0SAlex,Shi 			new_classzone_idx = classzone_idx;
33534d40502eSMel Gorman 			pgdat->kswapd_max_order = 0;
3354215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
33551da177e4SLinus Torvalds 		}
33561da177e4SLinus Torvalds 
33578fe23e05SDavid Rientjes 		ret = try_to_freeze();
33588fe23e05SDavid Rientjes 		if (kthread_should_stop())
33598fe23e05SDavid Rientjes 			break;
33608fe23e05SDavid Rientjes 
33618fe23e05SDavid Rientjes 		/*
33628fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
33638fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3364b1296cc4SRafael J. Wysocki 		 */
336533906bc5SMel Gorman 		if (!ret) {
336633906bc5SMel Gorman 			trace_mm_vmscan_kswapd_wake(pgdat->node_id, order);
3367d2ebd0f6SAlex,Shi 			balanced_classzone_idx = classzone_idx;
3368d2ebd0f6SAlex,Shi 			balanced_order = balance_pgdat(pgdat, order,
3369d2ebd0f6SAlex,Shi 						&balanced_classzone_idx);
33701da177e4SLinus Torvalds 		}
337133906bc5SMel Gorman 	}
3372b0a8cc58STakamori Yamaguchi 
337371abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
3374b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
337571abdc15SJohannes Weiner 	lockdep_clear_current_reclaim_state();
337671abdc15SJohannes Weiner 
33771da177e4SLinus Torvalds 	return 0;
33781da177e4SLinus Torvalds }
33791da177e4SLinus Torvalds 
33801da177e4SLinus Torvalds /*
33811da177e4SLinus Torvalds  * A zone is low on free memory, so wake its kswapd task to service it.
33821da177e4SLinus Torvalds  */
338399504748SMel Gorman void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
33841da177e4SLinus Torvalds {
33851da177e4SLinus Torvalds 	pg_data_t *pgdat;
33861da177e4SLinus Torvalds 
3387f3fe6512SCon Kolivas 	if (!populated_zone(zone))
33881da177e4SLinus Torvalds 		return;
33891da177e4SLinus Torvalds 
339002a0e53dSPaul Jackson 	if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
33911da177e4SLinus Torvalds 		return;
339288f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
339399504748SMel Gorman 	if (pgdat->kswapd_max_order < order) {
339488f5acf8SMel Gorman 		pgdat->kswapd_max_order = order;
339599504748SMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx);
339699504748SMel Gorman 	}
33978d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
33981da177e4SLinus Torvalds 		return;
3399892f795dSJohannes Weiner 	if (zone_balanced(zone, order, 0, 0))
340088f5acf8SMel Gorman 		return;
340188f5acf8SMel Gorman 
340288f5acf8SMel Gorman 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
34038d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
34041da177e4SLinus Torvalds }
34051da177e4SLinus Torvalds 
3406c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
34071da177e4SLinus Torvalds /*
34087b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3409d6277db4SRafael J. Wysocki  * freed pages.
3410d6277db4SRafael J. Wysocki  *
3411d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3412d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3413d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
34141da177e4SLinus Torvalds  */
34157b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
34161da177e4SLinus Torvalds {
3417d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3418d6277db4SRafael J. Wysocki 	struct scan_control sc = {
34197b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
3420ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
34219e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
3422ee814fe2SJohannes Weiner 		.may_writepage = 1,
3423ee814fe2SJohannes Weiner 		.may_unmap = 1,
3424ee814fe2SJohannes Weiner 		.may_swap = 1,
3425ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
34261da177e4SLinus Torvalds 	};
34277b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
34287b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
34297b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
34301da177e4SLinus Torvalds 
34317b51755cSKOSAKI Motohiro 	p->flags |= PF_MEMALLOC;
34327b51755cSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(sc.gfp_mask);
3433d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
34347b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3435d6277db4SRafael J. Wysocki 
34363115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3437d6277db4SRafael J. Wysocki 
34387b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
34397b51755cSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
34407b51755cSKOSAKI Motohiro 	p->flags &= ~PF_MEMALLOC;
3441d6277db4SRafael J. Wysocki 
34427b51755cSKOSAKI Motohiro 	return nr_reclaimed;
34431da177e4SLinus Torvalds }
3444c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
34451da177e4SLinus Torvalds 
34461da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
34471da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
34481da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
34491da177e4SLinus Torvalds    restore their cpu bindings. */
3450fcb35a9bSGreg Kroah-Hartman static int cpu_callback(struct notifier_block *nfb, unsigned long action,
3451fcb35a9bSGreg Kroah-Hartman 			void *hcpu)
34521da177e4SLinus Torvalds {
345358c0a4a7SYasunori Goto 	int nid;
34541da177e4SLinus Torvalds 
34558bb78442SRafael J. Wysocki 	if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
345648fb2e24SLai Jiangshan 		for_each_node_state(nid, N_MEMORY) {
3457c5f59f08SMike Travis 			pg_data_t *pgdat = NODE_DATA(nid);
3458a70f7302SRusty Russell 			const struct cpumask *mask;
3459a70f7302SRusty Russell 
3460a70f7302SRusty Russell 			mask = cpumask_of_node(pgdat->node_id);
3461c5f59f08SMike Travis 
34623e597945SRusty Russell 			if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
34631da177e4SLinus Torvalds 				/* One of our CPUs online: restore mask */
3464c5f59f08SMike Travis 				set_cpus_allowed_ptr(pgdat->kswapd, mask);
34651da177e4SLinus Torvalds 		}
34661da177e4SLinus Torvalds 	}
34671da177e4SLinus Torvalds 	return NOTIFY_OK;
34681da177e4SLinus Torvalds }
34691da177e4SLinus Torvalds 
34703218ae14SYasunori Goto /*
34713218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
34723218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
34733218ae14SYasunori Goto  */
34743218ae14SYasunori Goto int kswapd_run(int nid)
34753218ae14SYasunori Goto {
34763218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
34773218ae14SYasunori Goto 	int ret = 0;
34783218ae14SYasunori Goto 
34793218ae14SYasunori Goto 	if (pgdat->kswapd)
34803218ae14SYasunori Goto 		return 0;
34813218ae14SYasunori Goto 
34823218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
34833218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
34843218ae14SYasunori Goto 		/* failure at boot is fatal */
34853218ae14SYasunori Goto 		BUG_ON(system_state == SYSTEM_BOOTING);
3486d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3487d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3488d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
34893218ae14SYasunori Goto 	}
34903218ae14SYasunori Goto 	return ret;
34913218ae14SYasunori Goto }
34923218ae14SYasunori Goto 
34938fe23e05SDavid Rientjes /*
3494d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3495bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
34968fe23e05SDavid Rientjes  */
34978fe23e05SDavid Rientjes void kswapd_stop(int nid)
34988fe23e05SDavid Rientjes {
34998fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
35008fe23e05SDavid Rientjes 
3501d8adde17SJiang Liu 	if (kswapd) {
35028fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3503d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3504d8adde17SJiang Liu 	}
35058fe23e05SDavid Rientjes }
35068fe23e05SDavid Rientjes 
35071da177e4SLinus Torvalds static int __init kswapd_init(void)
35081da177e4SLinus Torvalds {
35093218ae14SYasunori Goto 	int nid;
351069e05944SAndrew Morton 
35111da177e4SLinus Torvalds 	swap_setup();
351248fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
35133218ae14SYasunori Goto  		kswapd_run(nid);
35141da177e4SLinus Torvalds 	hotcpu_notifier(cpu_callback, 0);
35151da177e4SLinus Torvalds 	return 0;
35161da177e4SLinus Torvalds }
35171da177e4SLinus Torvalds 
35181da177e4SLinus Torvalds module_init(kswapd_init)
35199eeff239SChristoph Lameter 
35209eeff239SChristoph Lameter #ifdef CONFIG_NUMA
35219eeff239SChristoph Lameter /*
35229eeff239SChristoph Lameter  * Zone reclaim mode
35239eeff239SChristoph Lameter  *
35249eeff239SChristoph Lameter  * If non-zero call zone_reclaim when the number of free pages falls below
35259eeff239SChristoph Lameter  * the watermarks.
35269eeff239SChristoph Lameter  */
35279eeff239SChristoph Lameter int zone_reclaim_mode __read_mostly;
35289eeff239SChristoph Lameter 
35291b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
35307d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
35311b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
35321b2ffb78SChristoph Lameter #define RECLAIM_SWAP (1<<2)	/* Swap pages out during reclaim */
35331b2ffb78SChristoph Lameter 
35349eeff239SChristoph Lameter /*
3535a92f7126SChristoph Lameter  * Priority for ZONE_RECLAIM. This determines the fraction of pages
3536a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3537a92f7126SChristoph Lameter  * a zone.
3538a92f7126SChristoph Lameter  */
3539a92f7126SChristoph Lameter #define ZONE_RECLAIM_PRIORITY 4
3540a92f7126SChristoph Lameter 
35419eeff239SChristoph Lameter /*
35429614634fSChristoph Lameter  * Percentage of pages in a zone that must be unmapped for zone_reclaim to
35439614634fSChristoph Lameter  * occur.
35449614634fSChristoph Lameter  */
35459614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
35469614634fSChristoph Lameter 
35479614634fSChristoph Lameter /*
35480ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
35490ff38490SChristoph Lameter  * slab reclaim needs to occur.
35500ff38490SChristoph Lameter  */
35510ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
35520ff38490SChristoph Lameter 
355390afa5deSMel Gorman static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
355490afa5deSMel Gorman {
355590afa5deSMel Gorman 	unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
355690afa5deSMel Gorman 	unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
355790afa5deSMel Gorman 		zone_page_state(zone, NR_ACTIVE_FILE);
355890afa5deSMel Gorman 
355990afa5deSMel Gorman 	/*
356090afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
356190afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
356290afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
356390afa5deSMel Gorman 	 */
356490afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
356590afa5deSMel Gorman }
356690afa5deSMel Gorman 
356790afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
356890afa5deSMel Gorman static long zone_pagecache_reclaimable(struct zone *zone)
356990afa5deSMel Gorman {
357090afa5deSMel Gorman 	long nr_pagecache_reclaimable;
357190afa5deSMel Gorman 	long delta = 0;
357290afa5deSMel Gorman 
357390afa5deSMel Gorman 	/*
357490afa5deSMel Gorman 	 * If RECLAIM_SWAP is set, then all file pages are considered
357590afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
357690afa5deSMel Gorman 	 * pages like swapcache and zone_unmapped_file_pages() provides
357790afa5deSMel Gorman 	 * a better estimate
357890afa5deSMel Gorman 	 */
357990afa5deSMel Gorman 	if (zone_reclaim_mode & RECLAIM_SWAP)
358090afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
358190afa5deSMel Gorman 	else
358290afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
358390afa5deSMel Gorman 
358490afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
358590afa5deSMel Gorman 	if (!(zone_reclaim_mode & RECLAIM_WRITE))
358690afa5deSMel Gorman 		delta += zone_page_state(zone, NR_FILE_DIRTY);
358790afa5deSMel Gorman 
358890afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
358990afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
359090afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
359190afa5deSMel Gorman 
359290afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
359390afa5deSMel Gorman }
359490afa5deSMel Gorman 
35950ff38490SChristoph Lameter /*
35969eeff239SChristoph Lameter  * Try to free up some pages from this zone through reclaim.
35979eeff239SChristoph Lameter  */
3598179e9639SAndrew Morton static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
35999eeff239SChristoph Lameter {
36007fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
360169e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
36029eeff239SChristoph Lameter 	struct task_struct *p = current;
36039eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
3604179e9639SAndrew Morton 	struct scan_control sc = {
360562b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
360621caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
3607bd2f6199SJohannes Weiner 		.order = order,
36089e3b2f8cSKonstantin Khlebnikov 		.priority = ZONE_RECLAIM_PRIORITY,
3609ee814fe2SJohannes Weiner 		.may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
3610ee814fe2SJohannes Weiner 		.may_unmap = !!(zone_reclaim_mode & RECLAIM_SWAP),
3611ee814fe2SJohannes Weiner 		.may_swap = 1,
3612179e9639SAndrew Morton 	};
3613a09ed5e0SYing Han 	struct shrink_control shrink = {
3614a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
3615a09ed5e0SYing Han 	};
361615748048SKOSAKI Motohiro 	unsigned long nr_slab_pages0, nr_slab_pages1;
36179eeff239SChristoph Lameter 
36189eeff239SChristoph Lameter 	cond_resched();
3619d4f7796eSChristoph Lameter 	/*
3620d4f7796eSChristoph Lameter 	 * We need to be able to allocate from the reserves for RECLAIM_SWAP
3621d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
3622d4f7796eSChristoph Lameter 	 * and RECLAIM_SWAP.
3623d4f7796eSChristoph Lameter 	 */
3624d4f7796eSChristoph Lameter 	p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
362576ca542dSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(gfp_mask);
36269eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
36279eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3628c84db23cSChristoph Lameter 
362990afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
3630a92f7126SChristoph Lameter 		/*
36310ff38490SChristoph Lameter 		 * Free memory by calling shrink zone with increasing
36320ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3633a92f7126SChristoph Lameter 		 */
3634a92f7126SChristoph Lameter 		do {
36359e3b2f8cSKonstantin Khlebnikov 			shrink_zone(zone, &sc);
36369e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
36370ff38490SChristoph Lameter 	}
3638a92f7126SChristoph Lameter 
363915748048SKOSAKI Motohiro 	nr_slab_pages0 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
364015748048SKOSAKI Motohiro 	if (nr_slab_pages0 > zone->min_slab_pages) {
36412a16e3f4SChristoph Lameter 		/*
36427fb2d46dSChristoph Lameter 		 * shrink_slab() does not currently allow us to determine how
36430ff38490SChristoph Lameter 		 * many pages were freed in this zone. So we take the current
36440ff38490SChristoph Lameter 		 * number of slab pages and shake the slab until it is reduced
36450ff38490SChristoph Lameter 		 * by the same nr_pages that we used for reclaiming unmapped
36460ff38490SChristoph Lameter 		 * pages.
36472a16e3f4SChristoph Lameter 		 */
36480ce3d744SDave Chinner 		nodes_clear(shrink.nodes_to_scan);
36490ce3d744SDave Chinner 		node_set(zone_to_nid(zone), shrink.nodes_to_scan);
36504dc4b3d9SKOSAKI Motohiro 		for (;;) {
36514dc4b3d9SKOSAKI Motohiro 			unsigned long lru_pages = zone_reclaimable_pages(zone);
36524dc4b3d9SKOSAKI Motohiro 
36534dc4b3d9SKOSAKI Motohiro 			/* No reclaimable slab or very low memory pressure */
36541495f230SYing Han 			if (!shrink_slab(&shrink, sc.nr_scanned, lru_pages))
36554dc4b3d9SKOSAKI Motohiro 				break;
36564dc4b3d9SKOSAKI Motohiro 
36574dc4b3d9SKOSAKI Motohiro 			/* Freed enough memory */
36584dc4b3d9SKOSAKI Motohiro 			nr_slab_pages1 = zone_page_state(zone,
36594dc4b3d9SKOSAKI Motohiro 							NR_SLAB_RECLAIMABLE);
36604dc4b3d9SKOSAKI Motohiro 			if (nr_slab_pages1 + nr_pages <= nr_slab_pages0)
36614dc4b3d9SKOSAKI Motohiro 				break;
36624dc4b3d9SKOSAKI Motohiro 		}
366383e33a47SChristoph Lameter 
366483e33a47SChristoph Lameter 		/*
366583e33a47SChristoph Lameter 		 * Update nr_reclaimed by the number of slab pages we
366683e33a47SChristoph Lameter 		 * reclaimed from this zone.
366783e33a47SChristoph Lameter 		 */
366815748048SKOSAKI Motohiro 		nr_slab_pages1 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
366915748048SKOSAKI Motohiro 		if (nr_slab_pages1 < nr_slab_pages0)
367015748048SKOSAKI Motohiro 			sc.nr_reclaimed += nr_slab_pages0 - nr_slab_pages1;
36712a16e3f4SChristoph Lameter 	}
36722a16e3f4SChristoph Lameter 
36739eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3674d4f7796eSChristoph Lameter 	current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
367576ca542dSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
3676a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
36779eeff239SChristoph Lameter }
3678179e9639SAndrew Morton 
3679179e9639SAndrew Morton int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
3680179e9639SAndrew Morton {
3681179e9639SAndrew Morton 	int node_id;
3682d773ed6bSDavid Rientjes 	int ret;
3683179e9639SAndrew Morton 
3684179e9639SAndrew Morton 	/*
36850ff38490SChristoph Lameter 	 * Zone reclaim reclaims unmapped file backed pages and
36860ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
368734aa1330SChristoph Lameter 	 *
36889614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
36899614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
36909614634fSChristoph Lameter 	 * thrown out if the zone is overallocated. So we do not reclaim
36919614634fSChristoph Lameter 	 * if less than a specified percentage of the zone is used by
36929614634fSChristoph Lameter 	 * unmapped file backed pages.
3693179e9639SAndrew Morton 	 */
369490afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
369590afa5deSMel Gorman 	    zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
3696fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3697179e9639SAndrew Morton 
36986e543d57SLisa Du 	if (!zone_reclaimable(zone))
3699fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3700d773ed6bSDavid Rientjes 
3701179e9639SAndrew Morton 	/*
3702d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3703179e9639SAndrew Morton 	 */
3704d773ed6bSDavid Rientjes 	if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
3705fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3706179e9639SAndrew Morton 
3707179e9639SAndrew Morton 	/*
3708179e9639SAndrew Morton 	 * Only run zone reclaim on the local zone or on zones that do not
3709179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3710179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3711179e9639SAndrew Morton 	 * as wide as possible.
3712179e9639SAndrew Morton 	 */
371389fa3024SChristoph Lameter 	node_id = zone_to_nid(zone);
371437c0708dSChristoph Lameter 	if (node_state(node_id, N_CPU) && node_id != numa_node_id())
3715fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3716d773ed6bSDavid Rientjes 
371757054651SJohannes Weiner 	if (test_and_set_bit(ZONE_RECLAIM_LOCKED, &zone->flags))
3718fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3719fa5e084eSMel Gorman 
3720d773ed6bSDavid Rientjes 	ret = __zone_reclaim(zone, gfp_mask, order);
372157054651SJohannes Weiner 	clear_bit(ZONE_RECLAIM_LOCKED, &zone->flags);
3722d773ed6bSDavid Rientjes 
372324cf7251SMel Gorman 	if (!ret)
372424cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
372524cf7251SMel Gorman 
3726d773ed6bSDavid Rientjes 	return ret;
3727179e9639SAndrew Morton }
37289eeff239SChristoph Lameter #endif
3729894bc310SLee Schermerhorn 
3730894bc310SLee Schermerhorn /*
3731894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3732894bc310SLee Schermerhorn  * @page: the page to test
3733894bc310SLee Schermerhorn  *
3734894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
373539b5f29aSHugh Dickins  * lists vs unevictable list.
3736894bc310SLee Schermerhorn  *
3737894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3738ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3739b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3740ba9ddf49SLee Schermerhorn  *
3741894bc310SLee Schermerhorn  */
374239b5f29aSHugh Dickins int page_evictable(struct page *page)
3743894bc310SLee Schermerhorn {
374439b5f29aSHugh Dickins 	return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3745894bc310SLee Schermerhorn }
374689e004eaSLee Schermerhorn 
374785046579SHugh Dickins #ifdef CONFIG_SHMEM
374889e004eaSLee Schermerhorn /**
374924513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
375024513264SHugh Dickins  * @pages:	array of pages to check
375124513264SHugh Dickins  * @nr_pages:	number of pages to check
375289e004eaSLee Schermerhorn  *
375324513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
375485046579SHugh Dickins  *
375585046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
375689e004eaSLee Schermerhorn  */
375724513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
375889e004eaSLee Schermerhorn {
3759925b7673SJohannes Weiner 	struct lruvec *lruvec;
376024513264SHugh Dickins 	struct zone *zone = NULL;
376124513264SHugh Dickins 	int pgscanned = 0;
376224513264SHugh Dickins 	int pgrescued = 0;
376389e004eaSLee Schermerhorn 	int i;
376489e004eaSLee Schermerhorn 
376524513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
376624513264SHugh Dickins 		struct page *page = pages[i];
376724513264SHugh Dickins 		struct zone *pagezone;
376889e004eaSLee Schermerhorn 
376924513264SHugh Dickins 		pgscanned++;
377024513264SHugh Dickins 		pagezone = page_zone(page);
377189e004eaSLee Schermerhorn 		if (pagezone != zone) {
377289e004eaSLee Schermerhorn 			if (zone)
377389e004eaSLee Schermerhorn 				spin_unlock_irq(&zone->lru_lock);
377489e004eaSLee Schermerhorn 			zone = pagezone;
377589e004eaSLee Schermerhorn 			spin_lock_irq(&zone->lru_lock);
377689e004eaSLee Schermerhorn 		}
3777fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
377889e004eaSLee Schermerhorn 
377924513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
378024513264SHugh Dickins 			continue;
378189e004eaSLee Schermerhorn 
378239b5f29aSHugh Dickins 		if (page_evictable(page)) {
378324513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
378424513264SHugh Dickins 
3785309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
378624513264SHugh Dickins 			ClearPageUnevictable(page);
3787fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3788fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
378924513264SHugh Dickins 			pgrescued++;
379089e004eaSLee Schermerhorn 		}
379189e004eaSLee Schermerhorn 	}
379224513264SHugh Dickins 
379324513264SHugh Dickins 	if (zone) {
379424513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
379524513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
379624513264SHugh Dickins 		spin_unlock_irq(&zone->lru_lock);
379724513264SHugh Dickins 	}
379885046579SHugh Dickins }
379985046579SHugh Dickins #endif /* CONFIG_SHMEM */
3800