xref: /openbmc/linux/mm/vmscan.c (revision a0b02131c5fcd8545b867db72224b3659e813f10)
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 
141da177e4SLinus Torvalds #include <linux/mm.h>
151da177e4SLinus Torvalds #include <linux/module.h>
165a0e3ad6STejun Heo #include <linux/gfp.h>
171da177e4SLinus Torvalds #include <linux/kernel_stat.h>
181da177e4SLinus Torvalds #include <linux/swap.h>
191da177e4SLinus Torvalds #include <linux/pagemap.h>
201da177e4SLinus Torvalds #include <linux/init.h>
211da177e4SLinus Torvalds #include <linux/highmem.h>
2270ddf637SAnton Vorontsov #include <linux/vmpressure.h>
23e129b5c2SAndrew Morton #include <linux/vmstat.h>
241da177e4SLinus Torvalds #include <linux/file.h>
251da177e4SLinus Torvalds #include <linux/writeback.h>
261da177e4SLinus Torvalds #include <linux/blkdev.h>
271da177e4SLinus Torvalds #include <linux/buffer_head.h>	/* for try_to_release_page(),
281da177e4SLinus Torvalds 					buffer_heads_over_limit */
291da177e4SLinus Torvalds #include <linux/mm_inline.h>
301da177e4SLinus Torvalds #include <linux/backing-dev.h>
311da177e4SLinus Torvalds #include <linux/rmap.h>
321da177e4SLinus Torvalds #include <linux/topology.h>
331da177e4SLinus Torvalds #include <linux/cpu.h>
341da177e4SLinus Torvalds #include <linux/cpuset.h>
353e7d3449SMel Gorman #include <linux/compaction.h>
361da177e4SLinus Torvalds #include <linux/notifier.h>
371da177e4SLinus Torvalds #include <linux/rwsem.h>
38248a0301SRafael J. Wysocki #include <linux/delay.h>
393218ae14SYasunori Goto #include <linux/kthread.h>
407dfb7103SNigel Cunningham #include <linux/freezer.h>
4166e1707bSBalbir Singh #include <linux/memcontrol.h>
42873b4771SKeika Kobayashi #include <linux/delayacct.h>
43af936a16SLee Schermerhorn #include <linux/sysctl.h>
44929bea7cSKOSAKI Motohiro #include <linux/oom.h>
45268bb0ceSLinus Torvalds #include <linux/prefetch.h>
461da177e4SLinus Torvalds 
471da177e4SLinus Torvalds #include <asm/tlbflush.h>
481da177e4SLinus Torvalds #include <asm/div64.h>
491da177e4SLinus Torvalds 
501da177e4SLinus Torvalds #include <linux/swapops.h>
511da177e4SLinus Torvalds 
520f8053a5SNick Piggin #include "internal.h"
530f8053a5SNick Piggin 
5433906bc5SMel Gorman #define CREATE_TRACE_POINTS
5533906bc5SMel Gorman #include <trace/events/vmscan.h>
5633906bc5SMel Gorman 
571da177e4SLinus Torvalds struct scan_control {
581da177e4SLinus Torvalds 	/* Incremented by the number of inactive pages that were scanned */
591da177e4SLinus Torvalds 	unsigned long nr_scanned;
601da177e4SLinus Torvalds 
61a79311c1SRik van Riel 	/* Number of pages freed so far during a call to shrink_zones() */
62a79311c1SRik van Riel 	unsigned long nr_reclaimed;
63a79311c1SRik van Riel 
6422fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6522fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
6622fba335SKOSAKI Motohiro 
677b51755cSKOSAKI Motohiro 	unsigned long hibernation_mode;
687b51755cSKOSAKI Motohiro 
691da177e4SLinus Torvalds 	/* This context's GFP mask */
706daa0e28SAl Viro 	gfp_t gfp_mask;
711da177e4SLinus Torvalds 
721da177e4SLinus Torvalds 	int may_writepage;
731da177e4SLinus Torvalds 
74a6dc60f8SJohannes Weiner 	/* Can mapped pages be reclaimed? */
75a6dc60f8SJohannes Weiner 	int may_unmap;
76f1fd1067SChristoph Lameter 
772e2e4259SKOSAKI Motohiro 	/* Can pages be swapped as part of reclaim? */
782e2e4259SKOSAKI Motohiro 	int may_swap;
792e2e4259SKOSAKI Motohiro 
805ad333ebSAndy Whitcroft 	int order;
8166e1707bSBalbir Singh 
829e3b2f8cSKonstantin Khlebnikov 	/* Scan (total_size >> priority) pages at once */
839e3b2f8cSKonstantin Khlebnikov 	int priority;
849e3b2f8cSKonstantin Khlebnikov 
855f53e762SKOSAKI Motohiro 	/*
86f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
87f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
88f16015fbSJohannes Weiner 	 */
89f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
9066e1707bSBalbir Singh 
91327c0e96SKAMEZAWA Hiroyuki 	/*
92327c0e96SKAMEZAWA Hiroyuki 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
93327c0e96SKAMEZAWA Hiroyuki 	 * are scanned.
94327c0e96SKAMEZAWA Hiroyuki 	 */
95327c0e96SKAMEZAWA Hiroyuki 	nodemask_t	*nodemask;
961da177e4SLinus Torvalds };
971da177e4SLinus Torvalds 
981da177e4SLinus Torvalds #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
991da177e4SLinus Torvalds 
1001da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCH
1011da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field)			\
1021da177e4SLinus Torvalds 	do {								\
1031da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1041da177e4SLinus Torvalds 			struct page *prev;				\
1051da177e4SLinus Torvalds 									\
1061da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1071da177e4SLinus Torvalds 			prefetch(&prev->_field);			\
1081da177e4SLinus Torvalds 		}							\
1091da177e4SLinus Torvalds 	} while (0)
1101da177e4SLinus Torvalds #else
1111da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
1121da177e4SLinus Torvalds #endif
1131da177e4SLinus Torvalds 
1141da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1151da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1161da177e4SLinus Torvalds 	do {								\
1171da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1181da177e4SLinus Torvalds 			struct page *prev;				\
1191da177e4SLinus Torvalds 									\
1201da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1211da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1221da177e4SLinus Torvalds 		}							\
1231da177e4SLinus Torvalds 	} while (0)
1241da177e4SLinus Torvalds #else
1251da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1261da177e4SLinus Torvalds #endif
1271da177e4SLinus Torvalds 
1281da177e4SLinus Torvalds /*
1291da177e4SLinus Torvalds  * From 0 .. 100.  Higher means more swappy.
1301da177e4SLinus Torvalds  */
1311da177e4SLinus Torvalds int vm_swappiness = 60;
132b21e0b90SZhang Yanfei unsigned long vm_total_pages;	/* The total number of pages which the VM controls */
1331da177e4SLinus Torvalds 
1341da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1351da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1361da177e4SLinus Torvalds 
137c255a458SAndrew Morton #ifdef CONFIG_MEMCG
13889b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
13989b5fae5SJohannes Weiner {
140f16015fbSJohannes Weiner 	return !sc->target_mem_cgroup;
14189b5fae5SJohannes Weiner }
14291a45470SKAMEZAWA Hiroyuki #else
14389b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
14489b5fae5SJohannes Weiner {
14589b5fae5SJohannes Weiner 	return true;
14689b5fae5SJohannes Weiner }
14791a45470SKAMEZAWA Hiroyuki #endif
14891a45470SKAMEZAWA Hiroyuki 
1494d7dcca2SHugh Dickins static unsigned long get_lru_size(struct lruvec *lruvec, enum lru_list lru)
150c9f299d9SKOSAKI Motohiro {
151c3c787e8SHugh Dickins 	if (!mem_cgroup_disabled())
1524d7dcca2SHugh Dickins 		return mem_cgroup_get_lru_size(lruvec, lru);
153a3d8e054SKOSAKI Motohiro 
154074291feSKonstantin Khlebnikov 	return zone_page_state(lruvec_zone(lruvec), NR_LRU_BASE + lru);
155c9f299d9SKOSAKI Motohiro }
156c9f299d9SKOSAKI Motohiro 
1571da177e4SLinus Torvalds /*
1581d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
1591da177e4SLinus Torvalds  */
1601d3d4437SGlauber Costa int register_shrinker(struct shrinker *shrinker)
1611da177e4SLinus Torvalds {
1621d3d4437SGlauber Costa 	size_t size = sizeof(*shrinker->nr_deferred);
1631d3d4437SGlauber Costa 
1641d3d4437SGlauber Costa 	/*
1651d3d4437SGlauber Costa 	 * If we only have one possible node in the system anyway, save
1661d3d4437SGlauber Costa 	 * ourselves the trouble and disable NUMA aware behavior. This way we
1671d3d4437SGlauber Costa 	 * will save memory and some small loop time later.
1681d3d4437SGlauber Costa 	 */
1691d3d4437SGlauber Costa 	if (nr_node_ids == 1)
1701d3d4437SGlauber Costa 		shrinker->flags &= ~SHRINKER_NUMA_AWARE;
1711d3d4437SGlauber Costa 
1721d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
1731d3d4437SGlauber Costa 		size *= nr_node_ids;
1741d3d4437SGlauber Costa 
1751d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
1761d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
1771d3d4437SGlauber Costa 		return -ENOMEM;
1781d3d4437SGlauber Costa 
1791da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
1801da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
1811da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
1821d3d4437SGlauber Costa 	return 0;
1831da177e4SLinus Torvalds }
1848e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
1851da177e4SLinus Torvalds 
1861da177e4SLinus Torvalds /*
1871da177e4SLinus Torvalds  * Remove one
1881da177e4SLinus Torvalds  */
1898e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
1901da177e4SLinus Torvalds {
1911da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
1921da177e4SLinus Torvalds 	list_del(&shrinker->list);
1931da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
1941da177e4SLinus Torvalds }
1958e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
1961da177e4SLinus Torvalds 
1971da177e4SLinus Torvalds #define SHRINK_BATCH 128
1981d3d4437SGlauber Costa 
1991d3d4437SGlauber Costa static unsigned long
2001d3d4437SGlauber Costa shrink_slab_node(struct shrink_control *shrinkctl, struct shrinker *shrinker,
2011d3d4437SGlauber Costa 		 unsigned long nr_pages_scanned, unsigned long lru_pages)
2021da177e4SLinus Torvalds {
20324f7c6b9SDave Chinner 	unsigned long freed = 0;
2041da177e4SLinus Torvalds 	unsigned long long delta;
205635697c6SKonstantin Khlebnikov 	long total_scan;
206635697c6SKonstantin Khlebnikov 	long max_pass;
207acf92b48SDave Chinner 	long nr;
208acf92b48SDave Chinner 	long new_nr;
2091d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
210e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
211e9299f50SDave Chinner 					  : SHRINK_BATCH;
2121da177e4SLinus Torvalds 
21324f7c6b9SDave Chinner 	max_pass = shrinker->count_objects(shrinker, shrinkctl);
21424f7c6b9SDave Chinner 	if (max_pass == 0)
2151d3d4437SGlauber Costa 		return 0;
216635697c6SKonstantin Khlebnikov 
217acf92b48SDave Chinner 	/*
218acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
219acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
220acf92b48SDave Chinner 	 * don't also do this scanning work.
221acf92b48SDave Chinner 	 */
2221d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
223acf92b48SDave Chinner 
224acf92b48SDave Chinner 	total_scan = nr;
2251495f230SYing Han 	delta = (4 * nr_pages_scanned) / shrinker->seeks;
226ea164d73SAndrea Arcangeli 	delta *= max_pass;
2271da177e4SLinus Torvalds 	do_div(delta, lru_pages + 1);
228acf92b48SDave Chinner 	total_scan += delta;
229acf92b48SDave Chinner 	if (total_scan < 0) {
23024f7c6b9SDave Chinner 		printk(KERN_ERR
23124f7c6b9SDave Chinner 		"shrink_slab: %pF negative objects to delete nr=%ld\n",
232*a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
233acf92b48SDave Chinner 		total_scan = max_pass;
234ea164d73SAndrea Arcangeli 	}
235ea164d73SAndrea Arcangeli 
236ea164d73SAndrea Arcangeli 	/*
2373567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
2383567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
2393567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
2403567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
2413567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
2423567b59aSDave Chinner 	 * max_pass.  This is bad for sustaining a working set in
2433567b59aSDave Chinner 	 * memory.
2443567b59aSDave Chinner 	 *
2453567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
2463567b59aSDave Chinner 	 * a large delta change is calculated directly.
2473567b59aSDave Chinner 	 */
2483567b59aSDave Chinner 	if (delta < max_pass / 4)
2493567b59aSDave Chinner 		total_scan = min(total_scan, max_pass / 2);
2503567b59aSDave Chinner 
2513567b59aSDave Chinner 	/*
252ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
253ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
254ea164d73SAndrea Arcangeli 	 * freeable entries.
255ea164d73SAndrea Arcangeli 	 */
256acf92b48SDave Chinner 	if (total_scan > max_pass * 2)
257acf92b48SDave Chinner 		total_scan = max_pass * 2;
2581da177e4SLinus Torvalds 
25924f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
26009576073SDave Chinner 				nr_pages_scanned, lru_pages,
26109576073SDave Chinner 				max_pass, delta, total_scan);
26209576073SDave Chinner 
263e9299f50SDave Chinner 	while (total_scan >= batch_size) {
26424f7c6b9SDave Chinner 		unsigned long ret;
265*a0b02131SDave Chinner 
26624f7c6b9SDave Chinner 		shrinkctl->nr_to_scan = batch_size;
26724f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
26824f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
2691da177e4SLinus Torvalds 			break;
27024f7c6b9SDave Chinner 		freed += ret;
27124f7c6b9SDave Chinner 
272e9299f50SDave Chinner 		count_vm_events(SLABS_SCANNED, batch_size);
273e9299f50SDave Chinner 		total_scan -= batch_size;
2741da177e4SLinus Torvalds 
2751da177e4SLinus Torvalds 		cond_resched();
2761da177e4SLinus Torvalds 	}
2771da177e4SLinus Torvalds 
278acf92b48SDave Chinner 	/*
279acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
280acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
281acf92b48SDave Chinner 	 * scan, there is no need to do an update.
282acf92b48SDave Chinner 	 */
28383aeeadaSKonstantin Khlebnikov 	if (total_scan > 0)
28483aeeadaSKonstantin Khlebnikov 		new_nr = atomic_long_add_return(total_scan,
2851d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
28683aeeadaSKonstantin Khlebnikov 	else
2871d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
288acf92b48SDave Chinner 
28924f7c6b9SDave Chinner 	trace_mm_shrink_slab_end(shrinker, freed, nr, new_nr);
2901d3d4437SGlauber Costa 	return freed;
2911d3d4437SGlauber Costa }
2921d3d4437SGlauber Costa 
2931d3d4437SGlauber Costa /*
2941d3d4437SGlauber Costa  * Call the shrink functions to age shrinkable caches
2951d3d4437SGlauber Costa  *
2961d3d4437SGlauber Costa  * Here we assume it costs one seek to replace a lru page and that it also
2971d3d4437SGlauber Costa  * takes a seek to recreate a cache object.  With this in mind we age equal
2981d3d4437SGlauber Costa  * percentages of the lru and ageable caches.  This should balance the seeks
2991d3d4437SGlauber Costa  * generated by these structures.
3001d3d4437SGlauber Costa  *
3011d3d4437SGlauber Costa  * If the vm encountered mapped pages on the LRU it increase the pressure on
3021d3d4437SGlauber Costa  * slab to avoid swapping.
3031d3d4437SGlauber Costa  *
3041d3d4437SGlauber Costa  * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
3051d3d4437SGlauber Costa  *
3061d3d4437SGlauber Costa  * `lru_pages' represents the number of on-LRU pages in all the zones which
3071d3d4437SGlauber Costa  * are eligible for the caller's allocation attempt.  It is used for balancing
3081d3d4437SGlauber Costa  * slab reclaim versus page reclaim.
3091d3d4437SGlauber Costa  *
3101d3d4437SGlauber Costa  * Returns the number of slab objects which we shrunk.
3111d3d4437SGlauber Costa  */
3121d3d4437SGlauber Costa unsigned long shrink_slab(struct shrink_control *shrinkctl,
3131d3d4437SGlauber Costa 			  unsigned long nr_pages_scanned,
3141d3d4437SGlauber Costa 			  unsigned long lru_pages)
3151d3d4437SGlauber Costa {
3161d3d4437SGlauber Costa 	struct shrinker *shrinker;
3171d3d4437SGlauber Costa 	unsigned long freed = 0;
3181d3d4437SGlauber Costa 
3191d3d4437SGlauber Costa 	if (nr_pages_scanned == 0)
3201d3d4437SGlauber Costa 		nr_pages_scanned = SWAP_CLUSTER_MAX;
3211d3d4437SGlauber Costa 
3221d3d4437SGlauber Costa 	if (!down_read_trylock(&shrinker_rwsem)) {
3231d3d4437SGlauber Costa 		/*
3241d3d4437SGlauber Costa 		 * If we would return 0, our callers would understand that we
3251d3d4437SGlauber Costa 		 * have nothing else to shrink and give up trying. By returning
3261d3d4437SGlauber Costa 		 * 1 we keep it going and assume we'll be able to shrink next
3271d3d4437SGlauber Costa 		 * time.
3281d3d4437SGlauber Costa 		 */
3291d3d4437SGlauber Costa 		freed = 1;
3301d3d4437SGlauber Costa 		goto out;
3311d3d4437SGlauber Costa 	}
3321d3d4437SGlauber Costa 
3331d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
3341d3d4437SGlauber Costa 		for_each_node_mask(shrinkctl->nid, shrinkctl->nodes_to_scan) {
3351d3d4437SGlauber Costa 			if (!node_online(shrinkctl->nid))
3361d3d4437SGlauber Costa 				continue;
3371d3d4437SGlauber Costa 
3381d3d4437SGlauber Costa 			if (!(shrinker->flags & SHRINKER_NUMA_AWARE) &&
3391d3d4437SGlauber Costa 			    (shrinkctl->nid != 0))
3401d3d4437SGlauber Costa 				break;
3411d3d4437SGlauber Costa 
3421d3d4437SGlauber Costa 			freed += shrink_slab_node(shrinkctl, shrinker,
3431d3d4437SGlauber Costa 				 nr_pages_scanned, lru_pages);
3441d3d4437SGlauber Costa 
3451d3d4437SGlauber Costa 		}
3461da177e4SLinus Torvalds 	}
3471da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
348f06590bdSMinchan Kim out:
349f06590bdSMinchan Kim 	cond_resched();
35024f7c6b9SDave Chinner 	return freed;
3511da177e4SLinus Torvalds }
3521da177e4SLinus Torvalds 
3531da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
3541da177e4SLinus Torvalds {
355ceddc3a5SJohannes Weiner 	/*
356ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
357ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
358ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
359ceddc3a5SJohannes Weiner 	 */
360edcf4748SJohannes Weiner 	return page_count(page) - page_has_private(page) == 2;
3611da177e4SLinus Torvalds }
3621da177e4SLinus Torvalds 
3637d3579e8SKOSAKI Motohiro static int may_write_to_queue(struct backing_dev_info *bdi,
3647d3579e8SKOSAKI Motohiro 			      struct scan_control *sc)
3651da177e4SLinus Torvalds {
366930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
3671da177e4SLinus Torvalds 		return 1;
3681da177e4SLinus Torvalds 	if (!bdi_write_congested(bdi))
3691da177e4SLinus Torvalds 		return 1;
3701da177e4SLinus Torvalds 	if (bdi == current->backing_dev_info)
3711da177e4SLinus Torvalds 		return 1;
3721da177e4SLinus Torvalds 	return 0;
3731da177e4SLinus Torvalds }
3741da177e4SLinus Torvalds 
3751da177e4SLinus Torvalds /*
3761da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
3771da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
3781da177e4SLinus Torvalds  * fsync(), msync() or close().
3791da177e4SLinus Torvalds  *
3801da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
3811da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
3821da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
3831da177e4SLinus Torvalds  *
3841da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
3851da177e4SLinus Torvalds  * __GFP_FS.
3861da177e4SLinus Torvalds  */
3871da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
3881da177e4SLinus Torvalds 				struct page *page, int error)
3891da177e4SLinus Torvalds {
3907eaceaccSJens Axboe 	lock_page(page);
3913e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
3923e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
3931da177e4SLinus Torvalds 	unlock_page(page);
3941da177e4SLinus Torvalds }
3951da177e4SLinus Torvalds 
39604e62a29SChristoph Lameter /* possible outcome of pageout() */
39704e62a29SChristoph Lameter typedef enum {
39804e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
39904e62a29SChristoph Lameter 	PAGE_KEEP,
40004e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
40104e62a29SChristoph Lameter 	PAGE_ACTIVATE,
40204e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
40304e62a29SChristoph Lameter 	PAGE_SUCCESS,
40404e62a29SChristoph Lameter 	/* page is clean and locked */
40504e62a29SChristoph Lameter 	PAGE_CLEAN,
40604e62a29SChristoph Lameter } pageout_t;
40704e62a29SChristoph Lameter 
4081da177e4SLinus Torvalds /*
4091742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
4101742f19fSAndrew Morton  * Calls ->writepage().
4111da177e4SLinus Torvalds  */
412c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
4137d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
4141da177e4SLinus Torvalds {
4151da177e4SLinus Torvalds 	/*
4161da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
4171da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
4181da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
4191da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
4201da177e4SLinus Torvalds 	 * PagePrivate for that.
4211da177e4SLinus Torvalds 	 *
4226aceb53bSVincent Li 	 * If this process is currently in __generic_file_aio_write() against
4231da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
4241da177e4SLinus Torvalds 	 * will block.
4251da177e4SLinus Torvalds 	 *
4261da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
4271da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
4281da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
4291da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
4301da177e4SLinus Torvalds 	 */
4311da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
4321da177e4SLinus Torvalds 		return PAGE_KEEP;
4331da177e4SLinus Torvalds 	if (!mapping) {
4341da177e4SLinus Torvalds 		/*
4351da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
4361da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
4371da177e4SLinus Torvalds 		 */
438266cf658SDavid Howells 		if (page_has_private(page)) {
4391da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
4401da177e4SLinus Torvalds 				ClearPageDirty(page);
441d40cee24SHarvey Harrison 				printk("%s: orphaned page\n", __func__);
4421da177e4SLinus Torvalds 				return PAGE_CLEAN;
4431da177e4SLinus Torvalds 			}
4441da177e4SLinus Torvalds 		}
4451da177e4SLinus Torvalds 		return PAGE_KEEP;
4461da177e4SLinus Torvalds 	}
4471da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
4481da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
4490e093d99SMel Gorman 	if (!may_write_to_queue(mapping->backing_dev_info, sc))
4501da177e4SLinus Torvalds 		return PAGE_KEEP;
4511da177e4SLinus Torvalds 
4521da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
4531da177e4SLinus Torvalds 		int res;
4541da177e4SLinus Torvalds 		struct writeback_control wbc = {
4551da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
4561da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
457111ebb6eSOGAWA Hirofumi 			.range_start = 0,
458111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
4591da177e4SLinus Torvalds 			.for_reclaim = 1,
4601da177e4SLinus Torvalds 		};
4611da177e4SLinus Torvalds 
4621da177e4SLinus Torvalds 		SetPageReclaim(page);
4631da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
4641da177e4SLinus Torvalds 		if (res < 0)
4651da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
466994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
4671da177e4SLinus Torvalds 			ClearPageReclaim(page);
4681da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
4691da177e4SLinus Torvalds 		}
470c661b078SAndy Whitcroft 
4711da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
4721da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
4731da177e4SLinus Torvalds 			ClearPageReclaim(page);
4741da177e4SLinus Torvalds 		}
47523b9da55SMel Gorman 		trace_mm_vmscan_writepage(page, trace_reclaim_flags(page));
476e129b5c2SAndrew Morton 		inc_zone_page_state(page, NR_VMSCAN_WRITE);
4771da177e4SLinus Torvalds 		return PAGE_SUCCESS;
4781da177e4SLinus Torvalds 	}
4791da177e4SLinus Torvalds 
4801da177e4SLinus Torvalds 	return PAGE_CLEAN;
4811da177e4SLinus Torvalds }
4821da177e4SLinus Torvalds 
483a649fd92SAndrew Morton /*
484e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
485e286781dSNick Piggin  * gets returned with a refcount of 0.
486a649fd92SAndrew Morton  */
487e286781dSNick Piggin static int __remove_mapping(struct address_space *mapping, struct page *page)
48849d2e9ccSChristoph Lameter {
48928e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
49028e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
49149d2e9ccSChristoph Lameter 
49219fd6231SNick Piggin 	spin_lock_irq(&mapping->tree_lock);
49349d2e9ccSChristoph Lameter 	/*
4940fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
4950fd0e6b0SNick Piggin 	 *
4960fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
4970fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
4980fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
4990fd0e6b0SNick Piggin 	 * here, then the following race may occur:
5000fd0e6b0SNick Piggin 	 *
5010fd0e6b0SNick Piggin 	 * get_user_pages(&page);
5020fd0e6b0SNick Piggin 	 * [user mapping goes away]
5030fd0e6b0SNick Piggin 	 * write_to(page);
5040fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
5050fd0e6b0SNick Piggin 	 * SetPageDirty(page);
5060fd0e6b0SNick Piggin 	 * put_page(page);
5070fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
5080fd0e6b0SNick Piggin 	 *
5090fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
5100fd0e6b0SNick Piggin 	 *
5110fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
5120fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
5130fd0e6b0SNick Piggin 	 * load is not satisfied before that of page->_count.
5140fd0e6b0SNick Piggin 	 *
5150fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
5160fd0e6b0SNick Piggin 	 * and thus under tree_lock, then this ordering is not required.
51749d2e9ccSChristoph Lameter 	 */
518e286781dSNick Piggin 	if (!page_freeze_refs(page, 2))
51949d2e9ccSChristoph Lameter 		goto cannot_free;
520e286781dSNick Piggin 	/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
521e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
522e286781dSNick Piggin 		page_unfreeze_refs(page, 2);
52349d2e9ccSChristoph Lameter 		goto cannot_free;
524e286781dSNick Piggin 	}
52549d2e9ccSChristoph Lameter 
52649d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
52749d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
52849d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
52919fd6231SNick Piggin 		spin_unlock_irq(&mapping->tree_lock);
530cb4b86baSKAMEZAWA Hiroyuki 		swapcache_free(swap, page);
531e286781dSNick Piggin 	} else {
5326072d13cSLinus Torvalds 		void (*freepage)(struct page *);
5336072d13cSLinus Torvalds 
5346072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
5356072d13cSLinus Torvalds 
536e64a782fSMinchan Kim 		__delete_from_page_cache(page);
53719fd6231SNick Piggin 		spin_unlock_irq(&mapping->tree_lock);
538e767e056SDaisuke Nishimura 		mem_cgroup_uncharge_cache_page(page);
5396072d13cSLinus Torvalds 
5406072d13cSLinus Torvalds 		if (freepage != NULL)
5416072d13cSLinus Torvalds 			freepage(page);
542e286781dSNick Piggin 	}
543e286781dSNick Piggin 
54449d2e9ccSChristoph Lameter 	return 1;
54549d2e9ccSChristoph Lameter 
54649d2e9ccSChristoph Lameter cannot_free:
54719fd6231SNick Piggin 	spin_unlock_irq(&mapping->tree_lock);
54849d2e9ccSChristoph Lameter 	return 0;
54949d2e9ccSChristoph Lameter }
55049d2e9ccSChristoph Lameter 
5511da177e4SLinus Torvalds /*
552e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
553e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
554e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
555e286781dSNick Piggin  * this page.
556e286781dSNick Piggin  */
557e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
558e286781dSNick Piggin {
559e286781dSNick Piggin 	if (__remove_mapping(mapping, page)) {
560e286781dSNick Piggin 		/*
561e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
562e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
563e286781dSNick Piggin 		 * atomic operation.
564e286781dSNick Piggin 		 */
565e286781dSNick Piggin 		page_unfreeze_refs(page, 1);
566e286781dSNick Piggin 		return 1;
567e286781dSNick Piggin 	}
568e286781dSNick Piggin 	return 0;
569e286781dSNick Piggin }
570e286781dSNick Piggin 
571894bc310SLee Schermerhorn /**
572894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
573894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
574894bc310SLee Schermerhorn  *
575894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
576894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
577894bc310SLee Schermerhorn  *
578894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
579894bc310SLee Schermerhorn  */
580894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
581894bc310SLee Schermerhorn {
582894bc310SLee Schermerhorn 	int lru;
583bbfd28eeSLee Schermerhorn 	int was_unevictable = PageUnevictable(page);
584894bc310SLee Schermerhorn 
585894bc310SLee Schermerhorn 	VM_BUG_ON(PageLRU(page));
586894bc310SLee Schermerhorn 
587894bc310SLee Schermerhorn redo:
588894bc310SLee Schermerhorn 	ClearPageUnevictable(page);
589894bc310SLee Schermerhorn 
59039b5f29aSHugh Dickins 	if (page_evictable(page)) {
591894bc310SLee Schermerhorn 		/*
592894bc310SLee Schermerhorn 		 * For evictable pages, we can use the cache.
593894bc310SLee Schermerhorn 		 * In event of a race, worst case is we end up with an
594894bc310SLee Schermerhorn 		 * unevictable page on [in]active list.
595894bc310SLee Schermerhorn 		 * We know how to handle that.
596894bc310SLee Schermerhorn 		 */
597c53954a0SMel Gorman 		lru = page_lru_base_type(page);
598c53954a0SMel Gorman 		lru_cache_add(page);
599894bc310SLee Schermerhorn 	} else {
600894bc310SLee Schermerhorn 		/*
601894bc310SLee Schermerhorn 		 * Put unevictable pages directly on zone's unevictable
602894bc310SLee Schermerhorn 		 * list.
603894bc310SLee Schermerhorn 		 */
604894bc310SLee Schermerhorn 		lru = LRU_UNEVICTABLE;
605894bc310SLee Schermerhorn 		add_page_to_unevictable_list(page);
6066a7b9548SJohannes Weiner 		/*
60721ee9f39SMinchan Kim 		 * When racing with an mlock or AS_UNEVICTABLE clearing
60821ee9f39SMinchan Kim 		 * (page is unlocked) make sure that if the other thread
60921ee9f39SMinchan Kim 		 * does not observe our setting of PG_lru and fails
61024513264SHugh Dickins 		 * isolation/check_move_unevictable_pages,
61121ee9f39SMinchan Kim 		 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
6126a7b9548SJohannes Weiner 		 * the page back to the evictable list.
6136a7b9548SJohannes Weiner 		 *
61421ee9f39SMinchan Kim 		 * The other side is TestClearPageMlocked() or shmem_lock().
6156a7b9548SJohannes Weiner 		 */
6166a7b9548SJohannes Weiner 		smp_mb();
617894bc310SLee Schermerhorn 	}
618894bc310SLee Schermerhorn 
619894bc310SLee Schermerhorn 	/*
620894bc310SLee Schermerhorn 	 * page's status can change while we move it among lru. If an evictable
621894bc310SLee Schermerhorn 	 * page is on unevictable list, it never be freed. To avoid that,
622894bc310SLee Schermerhorn 	 * check after we added it to the list, again.
623894bc310SLee Schermerhorn 	 */
62439b5f29aSHugh Dickins 	if (lru == LRU_UNEVICTABLE && page_evictable(page)) {
625894bc310SLee Schermerhorn 		if (!isolate_lru_page(page)) {
626894bc310SLee Schermerhorn 			put_page(page);
627894bc310SLee Schermerhorn 			goto redo;
628894bc310SLee Schermerhorn 		}
629894bc310SLee Schermerhorn 		/* This means someone else dropped this page from LRU
630894bc310SLee Schermerhorn 		 * So, it will be freed or putback to LRU again. There is
631894bc310SLee Schermerhorn 		 * nothing to do here.
632894bc310SLee Schermerhorn 		 */
633894bc310SLee Schermerhorn 	}
634894bc310SLee Schermerhorn 
635bbfd28eeSLee Schermerhorn 	if (was_unevictable && lru != LRU_UNEVICTABLE)
636bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGRESCUED);
637bbfd28eeSLee Schermerhorn 	else if (!was_unevictable && lru == LRU_UNEVICTABLE)
638bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGCULLED);
639bbfd28eeSLee Schermerhorn 
640894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
641894bc310SLee Schermerhorn }
642894bc310SLee Schermerhorn 
643dfc8d636SJohannes Weiner enum page_references {
644dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
645dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
64664574746SJohannes Weiner 	PAGEREF_KEEP,
647dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
648dfc8d636SJohannes Weiner };
649dfc8d636SJohannes Weiner 
650dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
651dfc8d636SJohannes Weiner 						  struct scan_control *sc)
652dfc8d636SJohannes Weiner {
65364574746SJohannes Weiner 	int referenced_ptes, referenced_page;
654dfc8d636SJohannes Weiner 	unsigned long vm_flags;
655dfc8d636SJohannes Weiner 
656c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
657c3ac9a8aSJohannes Weiner 					  &vm_flags);
65864574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
659dfc8d636SJohannes Weiner 
660dfc8d636SJohannes Weiner 	/*
661dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
662dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
663dfc8d636SJohannes Weiner 	 */
664dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
665dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
666dfc8d636SJohannes Weiner 
66764574746SJohannes Weiner 	if (referenced_ptes) {
668e4898273SMichal Hocko 		if (PageSwapBacked(page))
66964574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
67064574746SJohannes Weiner 		/*
67164574746SJohannes Weiner 		 * All mapped pages start out with page table
67264574746SJohannes Weiner 		 * references from the instantiating fault, so we need
67364574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
67464574746SJohannes Weiner 		 * than once.
67564574746SJohannes Weiner 		 *
67664574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
67764574746SJohannes Weiner 		 * inactive list.  Another page table reference will
67864574746SJohannes Weiner 		 * lead to its activation.
67964574746SJohannes Weiner 		 *
68064574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
68164574746SJohannes Weiner 		 * so that recently deactivated but used pages are
68264574746SJohannes Weiner 		 * quickly recovered.
68364574746SJohannes Weiner 		 */
68464574746SJohannes Weiner 		SetPageReferenced(page);
68564574746SJohannes Weiner 
68634dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
687dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
688dfc8d636SJohannes Weiner 
689c909e993SKonstantin Khlebnikov 		/*
690c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
691c909e993SKonstantin Khlebnikov 		 */
692c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
693c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
694c909e993SKonstantin Khlebnikov 
69564574746SJohannes Weiner 		return PAGEREF_KEEP;
69664574746SJohannes Weiner 	}
69764574746SJohannes Weiner 
698dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
6992e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
700dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
70164574746SJohannes Weiner 
70264574746SJohannes Weiner 	return PAGEREF_RECLAIM;
703dfc8d636SJohannes Weiner }
704dfc8d636SJohannes Weiner 
705e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
706e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
707e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
708e2be15f6SMel Gorman {
709b4597226SMel Gorman 	struct address_space *mapping;
710b4597226SMel Gorman 
711e2be15f6SMel Gorman 	/*
712e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
713e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
714e2be15f6SMel Gorman 	 */
715e2be15f6SMel Gorman 	if (!page_is_file_cache(page)) {
716e2be15f6SMel Gorman 		*dirty = false;
717e2be15f6SMel Gorman 		*writeback = false;
718e2be15f6SMel Gorman 		return;
719e2be15f6SMel Gorman 	}
720e2be15f6SMel Gorman 
721e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
722e2be15f6SMel Gorman 	*dirty = PageDirty(page);
723e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
724b4597226SMel Gorman 
725b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
726b4597226SMel Gorman 	if (!page_has_private(page))
727b4597226SMel Gorman 		return;
728b4597226SMel Gorman 
729b4597226SMel Gorman 	mapping = page_mapping(page);
730b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
731b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
732e2be15f6SMel Gorman }
733e2be15f6SMel Gorman 
734e286781dSNick Piggin /*
7351742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
7361da177e4SLinus Torvalds  */
7371742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
7386a18adb3SKonstantin Khlebnikov 				      struct zone *zone,
739f84f6e2bSMel Gorman 				      struct scan_control *sc,
74002c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
7418e950282SMel Gorman 				      unsigned long *ret_nr_dirty,
742d43006d5SMel Gorman 				      unsigned long *ret_nr_unqueued_dirty,
7438e950282SMel Gorman 				      unsigned long *ret_nr_congested,
74402c6de8dSMinchan Kim 				      unsigned long *ret_nr_writeback,
745b1a6f21eSMel Gorman 				      unsigned long *ret_nr_immediate,
74602c6de8dSMinchan Kim 				      bool force_reclaim)
7471da177e4SLinus Torvalds {
7481da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
749abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
7501da177e4SLinus Torvalds 	int pgactivate = 0;
751d43006d5SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
7520e093d99SMel Gorman 	unsigned long nr_dirty = 0;
7530e093d99SMel Gorman 	unsigned long nr_congested = 0;
75405ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
75592df3a72SMel Gorman 	unsigned long nr_writeback = 0;
756b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
7571da177e4SLinus Torvalds 
7581da177e4SLinus Torvalds 	cond_resched();
7591da177e4SLinus Torvalds 
76069980e31STim Chen 	mem_cgroup_uncharge_start();
7611da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
7621da177e4SLinus Torvalds 		struct address_space *mapping;
7631da177e4SLinus Torvalds 		struct page *page;
7641da177e4SLinus Torvalds 		int may_enter_fs;
76502c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
766e2be15f6SMel Gorman 		bool dirty, writeback;
7671da177e4SLinus Torvalds 
7681da177e4SLinus Torvalds 		cond_resched();
7691da177e4SLinus Torvalds 
7701da177e4SLinus Torvalds 		page = lru_to_page(page_list);
7711da177e4SLinus Torvalds 		list_del(&page->lru);
7721da177e4SLinus Torvalds 
773529ae9aaSNick Piggin 		if (!trylock_page(page))
7741da177e4SLinus Torvalds 			goto keep;
7751da177e4SLinus Torvalds 
776725d704eSNick Piggin 		VM_BUG_ON(PageActive(page));
7776a18adb3SKonstantin Khlebnikov 		VM_BUG_ON(page_zone(page) != zone);
7781da177e4SLinus Torvalds 
7791da177e4SLinus Torvalds 		sc->nr_scanned++;
78080e43426SChristoph Lameter 
78139b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
782b291f000SNick Piggin 			goto cull_mlocked;
783894bc310SLee Schermerhorn 
784a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
78580e43426SChristoph Lameter 			goto keep_locked;
78680e43426SChristoph Lameter 
7871da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
7881da177e4SLinus Torvalds 		if (page_mapped(page) || PageSwapCache(page))
7891da177e4SLinus Torvalds 			sc->nr_scanned++;
7901da177e4SLinus Torvalds 
791c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
792c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
793c661b078SAndy Whitcroft 
794e62e384eSMichal Hocko 		/*
795e2be15f6SMel Gorman 		 * The number of dirty pages determines if a zone is marked
796e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
797e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
798e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
799e2be15f6SMel Gorman 		 */
800e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
801e2be15f6SMel Gorman 		if (dirty || writeback)
802e2be15f6SMel Gorman 			nr_dirty++;
803e2be15f6SMel Gorman 
804e2be15f6SMel Gorman 		if (dirty && !writeback)
805e2be15f6SMel Gorman 			nr_unqueued_dirty++;
806e2be15f6SMel Gorman 
807d04e8acdSMel Gorman 		/*
808d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
809d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
810d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
811d04e8acdSMel Gorman 		 * end of the LRU a second time.
812d04e8acdSMel Gorman 		 */
813e2be15f6SMel Gorman 		mapping = page_mapping(page);
814d04e8acdSMel Gorman 		if ((mapping && bdi_write_congested(mapping->backing_dev_info)) ||
815d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
816e2be15f6SMel Gorman 			nr_congested++;
817e2be15f6SMel Gorman 
818e2be15f6SMel Gorman 		/*
819283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
820283aba9fSMel Gorman 		 * are three cases to consider.
821e62e384eSMichal Hocko 		 *
822283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
823283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
824283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
825283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
826283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
827283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
828283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
829b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
830b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
831c3b94f44SHugh Dickins 		 *
832283aba9fSMel Gorman 		 * 2) Global reclaim encounters a page, memcg encounters a
833283aba9fSMel Gorman 		 *    page that is not marked for immediate reclaim or
834283aba9fSMel Gorman 		 *    the caller does not have __GFP_IO. In this case mark
835283aba9fSMel Gorman 		 *    the page for immediate reclaim and continue scanning.
836283aba9fSMel Gorman 		 *
837283aba9fSMel Gorman 		 *    __GFP_IO is checked  because a loop driver thread might
838283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
839283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
840283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
841283aba9fSMel Gorman 		 *    would probably show more reasons.
842283aba9fSMel Gorman 		 *
843283aba9fSMel Gorman 		 *    Don't require __GFP_FS, since we're not going into the
844283aba9fSMel Gorman 		 *    FS, just waiting on its writeback completion. Worryingly,
845283aba9fSMel Gorman 		 *    ext4 gfs2 and xfs allocate pages with
846283aba9fSMel Gorman 		 *    grab_cache_page_write_begin(,,AOP_FLAG_NOFS), so testing
847283aba9fSMel Gorman 		 *    may_enter_fs here is liable to OOM on them.
848283aba9fSMel Gorman 		 *
849283aba9fSMel Gorman 		 * 3) memcg encounters a page that is not already marked
850283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
851283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
852283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
853283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
854e62e384eSMichal Hocko 		 */
855283aba9fSMel Gorman 		if (PageWriteback(page)) {
856283aba9fSMel Gorman 			/* Case 1 above */
857283aba9fSMel Gorman 			if (current_is_kswapd() &&
858283aba9fSMel Gorman 			    PageReclaim(page) &&
859283aba9fSMel Gorman 			    zone_is_reclaim_writeback(zone)) {
860b1a6f21eSMel Gorman 				nr_immediate++;
861b1a6f21eSMel Gorman 				goto keep_locked;
862283aba9fSMel Gorman 
863283aba9fSMel Gorman 			/* Case 2 above */
864283aba9fSMel Gorman 			} else if (global_reclaim(sc) ||
865c3b94f44SHugh Dickins 			    !PageReclaim(page) || !(sc->gfp_mask & __GFP_IO)) {
866c3b94f44SHugh Dickins 				/*
867c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
868c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
869c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
870c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
871c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
872c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
873c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
874c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
875c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
876c3b94f44SHugh Dickins 				 */
877c3b94f44SHugh Dickins 				SetPageReclaim(page);
87892df3a72SMel Gorman 				nr_writeback++;
879283aba9fSMel Gorman 
880c3b94f44SHugh Dickins 				goto keep_locked;
881283aba9fSMel Gorman 
882283aba9fSMel Gorman 			/* Case 3 above */
883283aba9fSMel Gorman 			} else {
884c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
885e62e384eSMichal Hocko 			}
886283aba9fSMel Gorman 		}
8871da177e4SLinus Torvalds 
88802c6de8dSMinchan Kim 		if (!force_reclaim)
8896a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
89002c6de8dSMinchan Kim 
891dfc8d636SJohannes Weiner 		switch (references) {
892dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
8931da177e4SLinus Torvalds 			goto activate_locked;
89464574746SJohannes Weiner 		case PAGEREF_KEEP:
89564574746SJohannes Weiner 			goto keep_locked;
896dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
897dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
898dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
899dfc8d636SJohannes Weiner 		}
9001da177e4SLinus Torvalds 
9011da177e4SLinus Torvalds 		/*
9021da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
9031da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
9041da177e4SLinus Torvalds 		 */
905b291f000SNick Piggin 		if (PageAnon(page) && !PageSwapCache(page)) {
90663eb6b93SHugh Dickins 			if (!(sc->gfp_mask & __GFP_IO))
90763eb6b93SHugh Dickins 				goto keep_locked;
9085bc7b8acSShaohua Li 			if (!add_to_swap(page, page_list))
9091da177e4SLinus Torvalds 				goto activate_locked;
91063eb6b93SHugh Dickins 			may_enter_fs = 1;
9111da177e4SLinus Torvalds 
912e2be15f6SMel Gorman 			/* Adding to swap updated mapping */
9131da177e4SLinus Torvalds 			mapping = page_mapping(page);
914e2be15f6SMel Gorman 		}
9151da177e4SLinus Torvalds 
9161da177e4SLinus Torvalds 		/*
9171da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
9181da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
9191da177e4SLinus Torvalds 		 */
9201da177e4SLinus Torvalds 		if (page_mapped(page) && mapping) {
92102c6de8dSMinchan Kim 			switch (try_to_unmap(page, ttu_flags)) {
9221da177e4SLinus Torvalds 			case SWAP_FAIL:
9231da177e4SLinus Torvalds 				goto activate_locked;
9241da177e4SLinus Torvalds 			case SWAP_AGAIN:
9251da177e4SLinus Torvalds 				goto keep_locked;
926b291f000SNick Piggin 			case SWAP_MLOCK:
927b291f000SNick Piggin 				goto cull_mlocked;
9281da177e4SLinus Torvalds 			case SWAP_SUCCESS:
9291da177e4SLinus Torvalds 				; /* try to free the page below */
9301da177e4SLinus Torvalds 			}
9311da177e4SLinus Torvalds 		}
9321da177e4SLinus Torvalds 
9331da177e4SLinus Torvalds 		if (PageDirty(page)) {
934ee72886dSMel Gorman 			/*
935ee72886dSMel Gorman 			 * Only kswapd can writeback filesystem pages to
936d43006d5SMel Gorman 			 * avoid risk of stack overflow but only writeback
937d43006d5SMel Gorman 			 * if many dirty pages have been encountered.
938ee72886dSMel Gorman 			 */
939f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
9409e3b2f8cSKonstantin Khlebnikov 					(!current_is_kswapd() ||
941d43006d5SMel Gorman 					 !zone_is_reclaim_dirty(zone))) {
94249ea7eb6SMel Gorman 				/*
94349ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
94449ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
94549ea7eb6SMel Gorman 				 * except we already have the page isolated
94649ea7eb6SMel Gorman 				 * and know it's dirty
94749ea7eb6SMel Gorman 				 */
94849ea7eb6SMel Gorman 				inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE);
94949ea7eb6SMel Gorman 				SetPageReclaim(page);
95049ea7eb6SMel Gorman 
951ee72886dSMel Gorman 				goto keep_locked;
952ee72886dSMel Gorman 			}
953ee72886dSMel Gorman 
954dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
9551da177e4SLinus Torvalds 				goto keep_locked;
9564dd4b920SAndrew Morton 			if (!may_enter_fs)
9571da177e4SLinus Torvalds 				goto keep_locked;
95852a8363eSChristoph Lameter 			if (!sc->may_writepage)
9591da177e4SLinus Torvalds 				goto keep_locked;
9601da177e4SLinus Torvalds 
9611da177e4SLinus Torvalds 			/* Page is dirty, try to write it out here */
9627d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
9631da177e4SLinus Torvalds 			case PAGE_KEEP:
9641da177e4SLinus Torvalds 				goto keep_locked;
9651da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
9661da177e4SLinus Torvalds 				goto activate_locked;
9671da177e4SLinus Torvalds 			case PAGE_SUCCESS:
9687d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
96941ac1999SMel Gorman 					goto keep;
9707d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
9711da177e4SLinus Torvalds 					goto keep;
9727d3579e8SKOSAKI Motohiro 
9731da177e4SLinus Torvalds 				/*
9741da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
9751da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
9761da177e4SLinus Torvalds 				 */
977529ae9aaSNick Piggin 				if (!trylock_page(page))
9781da177e4SLinus Torvalds 					goto keep;
9791da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
9801da177e4SLinus Torvalds 					goto keep_locked;
9811da177e4SLinus Torvalds 				mapping = page_mapping(page);
9821da177e4SLinus Torvalds 			case PAGE_CLEAN:
9831da177e4SLinus Torvalds 				; /* try to free the page below */
9841da177e4SLinus Torvalds 			}
9851da177e4SLinus Torvalds 		}
9861da177e4SLinus Torvalds 
9871da177e4SLinus Torvalds 		/*
9881da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
9891da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
9901da177e4SLinus Torvalds 		 * the page as well.
9911da177e4SLinus Torvalds 		 *
9921da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
9931da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
9941da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
9951da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
9961da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
9971da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
9981da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
9991da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
10001da177e4SLinus Torvalds 		 *
10011da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
10021da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
10031da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
10041da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
10051da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
10061da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
10071da177e4SLinus Torvalds 		 */
1008266cf658SDavid Howells 		if (page_has_private(page)) {
10091da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
10101da177e4SLinus Torvalds 				goto activate_locked;
1011e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1012e286781dSNick Piggin 				unlock_page(page);
1013e286781dSNick Piggin 				if (put_page_testzero(page))
10141da177e4SLinus Torvalds 					goto free_it;
1015e286781dSNick Piggin 				else {
1016e286781dSNick Piggin 					/*
1017e286781dSNick Piggin 					 * rare race with speculative reference.
1018e286781dSNick Piggin 					 * the speculative reference will free
1019e286781dSNick Piggin 					 * this page shortly, so we may
1020e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1021e286781dSNick Piggin 					 * leave it off the LRU).
1022e286781dSNick Piggin 					 */
1023e286781dSNick Piggin 					nr_reclaimed++;
1024e286781dSNick Piggin 					continue;
1025e286781dSNick Piggin 				}
1026e286781dSNick Piggin 			}
10271da177e4SLinus Torvalds 		}
10281da177e4SLinus Torvalds 
1029e286781dSNick Piggin 		if (!mapping || !__remove_mapping(mapping, page))
103049d2e9ccSChristoph Lameter 			goto keep_locked;
10311da177e4SLinus Torvalds 
1032a978d6f5SNick Piggin 		/*
1033a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
1034a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
1035a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
1036a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
1037a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
1038a978d6f5SNick Piggin 		 */
1039a978d6f5SNick Piggin 		__clear_page_locked(page);
1040e286781dSNick Piggin free_it:
104105ff5137SAndrew Morton 		nr_reclaimed++;
1042abe4c3b5SMel Gorman 
1043abe4c3b5SMel Gorman 		/*
1044abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1045abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1046abe4c3b5SMel Gorman 		 */
1047abe4c3b5SMel Gorman 		list_add(&page->lru, &free_pages);
10481da177e4SLinus Torvalds 		continue;
10491da177e4SLinus Torvalds 
1050b291f000SNick Piggin cull_mlocked:
105163d6c5adSHugh Dickins 		if (PageSwapCache(page))
105263d6c5adSHugh Dickins 			try_to_free_swap(page);
1053b291f000SNick Piggin 		unlock_page(page);
1054b291f000SNick Piggin 		putback_lru_page(page);
1055b291f000SNick Piggin 		continue;
1056b291f000SNick Piggin 
10571da177e4SLinus Torvalds activate_locked:
105868a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
105968a22394SRik van Riel 		if (PageSwapCache(page) && vm_swap_full())
1060a2c43eedSHugh Dickins 			try_to_free_swap(page);
1061894bc310SLee Schermerhorn 		VM_BUG_ON(PageActive(page));
10621da177e4SLinus Torvalds 		SetPageActive(page);
10631da177e4SLinus Torvalds 		pgactivate++;
10641da177e4SLinus Torvalds keep_locked:
10651da177e4SLinus Torvalds 		unlock_page(page);
10661da177e4SLinus Torvalds keep:
10671da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1068b291f000SNick Piggin 		VM_BUG_ON(PageLRU(page) || PageUnevictable(page));
10691da177e4SLinus Torvalds 	}
1070abe4c3b5SMel Gorman 
1071cc59850eSKonstantin Khlebnikov 	free_hot_cold_page_list(&free_pages, 1);
1072abe4c3b5SMel Gorman 
10731da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1074f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
107569980e31STim Chen 	mem_cgroup_uncharge_end();
10768e950282SMel Gorman 	*ret_nr_dirty += nr_dirty;
10778e950282SMel Gorman 	*ret_nr_congested += nr_congested;
1078d43006d5SMel Gorman 	*ret_nr_unqueued_dirty += nr_unqueued_dirty;
107992df3a72SMel Gorman 	*ret_nr_writeback += nr_writeback;
1080b1a6f21eSMel Gorman 	*ret_nr_immediate += nr_immediate;
108105ff5137SAndrew Morton 	return nr_reclaimed;
10821da177e4SLinus Torvalds }
10831da177e4SLinus Torvalds 
108402c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
108502c6de8dSMinchan Kim 					    struct list_head *page_list)
108602c6de8dSMinchan Kim {
108702c6de8dSMinchan Kim 	struct scan_control sc = {
108802c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
108902c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
109002c6de8dSMinchan Kim 		.may_unmap = 1,
109102c6de8dSMinchan Kim 	};
10928e950282SMel Gorman 	unsigned long ret, dummy1, dummy2, dummy3, dummy4, dummy5;
109302c6de8dSMinchan Kim 	struct page *page, *next;
109402c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
109502c6de8dSMinchan Kim 
109602c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
109702c6de8dSMinchan Kim 		if (page_is_file_cache(page) && !PageDirty(page)) {
109802c6de8dSMinchan Kim 			ClearPageActive(page);
109902c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
110002c6de8dSMinchan Kim 		}
110102c6de8dSMinchan Kim 	}
110202c6de8dSMinchan Kim 
110302c6de8dSMinchan Kim 	ret = shrink_page_list(&clean_pages, zone, &sc,
110402c6de8dSMinchan Kim 			TTU_UNMAP|TTU_IGNORE_ACCESS,
11058e950282SMel Gorman 			&dummy1, &dummy2, &dummy3, &dummy4, &dummy5, true);
110602c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
110702c6de8dSMinchan Kim 	__mod_zone_page_state(zone, NR_ISOLATED_FILE, -ret);
110802c6de8dSMinchan Kim 	return ret;
110902c6de8dSMinchan Kim }
111002c6de8dSMinchan Kim 
11115ad333ebSAndy Whitcroft /*
11125ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
11135ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
11145ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
11155ad333ebSAndy Whitcroft  *
11165ad333ebSAndy Whitcroft  * page:	page to consider
11175ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
11185ad333ebSAndy Whitcroft  *
11195ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
11205ad333ebSAndy Whitcroft  */
1121f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
11225ad333ebSAndy Whitcroft {
11235ad333ebSAndy Whitcroft 	int ret = -EINVAL;
11245ad333ebSAndy Whitcroft 
11255ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
11265ad333ebSAndy Whitcroft 	if (!PageLRU(page))
11275ad333ebSAndy Whitcroft 		return ret;
11285ad333ebSAndy Whitcroft 
1129e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1130e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1131894bc310SLee Schermerhorn 		return ret;
1132894bc310SLee Schermerhorn 
11335ad333ebSAndy Whitcroft 	ret = -EBUSY;
113408e552c6SKAMEZAWA Hiroyuki 
1135c8244935SMel Gorman 	/*
1136c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1137c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1138c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1139c8244935SMel Gorman 	 *
1140c8244935SMel Gorman 	 * ISOLATE_CLEAN means that only clean pages should be isolated. This
1141c8244935SMel Gorman 	 * is used by reclaim when it is cannot write to backing storage
1142c8244935SMel Gorman 	 *
1143c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1144c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1145c8244935SMel Gorman 	 */
1146c8244935SMel Gorman 	if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
1147c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1148c8244935SMel Gorman 		if (PageWriteback(page))
114939deaf85SMinchan Kim 			return ret;
115039deaf85SMinchan Kim 
1151c8244935SMel Gorman 		if (PageDirty(page)) {
1152c8244935SMel Gorman 			struct address_space *mapping;
1153c8244935SMel Gorman 
1154c8244935SMel Gorman 			/* ISOLATE_CLEAN means only clean pages */
1155c8244935SMel Gorman 			if (mode & ISOLATE_CLEAN)
1156c8244935SMel Gorman 				return ret;
1157c8244935SMel Gorman 
1158c8244935SMel Gorman 			/*
1159c8244935SMel Gorman 			 * Only pages without mappings or that have a
1160c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
1161c8244935SMel Gorman 			 * without blocking
1162c8244935SMel Gorman 			 */
1163c8244935SMel Gorman 			mapping = page_mapping(page);
1164c8244935SMel Gorman 			if (mapping && !mapping->a_ops->migratepage)
1165c8244935SMel Gorman 				return ret;
1166c8244935SMel Gorman 		}
1167c8244935SMel Gorman 	}
1168c8244935SMel Gorman 
1169f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1170f80c0673SMinchan Kim 		return ret;
1171f80c0673SMinchan Kim 
11725ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
11735ad333ebSAndy Whitcroft 		/*
11745ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
11755ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
11765ad333ebSAndy Whitcroft 		 * page release code relies on it.
11775ad333ebSAndy Whitcroft 		 */
11785ad333ebSAndy Whitcroft 		ClearPageLRU(page);
11795ad333ebSAndy Whitcroft 		ret = 0;
11805ad333ebSAndy Whitcroft 	}
11815ad333ebSAndy Whitcroft 
11825ad333ebSAndy Whitcroft 	return ret;
11835ad333ebSAndy Whitcroft }
11845ad333ebSAndy Whitcroft 
118549d2e9ccSChristoph Lameter /*
11861da177e4SLinus Torvalds  * zone->lru_lock is heavily contended.  Some of the functions that
11871da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
11881da177e4SLinus Torvalds  * and working on them outside the LRU lock.
11891da177e4SLinus Torvalds  *
11901da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
11911da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
11921da177e4SLinus Torvalds  *
11931da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
11941da177e4SLinus Torvalds  *
11951da177e4SLinus Torvalds  * @nr_to_scan:	The number of pages to look through on the list.
11965dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
11971da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1198f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1199fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
12005ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
12013cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
12021da177e4SLinus Torvalds  *
12031da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
12041da177e4SLinus Torvalds  */
120569e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
12065dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1207fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
12083cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
12091da177e4SLinus Torvalds {
121075b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
121169e05944SAndrew Morton 	unsigned long nr_taken = 0;
1212c9b02d97SWu Fengguang 	unsigned long scan;
12131da177e4SLinus Torvalds 
1214c9b02d97SWu Fengguang 	for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
12155ad333ebSAndy Whitcroft 		struct page *page;
1216fa9add64SHugh Dickins 		int nr_pages;
12175ad333ebSAndy Whitcroft 
12181da177e4SLinus Torvalds 		page = lru_to_page(src);
12191da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
12201da177e4SLinus Torvalds 
1221725d704eSNick Piggin 		VM_BUG_ON(!PageLRU(page));
12228d438f96SNick Piggin 
1223f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
12245ad333ebSAndy Whitcroft 		case 0:
1225fa9add64SHugh Dickins 			nr_pages = hpage_nr_pages(page);
1226fa9add64SHugh Dickins 			mem_cgroup_update_lru_size(lruvec, lru, -nr_pages);
12275ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
1228fa9add64SHugh Dickins 			nr_taken += nr_pages;
12295ad333ebSAndy Whitcroft 			break;
12307c8ee9a8SNick Piggin 
12315ad333ebSAndy Whitcroft 		case -EBUSY:
12325ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
12335ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
12345ad333ebSAndy Whitcroft 			continue;
12355ad333ebSAndy Whitcroft 
12365ad333ebSAndy Whitcroft 		default:
12375ad333ebSAndy Whitcroft 			BUG();
12385ad333ebSAndy Whitcroft 		}
12395ad333ebSAndy Whitcroft 	}
12401da177e4SLinus Torvalds 
1241f626012dSHugh Dickins 	*nr_scanned = scan;
124275b00af7SHugh Dickins 	trace_mm_vmscan_lru_isolate(sc->order, nr_to_scan, scan,
124375b00af7SHugh Dickins 				    nr_taken, mode, is_file_lru(lru));
12441da177e4SLinus Torvalds 	return nr_taken;
12451da177e4SLinus Torvalds }
12461da177e4SLinus Torvalds 
124762695a84SNick Piggin /**
124862695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
124962695a84SNick Piggin  * @page: page to isolate from its LRU list
125062695a84SNick Piggin  *
125162695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
125262695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
125362695a84SNick Piggin  *
125462695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
125562695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
125662695a84SNick Piggin  *
125762695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1258894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1259894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1260894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
126162695a84SNick Piggin  *
126262695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
126362695a84SNick Piggin  * found will be decremented.
126462695a84SNick Piggin  *
126562695a84SNick Piggin  * Restrictions:
126662695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
126762695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
126862695a84SNick Piggin  *     without a stable reference).
126962695a84SNick Piggin  * (2) the lru_lock must not be held.
127062695a84SNick Piggin  * (3) interrupts must be enabled.
127162695a84SNick Piggin  */
127262695a84SNick Piggin int isolate_lru_page(struct page *page)
127362695a84SNick Piggin {
127462695a84SNick Piggin 	int ret = -EBUSY;
127562695a84SNick Piggin 
12760c917313SKonstantin Khlebnikov 	VM_BUG_ON(!page_count(page));
12770c917313SKonstantin Khlebnikov 
127862695a84SNick Piggin 	if (PageLRU(page)) {
127962695a84SNick Piggin 		struct zone *zone = page_zone(page);
1280fa9add64SHugh Dickins 		struct lruvec *lruvec;
128162695a84SNick Piggin 
128262695a84SNick Piggin 		spin_lock_irq(&zone->lru_lock);
1283fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
12840c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1285894bc310SLee Schermerhorn 			int lru = page_lru(page);
12860c917313SKonstantin Khlebnikov 			get_page(page);
128762695a84SNick Piggin 			ClearPageLRU(page);
1288fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1289fa9add64SHugh Dickins 			ret = 0;
129062695a84SNick Piggin 		}
129162695a84SNick Piggin 		spin_unlock_irq(&zone->lru_lock);
129262695a84SNick Piggin 	}
129362695a84SNick Piggin 	return ret;
129462695a84SNick Piggin }
129562695a84SNick Piggin 
12965ad333ebSAndy Whitcroft /*
1297d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1298d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1299d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1300d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1301d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
130235cd7815SRik van Riel  */
130335cd7815SRik van Riel static int too_many_isolated(struct zone *zone, int file,
130435cd7815SRik van Riel 		struct scan_control *sc)
130535cd7815SRik van Riel {
130635cd7815SRik van Riel 	unsigned long inactive, isolated;
130735cd7815SRik van Riel 
130835cd7815SRik van Riel 	if (current_is_kswapd())
130935cd7815SRik van Riel 		return 0;
131035cd7815SRik van Riel 
131189b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
131235cd7815SRik van Riel 		return 0;
131335cd7815SRik van Riel 
131435cd7815SRik van Riel 	if (file) {
131535cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_FILE);
131635cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_FILE);
131735cd7815SRik van Riel 	} else {
131835cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_ANON);
131935cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_ANON);
132035cd7815SRik van Riel 	}
132135cd7815SRik van Riel 
13223cf23841SFengguang Wu 	/*
13233cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
13243cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
13253cf23841SFengguang Wu 	 * deadlock.
13263cf23841SFengguang Wu 	 */
13273cf23841SFengguang Wu 	if ((sc->gfp_mask & GFP_IOFS) == GFP_IOFS)
13283cf23841SFengguang Wu 		inactive >>= 3;
13293cf23841SFengguang Wu 
133035cd7815SRik van Riel 	return isolated > inactive;
133135cd7815SRik van Riel }
133235cd7815SRik van Riel 
133366635629SMel Gorman static noinline_for_stack void
133475b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
133566635629SMel Gorman {
133627ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
133727ac81d8SKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
13383f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
133966635629SMel Gorman 
134066635629SMel Gorman 	/*
134166635629SMel Gorman 	 * Put back any unfreeable pages.
134266635629SMel Gorman 	 */
134366635629SMel Gorman 	while (!list_empty(page_list)) {
13443f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
134566635629SMel Gorman 		int lru;
13463f79768fSHugh Dickins 
134766635629SMel Gorman 		VM_BUG_ON(PageLRU(page));
134866635629SMel Gorman 		list_del(&page->lru);
134939b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
135066635629SMel Gorman 			spin_unlock_irq(&zone->lru_lock);
135166635629SMel Gorman 			putback_lru_page(page);
135266635629SMel Gorman 			spin_lock_irq(&zone->lru_lock);
135366635629SMel Gorman 			continue;
135466635629SMel Gorman 		}
1355fa9add64SHugh Dickins 
1356fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
1357fa9add64SHugh Dickins 
13587a608572SLinus Torvalds 		SetPageLRU(page);
135966635629SMel Gorman 		lru = page_lru(page);
1360fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1361fa9add64SHugh Dickins 
136266635629SMel Gorman 		if (is_active_lru(lru)) {
136366635629SMel Gorman 			int file = is_file_lru(lru);
13649992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
13659992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
136666635629SMel Gorman 		}
13672bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
13682bcf8879SHugh Dickins 			__ClearPageLRU(page);
13692bcf8879SHugh Dickins 			__ClearPageActive(page);
1370fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
13712bcf8879SHugh Dickins 
13722bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
137366635629SMel Gorman 				spin_unlock_irq(&zone->lru_lock);
13742bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
137566635629SMel Gorman 				spin_lock_irq(&zone->lru_lock);
13762bcf8879SHugh Dickins 			} else
13772bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
137866635629SMel Gorman 		}
137966635629SMel Gorman 	}
138066635629SMel Gorman 
13813f79768fSHugh Dickins 	/*
13823f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
13833f79768fSHugh Dickins 	 */
13843f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
138566635629SMel Gorman }
138666635629SMel Gorman 
138766635629SMel Gorman /*
13881742f19fSAndrew Morton  * shrink_inactive_list() is a helper for shrink_zone().  It returns the number
13891742f19fSAndrew Morton  * of reclaimed pages
13901da177e4SLinus Torvalds  */
139166635629SMel Gorman static noinline_for_stack unsigned long
13921a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
13939e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
13941da177e4SLinus Torvalds {
13951da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1396e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
139705ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1398e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
13998e950282SMel Gorman 	unsigned long nr_dirty = 0;
14008e950282SMel Gorman 	unsigned long nr_congested = 0;
1401e2be15f6SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
140292df3a72SMel Gorman 	unsigned long nr_writeback = 0;
1403b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
1404f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
14053cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
14061a93be0eSKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
14071a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
140878dc583dSKOSAKI Motohiro 
140935cd7815SRik van Riel 	while (unlikely(too_many_isolated(zone, file, sc))) {
141058355c78SKOSAKI Motohiro 		congestion_wait(BLK_RW_ASYNC, HZ/10);
141135cd7815SRik van Riel 
141235cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
141335cd7815SRik van Riel 		if (fatal_signal_pending(current))
141435cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
141535cd7815SRik van Riel 	}
141635cd7815SRik van Riel 
14171da177e4SLinus Torvalds 	lru_add_drain();
1418f80c0673SMinchan Kim 
1419f80c0673SMinchan Kim 	if (!sc->may_unmap)
142061317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1421f80c0673SMinchan Kim 	if (!sc->may_writepage)
142261317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1423f80c0673SMinchan Kim 
14241da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
14251da177e4SLinus Torvalds 
14265dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
14275dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
142895d918fcSKonstantin Khlebnikov 
142995d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
143095d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
143195d918fcSKonstantin Khlebnikov 
143289b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
1433e247dbceSKOSAKI Motohiro 		zone->pages_scanned += nr_scanned;
1434b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
143575b00af7SHugh Dickins 			__count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scanned);
1436b35ea17bSKOSAKI Motohiro 		else
143775b00af7SHugh Dickins 			__count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scanned);
1438b35ea17bSKOSAKI Motohiro 	}
143966635629SMel Gorman 	spin_unlock_irq(&zone->lru_lock);
1440d563c050SHillf Danton 
1441d563c050SHillf Danton 	if (nr_taken == 0)
144266635629SMel Gorman 		return 0;
1443b35ea17bSKOSAKI Motohiro 
144402c6de8dSMinchan Kim 	nr_reclaimed = shrink_page_list(&page_list, zone, sc, TTU_UNMAP,
14458e950282SMel Gorman 				&nr_dirty, &nr_unqueued_dirty, &nr_congested,
14468e950282SMel Gorman 				&nr_writeback, &nr_immediate,
1447b1a6f21eSMel Gorman 				false);
1448c661b078SAndy Whitcroft 
14493f79768fSHugh Dickins 	spin_lock_irq(&zone->lru_lock);
14503f79768fSHugh Dickins 
145195d918fcSKonstantin Khlebnikov 	reclaim_stat->recent_scanned[file] += nr_taken;
1452d563c050SHillf Danton 
1453904249aaSYing Han 	if (global_reclaim(sc)) {
1454b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1455904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_KSWAPD, zone,
1456904249aaSYing Han 					       nr_reclaimed);
1457904249aaSYing Han 		else
1458904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_DIRECT, zone,
1459904249aaSYing Han 					       nr_reclaimed);
1460904249aaSYing Han 	}
1461a74609faSNick Piggin 
146227ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
14633f79768fSHugh Dickins 
146495d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
14653f79768fSHugh Dickins 
14663f79768fSHugh Dickins 	spin_unlock_irq(&zone->lru_lock);
14673f79768fSHugh Dickins 
14683f79768fSHugh Dickins 	free_hot_cold_page_list(&page_list, 1);
1469e11da5b4SMel Gorman 
147092df3a72SMel Gorman 	/*
147192df3a72SMel Gorman 	 * If reclaim is isolating dirty pages under writeback, it implies
147292df3a72SMel Gorman 	 * that the long-lived page allocation rate is exceeding the page
147392df3a72SMel Gorman 	 * laundering rate. Either the global limits are not being effective
147492df3a72SMel Gorman 	 * at throttling processes due to the page distribution throughout
147592df3a72SMel Gorman 	 * zones or there is heavy usage of a slow backing device. The
147692df3a72SMel Gorman 	 * only option is to throttle from reclaim context which is not ideal
147792df3a72SMel Gorman 	 * as there is no guarantee the dirtying process is throttled in the
147892df3a72SMel Gorman 	 * same way balance_dirty_pages() manages.
147992df3a72SMel Gorman 	 *
14808e950282SMel Gorman 	 * Once a zone is flagged ZONE_WRITEBACK, kswapd will count the number
14818e950282SMel Gorman 	 * of pages under pages flagged for immediate reclaim and stall if any
14828e950282SMel Gorman 	 * are encountered in the nr_immediate check below.
148392df3a72SMel Gorman 	 */
1484918fc718SMel Gorman 	if (nr_writeback && nr_writeback == nr_taken)
1485283aba9fSMel Gorman 		zone_set_flag(zone, ZONE_WRITEBACK);
148692df3a72SMel Gorman 
1487d43006d5SMel Gorman 	/*
1488b1a6f21eSMel Gorman 	 * memcg will stall in page writeback so only consider forcibly
1489b1a6f21eSMel Gorman 	 * stalling for global reclaim
1490d43006d5SMel Gorman 	 */
1491b1a6f21eSMel Gorman 	if (global_reclaim(sc)) {
1492b1a6f21eSMel Gorman 		/*
14938e950282SMel Gorman 		 * Tag a zone as congested if all the dirty pages scanned were
14948e950282SMel Gorman 		 * backed by a congested BDI and wait_iff_congested will stall.
14958e950282SMel Gorman 		 */
14968e950282SMel Gorman 		if (nr_dirty && nr_dirty == nr_congested)
14978e950282SMel Gorman 			zone_set_flag(zone, ZONE_CONGESTED);
14988e950282SMel Gorman 
14998e950282SMel Gorman 		/*
1500b1a6f21eSMel Gorman 		 * If dirty pages are scanned that are not queued for IO, it
1501b1a6f21eSMel Gorman 		 * implies that flushers are not keeping up. In this case, flag
1502b1a6f21eSMel Gorman 		 * the zone ZONE_TAIL_LRU_DIRTY and kswapd will start writing
1503b1a6f21eSMel Gorman 		 * pages from reclaim context. It will forcibly stall in the
1504b1a6f21eSMel Gorman 		 * next check.
1505b1a6f21eSMel Gorman 		 */
1506b1a6f21eSMel Gorman 		if (nr_unqueued_dirty == nr_taken)
1507d43006d5SMel Gorman 			zone_set_flag(zone, ZONE_TAIL_LRU_DIRTY);
1508b1a6f21eSMel Gorman 
1509b1a6f21eSMel Gorman 		/*
1510b1a6f21eSMel Gorman 		 * In addition, if kswapd scans pages marked marked for
1511b1a6f21eSMel Gorman 		 * immediate reclaim and under writeback (nr_immediate), it
1512b1a6f21eSMel Gorman 		 * implies that pages are cycling through the LRU faster than
1513b1a6f21eSMel Gorman 		 * they are written so also forcibly stall.
1514b1a6f21eSMel Gorman 		 */
1515b1a6f21eSMel Gorman 		if (nr_unqueued_dirty == nr_taken || nr_immediate)
1516b1a6f21eSMel Gorman 			congestion_wait(BLK_RW_ASYNC, HZ/10);
1517e2be15f6SMel Gorman 	}
1518d43006d5SMel Gorman 
15198e950282SMel Gorman 	/*
15208e950282SMel Gorman 	 * Stall direct reclaim for IO completions if underlying BDIs or zone
15218e950282SMel Gorman 	 * is congested. Allow kswapd to continue until it starts encountering
15228e950282SMel Gorman 	 * unqueued dirty pages or cycling through the LRU too quickly.
15238e950282SMel Gorman 	 */
15248e950282SMel Gorman 	if (!sc->hibernation_mode && !current_is_kswapd())
15258e950282SMel Gorman 		wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10);
15268e950282SMel Gorman 
1527e11da5b4SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(zone->zone_pgdat->node_id,
1528e11da5b4SMel Gorman 		zone_idx(zone),
1529e11da5b4SMel Gorman 		nr_scanned, nr_reclaimed,
15309e3b2f8cSKonstantin Khlebnikov 		sc->priority,
153123b9da55SMel Gorman 		trace_shrink_flags(file));
153205ff5137SAndrew Morton 	return nr_reclaimed;
15331da177e4SLinus Torvalds }
15341da177e4SLinus Torvalds 
15353bb1a852SMartin Bligh /*
15361cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
15371cfb419bSKAMEZAWA Hiroyuki  *
15381cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
15391cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
15401cfb419bSKAMEZAWA Hiroyuki  *
15411cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
15421cfb419bSKAMEZAWA Hiroyuki  * appropriate to hold zone->lru_lock across the whole operation.  But if
15431cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
15441cfb419bSKAMEZAWA Hiroyuki  * should drop zone->lru_lock around each page.  It's impossible to balance
15451cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
15461cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
15471cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
15481cfb419bSKAMEZAWA Hiroyuki  *
15491cfb419bSKAMEZAWA Hiroyuki  * The downside is that we have to touch page->_count against each page.
15501cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
15511cfb419bSKAMEZAWA Hiroyuki  */
15521cfb419bSKAMEZAWA Hiroyuki 
1553fa9add64SHugh Dickins static void move_active_pages_to_lru(struct lruvec *lruvec,
15543eb4140fSWu Fengguang 				     struct list_head *list,
15552bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
15563eb4140fSWu Fengguang 				     enum lru_list lru)
15573eb4140fSWu Fengguang {
1558fa9add64SHugh Dickins 	struct zone *zone = lruvec_zone(lruvec);
15593eb4140fSWu Fengguang 	unsigned long pgmoved = 0;
15603eb4140fSWu Fengguang 	struct page *page;
1561fa9add64SHugh Dickins 	int nr_pages;
15623eb4140fSWu Fengguang 
15633eb4140fSWu Fengguang 	while (!list_empty(list)) {
15643eb4140fSWu Fengguang 		page = lru_to_page(list);
1565fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
15663eb4140fSWu Fengguang 
15673eb4140fSWu Fengguang 		VM_BUG_ON(PageLRU(page));
15683eb4140fSWu Fengguang 		SetPageLRU(page);
15693eb4140fSWu Fengguang 
1570fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
1571fa9add64SHugh Dickins 		mem_cgroup_update_lru_size(lruvec, lru, nr_pages);
1572925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
1573fa9add64SHugh Dickins 		pgmoved += nr_pages;
15743eb4140fSWu Fengguang 
15752bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
15762bcf8879SHugh Dickins 			__ClearPageLRU(page);
15772bcf8879SHugh Dickins 			__ClearPageActive(page);
1578fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
15792bcf8879SHugh Dickins 
15802bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
15813eb4140fSWu Fengguang 				spin_unlock_irq(&zone->lru_lock);
15822bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
15833eb4140fSWu Fengguang 				spin_lock_irq(&zone->lru_lock);
15842bcf8879SHugh Dickins 			} else
15852bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
15863eb4140fSWu Fengguang 		}
15873eb4140fSWu Fengguang 	}
15883eb4140fSWu Fengguang 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved);
15893eb4140fSWu Fengguang 	if (!is_active_lru(lru))
15903eb4140fSWu Fengguang 		__count_vm_events(PGDEACTIVATE, pgmoved);
15913eb4140fSWu Fengguang }
15921cfb419bSKAMEZAWA Hiroyuki 
1593f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
15941a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1595f16015fbSJohannes Weiner 			       struct scan_control *sc,
15969e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
15971cfb419bSKAMEZAWA Hiroyuki {
159844c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1599f626012dSHugh Dickins 	unsigned long nr_scanned;
16006fe6b7e3SWu Fengguang 	unsigned long vm_flags;
16011cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
16028cab4754SWu Fengguang 	LIST_HEAD(l_active);
1603b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
16041cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
16051a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
160644c241f1SKOSAKI Motohiro 	unsigned long nr_rotated = 0;
1607f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
16083cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
16091a93be0eSKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
16101cfb419bSKAMEZAWA Hiroyuki 
16111da177e4SLinus Torvalds 	lru_add_drain();
1612f80c0673SMinchan Kim 
1613f80c0673SMinchan Kim 	if (!sc->may_unmap)
161461317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1615f80c0673SMinchan Kim 	if (!sc->may_writepage)
161661317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1617f80c0673SMinchan Kim 
16181da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
1619925b7673SJohannes Weiner 
16205dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
16215dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
162289b5fae5SJohannes Weiner 	if (global_reclaim(sc))
1623f626012dSHugh Dickins 		zone->pages_scanned += nr_scanned;
162489b5fae5SJohannes Weiner 
1625b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
16261cfb419bSKAMEZAWA Hiroyuki 
1627f626012dSHugh Dickins 	__count_zone_vm_events(PGREFILL, zone, nr_scanned);
16283cb99451SKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
1629a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
16301da177e4SLinus Torvalds 	spin_unlock_irq(&zone->lru_lock);
16311da177e4SLinus Torvalds 
16321da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
16331da177e4SLinus Torvalds 		cond_resched();
16341da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
16351da177e4SLinus Torvalds 		list_del(&page->lru);
16367e9cd484SRik van Riel 
163739b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1638894bc310SLee Schermerhorn 			putback_lru_page(page);
1639894bc310SLee Schermerhorn 			continue;
1640894bc310SLee Schermerhorn 		}
1641894bc310SLee Schermerhorn 
1642cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
1643cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
1644cc715d99SMel Gorman 				if (page_has_private(page))
1645cc715d99SMel Gorman 					try_to_release_page(page, 0);
1646cc715d99SMel Gorman 				unlock_page(page);
1647cc715d99SMel Gorman 			}
1648cc715d99SMel Gorman 		}
1649cc715d99SMel Gorman 
1650c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
1651c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
16529992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
16538cab4754SWu Fengguang 			/*
16548cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
16558cab4754SWu Fengguang 			 * give them one more trip around the active list. So
16568cab4754SWu Fengguang 			 * that executable code get better chances to stay in
16578cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
16588cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
16598cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
16608cab4754SWu Fengguang 			 * so we ignore them here.
16618cab4754SWu Fengguang 			 */
166241e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
16638cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
16648cab4754SWu Fengguang 				continue;
16658cab4754SWu Fengguang 			}
16668cab4754SWu Fengguang 		}
16677e9cd484SRik van Riel 
16685205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
16691da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
16701da177e4SLinus Torvalds 	}
16711da177e4SLinus Torvalds 
1672b555749aSAndrew Morton 	/*
16738cab4754SWu Fengguang 	 * Move pages back to the lru list.
1674b555749aSAndrew Morton 	 */
16752a1dc509SJohannes Weiner 	spin_lock_irq(&zone->lru_lock);
16764f98a2feSRik van Riel 	/*
16778cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
16788cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
16798cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
16808cab4754SWu Fengguang 	 * get_scan_ratio.
1681556adecbSRik van Riel 	 */
1682b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
1683556adecbSRik van Riel 
1684fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
1685fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1686a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1687f8891e5eSChristoph Lameter 	spin_unlock_irq(&zone->lru_lock);
16882bcf8879SHugh Dickins 
16892bcf8879SHugh Dickins 	free_hot_cold_page_list(&l_hold, 1);
16901da177e4SLinus Torvalds }
16911da177e4SLinus Torvalds 
169274e3f3c3SMinchan Kim #ifdef CONFIG_SWAP
169314797e23SKOSAKI Motohiro static int inactive_anon_is_low_global(struct zone *zone)
1694f89eb90eSKOSAKI Motohiro {
1695f89eb90eSKOSAKI Motohiro 	unsigned long active, inactive;
1696f89eb90eSKOSAKI Motohiro 
1697f89eb90eSKOSAKI Motohiro 	active = zone_page_state(zone, NR_ACTIVE_ANON);
1698f89eb90eSKOSAKI Motohiro 	inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1699f89eb90eSKOSAKI Motohiro 
1700f89eb90eSKOSAKI Motohiro 	if (inactive * zone->inactive_ratio < active)
1701f89eb90eSKOSAKI Motohiro 		return 1;
1702f89eb90eSKOSAKI Motohiro 
1703f89eb90eSKOSAKI Motohiro 	return 0;
1704f89eb90eSKOSAKI Motohiro }
1705f89eb90eSKOSAKI Motohiro 
170614797e23SKOSAKI Motohiro /**
170714797e23SKOSAKI Motohiro  * inactive_anon_is_low - check if anonymous pages need to be deactivated
1708c56d5c7dSKonstantin Khlebnikov  * @lruvec: LRU vector to check
170914797e23SKOSAKI Motohiro  *
171014797e23SKOSAKI Motohiro  * Returns true if the zone does not have enough inactive anon pages,
171114797e23SKOSAKI Motohiro  * meaning some active anon pages need to be deactivated.
171214797e23SKOSAKI Motohiro  */
1713c56d5c7dSKonstantin Khlebnikov static int inactive_anon_is_low(struct lruvec *lruvec)
171414797e23SKOSAKI Motohiro {
171574e3f3c3SMinchan Kim 	/*
171674e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
171774e3f3c3SMinchan Kim 	 * is pointless.
171874e3f3c3SMinchan Kim 	 */
171974e3f3c3SMinchan Kim 	if (!total_swap_pages)
172074e3f3c3SMinchan Kim 		return 0;
172174e3f3c3SMinchan Kim 
1722c3c787e8SHugh Dickins 	if (!mem_cgroup_disabled())
1723c56d5c7dSKonstantin Khlebnikov 		return mem_cgroup_inactive_anon_is_low(lruvec);
1724f16015fbSJohannes Weiner 
1725c56d5c7dSKonstantin Khlebnikov 	return inactive_anon_is_low_global(lruvec_zone(lruvec));
172614797e23SKOSAKI Motohiro }
172774e3f3c3SMinchan Kim #else
1728c56d5c7dSKonstantin Khlebnikov static inline int inactive_anon_is_low(struct lruvec *lruvec)
172974e3f3c3SMinchan Kim {
173074e3f3c3SMinchan Kim 	return 0;
173174e3f3c3SMinchan Kim }
173274e3f3c3SMinchan Kim #endif
173314797e23SKOSAKI Motohiro 
173456e49d21SRik van Riel /**
173556e49d21SRik van Riel  * inactive_file_is_low - check if file pages need to be deactivated
1736c56d5c7dSKonstantin Khlebnikov  * @lruvec: LRU vector to check
173756e49d21SRik van Riel  *
173856e49d21SRik van Riel  * When the system is doing streaming IO, memory pressure here
173956e49d21SRik van Riel  * ensures that active file pages get deactivated, until more
174056e49d21SRik van Riel  * than half of the file pages are on the inactive list.
174156e49d21SRik van Riel  *
174256e49d21SRik van Riel  * Once we get to that situation, protect the system's working
174356e49d21SRik van Riel  * set from being evicted by disabling active file page aging.
174456e49d21SRik van Riel  *
174556e49d21SRik van Riel  * This uses a different ratio than the anonymous pages, because
174656e49d21SRik van Riel  * the page cache uses a use-once replacement algorithm.
174756e49d21SRik van Riel  */
1748c56d5c7dSKonstantin Khlebnikov static int inactive_file_is_low(struct lruvec *lruvec)
174956e49d21SRik van Riel {
1750e3790144SJohannes Weiner 	unsigned long inactive;
1751e3790144SJohannes Weiner 	unsigned long active;
175256e49d21SRik van Riel 
1753e3790144SJohannes Weiner 	inactive = get_lru_size(lruvec, LRU_INACTIVE_FILE);
1754e3790144SJohannes Weiner 	active = get_lru_size(lruvec, LRU_ACTIVE_FILE);
1755e3790144SJohannes Weiner 
1756e3790144SJohannes Weiner 	return active > inactive;
175756e49d21SRik van Riel }
175856e49d21SRik van Riel 
175975b00af7SHugh Dickins static int inactive_list_is_low(struct lruvec *lruvec, enum lru_list lru)
1760b39415b2SRik van Riel {
176175b00af7SHugh Dickins 	if (is_file_lru(lru))
1762c56d5c7dSKonstantin Khlebnikov 		return inactive_file_is_low(lruvec);
1763b39415b2SRik van Riel 	else
1764c56d5c7dSKonstantin Khlebnikov 		return inactive_anon_is_low(lruvec);
1765b39415b2SRik van Riel }
1766b39415b2SRik van Riel 
17674f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
17681a93be0eSKonstantin Khlebnikov 				 struct lruvec *lruvec, struct scan_control *sc)
1769b69408e8SChristoph Lameter {
1770b39415b2SRik van Riel 	if (is_active_lru(lru)) {
177175b00af7SHugh Dickins 		if (inactive_list_is_low(lruvec, lru))
17721a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
1773556adecbSRik van Riel 		return 0;
1774556adecbSRik van Riel 	}
1775556adecbSRik van Riel 
17761a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
1777b69408e8SChristoph Lameter }
1778b69408e8SChristoph Lameter 
17793d58ab5cSKonstantin Khlebnikov static int vmscan_swappiness(struct scan_control *sc)
17801f4c025bSKAMEZAWA Hiroyuki {
178189b5fae5SJohannes Weiner 	if (global_reclaim(sc))
17821f4c025bSKAMEZAWA Hiroyuki 		return vm_swappiness;
17833d58ab5cSKonstantin Khlebnikov 	return mem_cgroup_swappiness(sc->target_mem_cgroup);
17841f4c025bSKAMEZAWA Hiroyuki }
17851f4c025bSKAMEZAWA Hiroyuki 
17869a265114SJohannes Weiner enum scan_balance {
17879a265114SJohannes Weiner 	SCAN_EQUAL,
17889a265114SJohannes Weiner 	SCAN_FRACT,
17899a265114SJohannes Weiner 	SCAN_ANON,
17909a265114SJohannes Weiner 	SCAN_FILE,
17919a265114SJohannes Weiner };
17929a265114SJohannes Weiner 
17931da177e4SLinus Torvalds /*
17944f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
17954f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
17964f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
17974f98a2feSRik van Riel  * onto the active list instead of evict.
17984f98a2feSRik van Riel  *
1799be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
1800be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
18014f98a2feSRik van Riel  */
180290126375SKonstantin Khlebnikov static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
18039e3b2f8cSKonstantin Khlebnikov 			   unsigned long *nr)
18044f98a2feSRik van Riel {
180590126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
18069a265114SJohannes Weiner 	u64 fraction[2];
18079a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
180890126375SKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
18099a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
18109a265114SJohannes Weiner 	enum scan_balance scan_balance;
18119a265114SJohannes Weiner 	unsigned long anon, file, free;
18129a265114SJohannes Weiner 	bool force_scan = false;
18139a265114SJohannes Weiner 	unsigned long ap, fp;
18149a265114SJohannes Weiner 	enum lru_list lru;
1815246e87a9SKAMEZAWA Hiroyuki 
1816f11c0ca5SJohannes Weiner 	/*
1817f11c0ca5SJohannes Weiner 	 * If the zone or memcg is small, nr[l] can be 0.  This
1818f11c0ca5SJohannes Weiner 	 * results in no scanning on this priority and a potential
1819f11c0ca5SJohannes Weiner 	 * priority drop.  Global direct reclaim can go to the next
1820f11c0ca5SJohannes Weiner 	 * zone and tends to have no problems. Global kswapd is for
1821f11c0ca5SJohannes Weiner 	 * zone balancing and it needs to scan a minimum amount. When
1822f11c0ca5SJohannes Weiner 	 * reclaiming for a memcg, a priority drop can cause high
1823f11c0ca5SJohannes Weiner 	 * latencies, so it's better to scan a minimum amount there as
1824f11c0ca5SJohannes Weiner 	 * well.
1825f11c0ca5SJohannes Weiner 	 */
182690126375SKonstantin Khlebnikov 	if (current_is_kswapd() && zone->all_unreclaimable)
1827a4d3e9e7SJohannes Weiner 		force_scan = true;
182889b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
1829a4d3e9e7SJohannes Weiner 		force_scan = true;
183076a33fc3SShaohua Li 
183176a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
1832ec8acf20SShaohua Li 	if (!sc->may_swap || (get_nr_swap_pages() <= 0)) {
18339a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
183476a33fc3SShaohua Li 		goto out;
183576a33fc3SShaohua Li 	}
18364f98a2feSRik van Riel 
183710316b31SJohannes Weiner 	/*
183810316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
183910316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
184010316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
184110316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
184210316b31SJohannes Weiner 	 * too expensive.
184310316b31SJohannes Weiner 	 */
184410316b31SJohannes Weiner 	if (!global_reclaim(sc) && !vmscan_swappiness(sc)) {
18459a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
184610316b31SJohannes Weiner 		goto out;
184710316b31SJohannes Weiner 	}
184810316b31SJohannes Weiner 
184910316b31SJohannes Weiner 	/*
185010316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
185110316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
185210316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
185310316b31SJohannes Weiner 	 */
185410316b31SJohannes Weiner 	if (!sc->priority && vmscan_swappiness(sc)) {
18559a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
185610316b31SJohannes Weiner 		goto out;
185710316b31SJohannes Weiner 	}
185810316b31SJohannes Weiner 
18594d7dcca2SHugh Dickins 	anon  = get_lru_size(lruvec, LRU_ACTIVE_ANON) +
18604d7dcca2SHugh Dickins 		get_lru_size(lruvec, LRU_INACTIVE_ANON);
18614d7dcca2SHugh Dickins 	file  = get_lru_size(lruvec, LRU_ACTIVE_FILE) +
18624d7dcca2SHugh Dickins 		get_lru_size(lruvec, LRU_INACTIVE_FILE);
1863a4d3e9e7SJohannes Weiner 
186411d16c25SJohannes Weiner 	/*
186511d16c25SJohannes Weiner 	 * If it's foreseeable that reclaiming the file cache won't be
186611d16c25SJohannes Weiner 	 * enough to get the zone back into a desirable shape, we have
186711d16c25SJohannes Weiner 	 * to swap.  Better start now and leave the - probably heavily
186811d16c25SJohannes Weiner 	 * thrashing - remaining file pages alone.
186911d16c25SJohannes Weiner 	 */
187089b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
187190126375SKonstantin Khlebnikov 		free = zone_page_state(zone, NR_FREE_PAGES);
187290126375SKonstantin Khlebnikov 		if (unlikely(file + free <= high_wmark_pages(zone))) {
18739a265114SJohannes Weiner 			scan_balance = SCAN_ANON;
187476a33fc3SShaohua Li 			goto out;
18757c5bd705SJohannes Weiner 		}
18767c5bd705SJohannes Weiner 	}
18777c5bd705SJohannes Weiner 
1878e9868505SRik van Riel 	/*
18797c5bd705SJohannes Weiner 	 * There is enough inactive page cache, do not reclaim
18807c5bd705SJohannes Weiner 	 * anything from the anonymous working set right now.
1881e9868505SRik van Riel 	 */
18827c5bd705SJohannes Weiner 	if (!inactive_file_is_low(lruvec)) {
18839a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
1884e9868505SRik van Riel 		goto out;
18854f98a2feSRik van Riel 	}
18864f98a2feSRik van Riel 
18879a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
18889a265114SJohannes Weiner 
18894f98a2feSRik van Riel 	/*
189058c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
189158c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
189258c37f6eSKOSAKI Motohiro 	 */
18933d58ab5cSKonstantin Khlebnikov 	anon_prio = vmscan_swappiness(sc);
189475b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
189558c37f6eSKOSAKI Motohiro 
189658c37f6eSKOSAKI Motohiro 	/*
18974f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
18984f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
18994f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
19004f98a2feSRik van Riel 	 *
19014f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
19024f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
19034f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
19044f98a2feSRik van Riel 	 *
19054f98a2feSRik van Riel 	 * anon in [0], file in [1]
19064f98a2feSRik van Riel 	 */
190790126375SKonstantin Khlebnikov 	spin_lock_irq(&zone->lru_lock);
190858c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
19096e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
19106e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
19114f98a2feSRik van Riel 	}
19124f98a2feSRik van Riel 
19136e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
19146e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
19156e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
19164f98a2feSRik van Riel 	}
19174f98a2feSRik van Riel 
19184f98a2feSRik van Riel 	/*
191900d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
192000d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
192100d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
19224f98a2feSRik van Riel 	 */
1923fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
19246e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
19254f98a2feSRik van Riel 
1926fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
19276e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
192890126375SKonstantin Khlebnikov 	spin_unlock_irq(&zone->lru_lock);
19294f98a2feSRik van Riel 
193076a33fc3SShaohua Li 	fraction[0] = ap;
193176a33fc3SShaohua Li 	fraction[1] = fp;
193276a33fc3SShaohua Li 	denominator = ap + fp + 1;
193376a33fc3SShaohua Li out:
19344111304dSHugh Dickins 	for_each_evictable_lru(lru) {
19354111304dSHugh Dickins 		int file = is_file_lru(lru);
1936d778df51SJohannes Weiner 		unsigned long size;
193776a33fc3SShaohua Li 		unsigned long scan;
193876a33fc3SShaohua Li 
1939d778df51SJohannes Weiner 		size = get_lru_size(lruvec, lru);
1940d778df51SJohannes Weiner 		scan = size >> sc->priority;
19419a265114SJohannes Weiner 
1942f11c0ca5SJohannes Weiner 		if (!scan && force_scan)
1943d778df51SJohannes Weiner 			scan = min(size, SWAP_CLUSTER_MAX);
19449a265114SJohannes Weiner 
19459a265114SJohannes Weiner 		switch (scan_balance) {
19469a265114SJohannes Weiner 		case SCAN_EQUAL:
19479a265114SJohannes Weiner 			/* Scan lists relative to size */
19489a265114SJohannes Weiner 			break;
19499a265114SJohannes Weiner 		case SCAN_FRACT:
19509a265114SJohannes Weiner 			/*
19519a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
19529a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
19539a265114SJohannes Weiner 			 */
195476a33fc3SShaohua Li 			scan = div64_u64(scan * fraction[file], denominator);
19559a265114SJohannes Weiner 			break;
19569a265114SJohannes Weiner 		case SCAN_FILE:
19579a265114SJohannes Weiner 		case SCAN_ANON:
19589a265114SJohannes Weiner 			/* Scan one type exclusively */
19599a265114SJohannes Weiner 			if ((scan_balance == SCAN_FILE) != file)
19609a265114SJohannes Weiner 				scan = 0;
19619a265114SJohannes Weiner 			break;
19629a265114SJohannes Weiner 		default:
19639a265114SJohannes Weiner 			/* Look ma, no brain */
19649a265114SJohannes Weiner 			BUG();
19659a265114SJohannes Weiner 		}
19664111304dSHugh Dickins 		nr[lru] = scan;
196776a33fc3SShaohua Li 	}
19686e08a369SWu Fengguang }
19694f98a2feSRik van Riel 
19709b4f98cdSJohannes Weiner /*
19719b4f98cdSJohannes Weiner  * This is a basic per-zone page freer.  Used by both kswapd and direct reclaim.
19729b4f98cdSJohannes Weiner  */
19739b4f98cdSJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
19749b4f98cdSJohannes Weiner {
19759b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
1976e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
19779b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
19789b4f98cdSJohannes Weiner 	enum lru_list lru;
19799b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
19809b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
19819b4f98cdSJohannes Weiner 	struct blk_plug plug;
1982e82e0561SMel Gorman 	bool scan_adjusted = false;
19839b4f98cdSJohannes Weiner 
19849b4f98cdSJohannes Weiner 	get_scan_count(lruvec, sc, nr);
19859b4f98cdSJohannes Weiner 
1986e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
1987e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
1988e82e0561SMel Gorman 
19899b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
19909b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
19919b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
1992e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
1993e82e0561SMel Gorman 		unsigned long nr_scanned;
1994e82e0561SMel Gorman 
19959b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
19969b4f98cdSJohannes Weiner 			if (nr[lru]) {
19979b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
19989b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
19999b4f98cdSJohannes Weiner 
20009b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
20019b4f98cdSJohannes Weiner 							    lruvec, sc);
20029b4f98cdSJohannes Weiner 			}
20039b4f98cdSJohannes Weiner 		}
2004e82e0561SMel Gorman 
2005e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2006e82e0561SMel Gorman 			continue;
2007e82e0561SMel Gorman 
20089b4f98cdSJohannes Weiner 		/*
2009e82e0561SMel Gorman 		 * For global direct reclaim, reclaim only the number of pages
2010e82e0561SMel Gorman 		 * requested. Less care is taken to scan proportionally as it
2011e82e0561SMel Gorman 		 * is more important to minimise direct reclaim stall latency
2012e82e0561SMel Gorman 		 * than it is to properly age the LRU lists.
20139b4f98cdSJohannes Weiner 		 */
2014e82e0561SMel Gorman 		if (global_reclaim(sc) && !current_is_kswapd())
20159b4f98cdSJohannes Weiner 			break;
2016e82e0561SMel Gorman 
2017e82e0561SMel Gorman 		/*
2018e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
2019e82e0561SMel Gorman 		 * requested. Ensure that the anon and file LRUs shrink
2020e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2021e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2022e82e0561SMel Gorman 		 * proportional to the original scan target.
2023e82e0561SMel Gorman 		 */
2024e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2025e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2026e82e0561SMel Gorman 
2027e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2028e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2029e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2030e82e0561SMel Gorman 			lru = LRU_BASE;
2031e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2032e82e0561SMel Gorman 		} else {
2033e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2034e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2035e82e0561SMel Gorman 			lru = LRU_FILE;
2036e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2037e82e0561SMel Gorman 		}
2038e82e0561SMel Gorman 
2039e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2040e82e0561SMel Gorman 		nr[lru] = 0;
2041e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2042e82e0561SMel Gorman 
2043e82e0561SMel Gorman 		/*
2044e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2045e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2046e82e0561SMel Gorman 		 */
2047e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2048e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2049e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2050e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2051e82e0561SMel Gorman 
2052e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2053e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2054e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2055e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2056e82e0561SMel Gorman 
2057e82e0561SMel Gorman 		scan_adjusted = true;
20589b4f98cdSJohannes Weiner 	}
20599b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
20609b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
20619b4f98cdSJohannes Weiner 
20629b4f98cdSJohannes Weiner 	/*
20639b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
20649b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
20659b4f98cdSJohannes Weiner 	 */
20669b4f98cdSJohannes Weiner 	if (inactive_anon_is_low(lruvec))
20679b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
20689b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
20699b4f98cdSJohannes Weiner 
20709b4f98cdSJohannes Weiner 	throttle_vm_writeout(sc->gfp_mask);
20719b4f98cdSJohannes Weiner }
20729b4f98cdSJohannes Weiner 
207323b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
20749e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
207523b9da55SMel Gorman {
2076d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
207723b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
20789e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
207923b9da55SMel Gorman 		return true;
208023b9da55SMel Gorman 
208123b9da55SMel Gorman 	return false;
208223b9da55SMel Gorman }
208323b9da55SMel Gorman 
20844f98a2feSRik van Riel /*
208523b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
208623b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
208723b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
208823b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
208923b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
20903e7d3449SMel Gorman  */
20919b4f98cdSJohannes Weiner static inline bool should_continue_reclaim(struct zone *zone,
20923e7d3449SMel Gorman 					unsigned long nr_reclaimed,
20933e7d3449SMel Gorman 					unsigned long nr_scanned,
20943e7d3449SMel Gorman 					struct scan_control *sc)
20953e7d3449SMel Gorman {
20963e7d3449SMel Gorman 	unsigned long pages_for_compaction;
20973e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
20983e7d3449SMel Gorman 
20993e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
21009e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
21013e7d3449SMel Gorman 		return false;
21023e7d3449SMel Gorman 
21032876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
21042876592fSMel Gorman 	if (sc->gfp_mask & __GFP_REPEAT) {
21053e7d3449SMel Gorman 		/*
21062876592fSMel Gorman 		 * For __GFP_REPEAT allocations, stop reclaiming if the
21072876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
21082876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
21092876592fSMel Gorman 		 * expensive but a __GFP_REPEAT caller really wants to succeed
21103e7d3449SMel Gorman 		 */
21113e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
21123e7d3449SMel Gorman 			return false;
21132876592fSMel Gorman 	} else {
21142876592fSMel Gorman 		/*
21152876592fSMel Gorman 		 * For non-__GFP_REPEAT allocations which can presumably
21162876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
21172876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
21182876592fSMel Gorman 		 * pages that were scanned. This will return to the
21192876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
21202876592fSMel Gorman 		 * the resulting allocation attempt fails
21212876592fSMel Gorman 		 */
21222876592fSMel Gorman 		if (!nr_reclaimed)
21232876592fSMel Gorman 			return false;
21242876592fSMel Gorman 	}
21253e7d3449SMel Gorman 
21263e7d3449SMel Gorman 	/*
21273e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
21283e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
21293e7d3449SMel Gorman 	 */
21303e7d3449SMel Gorman 	pages_for_compaction = (2UL << sc->order);
21319b4f98cdSJohannes Weiner 	inactive_lru_pages = zone_page_state(zone, NR_INACTIVE_FILE);
2132ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
21339b4f98cdSJohannes Weiner 		inactive_lru_pages += zone_page_state(zone, NR_INACTIVE_ANON);
21343e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
21353e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
21363e7d3449SMel Gorman 		return true;
21373e7d3449SMel Gorman 
21383e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
21399b4f98cdSJohannes Weiner 	switch (compaction_suitable(zone, sc->order)) {
21403e7d3449SMel Gorman 	case COMPACT_PARTIAL:
21413e7d3449SMel Gorman 	case COMPACT_CONTINUE:
21423e7d3449SMel Gorman 		return false;
21433e7d3449SMel Gorman 	default:
21443e7d3449SMel Gorman 		return true;
21453e7d3449SMel Gorman 	}
21463e7d3449SMel Gorman }
21473e7d3449SMel Gorman 
21489e3b2f8cSKonstantin Khlebnikov static void shrink_zone(struct zone *zone, struct scan_control *sc)
2149f16015fbSJohannes Weiner {
21509b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
21519b4f98cdSJohannes Weiner 
21529b4f98cdSJohannes Weiner 	do {
21535660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
21545660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
21555660048cSJohannes Weiner 			.zone = zone,
21569e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
21575660048cSJohannes Weiner 		};
21585660048cSJohannes Weiner 		struct mem_cgroup *memcg;
21595660048cSJohannes Weiner 
21609b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
21619b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
21629b4f98cdSJohannes Weiner 
21635660048cSJohannes Weiner 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
21645660048cSJohannes Weiner 		do {
21659b4f98cdSJohannes Weiner 			struct lruvec *lruvec;
21669b4f98cdSJohannes Weiner 
21679b4f98cdSJohannes Weiner 			lruvec = mem_cgroup_zone_lruvec(zone, memcg);
21685660048cSJohannes Weiner 
2169f9be23d6SKonstantin Khlebnikov 			shrink_lruvec(lruvec, sc);
2170f9be23d6SKonstantin Khlebnikov 
21715660048cSJohannes Weiner 			/*
2172a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2173a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
21749b4f98cdSJohannes Weiner 			 * zone.
2175a394cb8eSMichal Hocko 			 *
2176a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2177a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2178a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2179a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
21805660048cSJohannes Weiner 			 */
2181a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2182a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
21835660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
21845660048cSJohannes Weiner 				break;
21855660048cSJohannes Weiner 			}
21865660048cSJohannes Weiner 			memcg = mem_cgroup_iter(root, memcg, &reclaim);
21875660048cSJohannes Weiner 		} while (memcg);
218870ddf637SAnton Vorontsov 
218970ddf637SAnton Vorontsov 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup,
219070ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
219170ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
219270ddf637SAnton Vorontsov 
21939b4f98cdSJohannes Weiner 	} while (should_continue_reclaim(zone, sc->nr_reclaimed - nr_reclaimed,
21949b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
2195f16015fbSJohannes Weiner }
2196f16015fbSJohannes Weiner 
2197fe4b1b24SMel Gorman /* Returns true if compaction should go ahead for a high-order request */
2198fe4b1b24SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2199fe4b1b24SMel Gorman {
2200fe4b1b24SMel Gorman 	unsigned long balance_gap, watermark;
2201fe4b1b24SMel Gorman 	bool watermark_ok;
2202fe4b1b24SMel Gorman 
2203fe4b1b24SMel Gorman 	/* Do not consider compaction for orders reclaim is meant to satisfy */
2204fe4b1b24SMel Gorman 	if (sc->order <= PAGE_ALLOC_COSTLY_ORDER)
2205fe4b1b24SMel Gorman 		return false;
2206fe4b1b24SMel Gorman 
2207fe4b1b24SMel Gorman 	/*
2208fe4b1b24SMel Gorman 	 * Compaction takes time to run and there are potentially other
2209fe4b1b24SMel Gorman 	 * callers using the pages just freed. Continue reclaiming until
2210fe4b1b24SMel Gorman 	 * there is a buffer of free pages available to give compaction
2211fe4b1b24SMel Gorman 	 * a reasonable chance of completing and allocating the page
2212fe4b1b24SMel Gorman 	 */
2213fe4b1b24SMel Gorman 	balance_gap = min(low_wmark_pages(zone),
2214b40da049SJiang Liu 		(zone->managed_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
2215fe4b1b24SMel Gorman 			KSWAPD_ZONE_BALANCE_GAP_RATIO);
2216fe4b1b24SMel Gorman 	watermark = high_wmark_pages(zone) + balance_gap + (2UL << sc->order);
2217fe4b1b24SMel Gorman 	watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, 0, 0);
2218fe4b1b24SMel Gorman 
2219fe4b1b24SMel Gorman 	/*
2220fe4b1b24SMel Gorman 	 * If compaction is deferred, reclaim up to a point where
2221fe4b1b24SMel Gorman 	 * compaction will have a chance of success when re-enabled
2222fe4b1b24SMel Gorman 	 */
2223aff62249SRik van Riel 	if (compaction_deferred(zone, sc->order))
2224fe4b1b24SMel Gorman 		return watermark_ok;
2225fe4b1b24SMel Gorman 
2226fe4b1b24SMel Gorman 	/* If compaction is not ready to start, keep reclaiming */
2227fe4b1b24SMel Gorman 	if (!compaction_suitable(zone, sc->order))
2228fe4b1b24SMel Gorman 		return false;
2229fe4b1b24SMel Gorman 
2230fe4b1b24SMel Gorman 	return watermark_ok;
2231fe4b1b24SMel Gorman }
2232fe4b1b24SMel Gorman 
22331da177e4SLinus Torvalds /*
22341da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
22351da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
22361da177e4SLinus Torvalds  * request.
22371da177e4SLinus Torvalds  *
223841858966SMel Gorman  * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
223941858966SMel Gorman  * Because:
22401da177e4SLinus Torvalds  * a) The caller may be trying to free *extra* pages to satisfy a higher-order
22411da177e4SLinus Torvalds  *    allocation or
224241858966SMel Gorman  * b) The target zone may be at high_wmark_pages(zone) but the lower zones
224341858966SMel Gorman  *    must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
224441858966SMel Gorman  *    zone defense algorithm.
22451da177e4SLinus Torvalds  *
22461da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
22471da177e4SLinus Torvalds  * scan then give up on it.
2248e0c23279SMel Gorman  *
2249e0c23279SMel Gorman  * This function returns true if a zone is being reclaimed for a costly
2250fe4b1b24SMel Gorman  * high-order allocation and compaction is ready to begin. This indicates to
22510cee34fdSMel Gorman  * the caller that it should consider retrying the allocation instead of
22520cee34fdSMel Gorman  * further reclaim.
22531da177e4SLinus Torvalds  */
22549e3b2f8cSKonstantin Khlebnikov static bool shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
22551da177e4SLinus Torvalds {
2256dd1a239fSMel Gorman 	struct zoneref *z;
225754a6eb5cSMel Gorman 	struct zone *zone;
2258d149e3b2SYing Han 	unsigned long nr_soft_reclaimed;
2259d149e3b2SYing Han 	unsigned long nr_soft_scanned;
22600cee34fdSMel Gorman 	bool aborted_reclaim = false;
22611cfb419bSKAMEZAWA Hiroyuki 
2262cc715d99SMel Gorman 	/*
2263cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2264cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2265cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2266cc715d99SMel Gorman 	 */
2267cc715d99SMel Gorman 	if (buffer_heads_over_limit)
2268cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
2269cc715d99SMel Gorman 
2270d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2271d4debc66SMel Gorman 					gfp_zone(sc->gfp_mask), sc->nodemask) {
2272f3fe6512SCon Kolivas 		if (!populated_zone(zone))
22731da177e4SLinus Torvalds 			continue;
22741cfb419bSKAMEZAWA Hiroyuki 		/*
22751cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
22761cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
22771cfb419bSKAMEZAWA Hiroyuki 		 */
227889b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
227902a0e53dSPaul Jackson 			if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
22801da177e4SLinus Torvalds 				continue;
22819e3b2f8cSKonstantin Khlebnikov 			if (zone->all_unreclaimable &&
22829e3b2f8cSKonstantin Khlebnikov 					sc->priority != DEF_PRIORITY)
22831da177e4SLinus Torvalds 				continue;	/* Let kswapd poll it */
2284d84da3f9SKirill A. Shutemov 			if (IS_ENABLED(CONFIG_COMPACTION)) {
2285e0887c19SRik van Riel 				/*
2286e0c23279SMel Gorman 				 * If we already have plenty of memory free for
2287e0c23279SMel Gorman 				 * compaction in this zone, don't free any more.
2288e0c23279SMel Gorman 				 * Even though compaction is invoked for any
2289e0c23279SMel Gorman 				 * non-zero order, only frequent costly order
2290e0c23279SMel Gorman 				 * reclamation is disruptive enough to become a
2291c7cfa37bSCopot Alexandru 				 * noticeable problem, like transparent huge
2292c7cfa37bSCopot Alexandru 				 * page allocations.
2293e0887c19SRik van Riel 				 */
2294fe4b1b24SMel Gorman 				if (compaction_ready(zone, sc)) {
22950cee34fdSMel Gorman 					aborted_reclaim = true;
2296e0887c19SRik van Riel 					continue;
2297e0887c19SRik van Riel 				}
2298e0c23279SMel Gorman 			}
2299ac34a1a3SKAMEZAWA Hiroyuki 			/*
2300ac34a1a3SKAMEZAWA Hiroyuki 			 * This steals pages from memory cgroups over softlimit
2301ac34a1a3SKAMEZAWA Hiroyuki 			 * and returns the number of reclaimed pages and
2302ac34a1a3SKAMEZAWA Hiroyuki 			 * scanned pages. This works for global memory pressure
2303ac34a1a3SKAMEZAWA Hiroyuki 			 * and balancing, not for a memcg's limit.
2304ac34a1a3SKAMEZAWA Hiroyuki 			 */
2305d149e3b2SYing Han 			nr_soft_scanned = 0;
2306d149e3b2SYing Han 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
2307d149e3b2SYing Han 						sc->order, sc->gfp_mask,
2308d149e3b2SYing Han 						&nr_soft_scanned);
2309d149e3b2SYing Han 			sc->nr_reclaimed += nr_soft_reclaimed;
2310ac34a1a3SKAMEZAWA Hiroyuki 			sc->nr_scanned += nr_soft_scanned;
2311ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2312ac34a1a3SKAMEZAWA Hiroyuki 		}
2313d149e3b2SYing Han 
23149e3b2f8cSKonstantin Khlebnikov 		shrink_zone(zone, sc);
23151da177e4SLinus Torvalds 	}
2316e0c23279SMel Gorman 
23170cee34fdSMel Gorman 	return aborted_reclaim;
2318d1908362SMinchan Kim }
2319d1908362SMinchan Kim 
2320d1908362SMinchan Kim static bool zone_reclaimable(struct zone *zone)
2321d1908362SMinchan Kim {
2322d1908362SMinchan Kim 	return zone->pages_scanned < zone_reclaimable_pages(zone) * 6;
2323d1908362SMinchan Kim }
2324d1908362SMinchan Kim 
2325929bea7cSKOSAKI Motohiro /* All zones in zonelist are unreclaimable? */
2326d1908362SMinchan Kim static bool all_unreclaimable(struct zonelist *zonelist,
2327d1908362SMinchan Kim 		struct scan_control *sc)
2328d1908362SMinchan Kim {
2329d1908362SMinchan Kim 	struct zoneref *z;
2330d1908362SMinchan Kim 	struct zone *zone;
2331d1908362SMinchan Kim 
2332d1908362SMinchan Kim 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2333d1908362SMinchan Kim 			gfp_zone(sc->gfp_mask), sc->nodemask) {
2334d1908362SMinchan Kim 		if (!populated_zone(zone))
2335d1908362SMinchan Kim 			continue;
2336d1908362SMinchan Kim 		if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2337d1908362SMinchan Kim 			continue;
2338929bea7cSKOSAKI Motohiro 		if (!zone->all_unreclaimable)
2339929bea7cSKOSAKI Motohiro 			return false;
2340d1908362SMinchan Kim 	}
2341d1908362SMinchan Kim 
2342929bea7cSKOSAKI Motohiro 	return true;
23431da177e4SLinus Torvalds }
23441da177e4SLinus Torvalds 
23451da177e4SLinus Torvalds /*
23461da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
23471da177e4SLinus Torvalds  *
23481da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
23491da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
23501da177e4SLinus Torvalds  *
23511da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
23521da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
23535b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
23545b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
23555b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
23565b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2357a41f24eaSNishanth Aravamudan  *
2358a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2359a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
23601da177e4SLinus Torvalds  */
2361dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
2362a09ed5e0SYing Han 					struct scan_control *sc,
2363a09ed5e0SYing Han 					struct shrink_control *shrink)
23641da177e4SLinus Torvalds {
236569e05944SAndrew Morton 	unsigned long total_scanned = 0;
23661da177e4SLinus Torvalds 	struct reclaim_state *reclaim_state = current->reclaim_state;
2367dd1a239fSMel Gorman 	struct zoneref *z;
236854a6eb5cSMel Gorman 	struct zone *zone;
236922fba335SKOSAKI Motohiro 	unsigned long writeback_threshold;
23700cee34fdSMel Gorman 	bool aborted_reclaim;
23711da177e4SLinus Torvalds 
2372873b4771SKeika Kobayashi 	delayacct_freepages_start();
2373873b4771SKeika Kobayashi 
237489b5fae5SJohannes Weiner 	if (global_reclaim(sc))
2375f8891e5eSChristoph Lameter 		count_vm_event(ALLOCSTALL);
23761da177e4SLinus Torvalds 
23779e3b2f8cSKonstantin Khlebnikov 	do {
237870ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
237970ddf637SAnton Vorontsov 				sc->priority);
238066e1707bSBalbir Singh 		sc->nr_scanned = 0;
23819e3b2f8cSKonstantin Khlebnikov 		aborted_reclaim = shrink_zones(zonelist, sc);
2382e0c23279SMel Gorman 
238366e1707bSBalbir Singh 		/*
23845a1c9cbcSMel Gorman 		 * Don't shrink slabs when reclaiming memory from over limit
23855a1c9cbcSMel Gorman 		 * cgroups but do shrink slab at least once when aborting
23865a1c9cbcSMel Gorman 		 * reclaim for compaction to avoid unevenly scanning file/anon
23875a1c9cbcSMel Gorman 		 * LRU pages over slab pages.
238866e1707bSBalbir Singh 		 */
238989b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2390c6a8a8c5SKOSAKI Motohiro 			unsigned long lru_pages = 0;
23910ce3d744SDave Chinner 
23920ce3d744SDave Chinner 			nodes_clear(shrink->nodes_to_scan);
2393d4debc66SMel Gorman 			for_each_zone_zonelist(zone, z, zonelist,
2394d4debc66SMel Gorman 					gfp_zone(sc->gfp_mask)) {
2395c6a8a8c5SKOSAKI Motohiro 				if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2396c6a8a8c5SKOSAKI Motohiro 					continue;
2397c6a8a8c5SKOSAKI Motohiro 
2398c6a8a8c5SKOSAKI Motohiro 				lru_pages += zone_reclaimable_pages(zone);
23990ce3d744SDave Chinner 				node_set(zone_to_nid(zone),
24000ce3d744SDave Chinner 					 shrink->nodes_to_scan);
2401c6a8a8c5SKOSAKI Motohiro 			}
2402c6a8a8c5SKOSAKI Motohiro 
24031495f230SYing Han 			shrink_slab(shrink, sc->nr_scanned, lru_pages);
24041da177e4SLinus Torvalds 			if (reclaim_state) {
2405a79311c1SRik van Riel 				sc->nr_reclaimed += reclaim_state->reclaimed_slab;
24061da177e4SLinus Torvalds 				reclaim_state->reclaimed_slab = 0;
24071da177e4SLinus Torvalds 			}
240891a45470SKAMEZAWA Hiroyuki 		}
240966e1707bSBalbir Singh 		total_scanned += sc->nr_scanned;
2410bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
24111da177e4SLinus Torvalds 			goto out;
24121da177e4SLinus Torvalds 
24131da177e4SLinus Torvalds 		/*
24140e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
24150e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
24160e50ce3bSMinchan Kim 		 */
24170e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
24180e50ce3bSMinchan Kim 			sc->may_writepage = 1;
24190e50ce3bSMinchan Kim 
24200e50ce3bSMinchan Kim 		/*
24211da177e4SLinus Torvalds 		 * Try to write back as many pages as we just scanned.  This
24221da177e4SLinus Torvalds 		 * tends to cause slow streaming writers to write data to the
24231da177e4SLinus Torvalds 		 * disk smoothly, at the dirtying rate, which is nice.   But
24241da177e4SLinus Torvalds 		 * that's undesirable in laptop mode, where we *want* lumpy
24251da177e4SLinus Torvalds 		 * writeout.  So in laptop mode, write out the whole world.
24261da177e4SLinus Torvalds 		 */
242722fba335SKOSAKI Motohiro 		writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
242822fba335SKOSAKI Motohiro 		if (total_scanned > writeback_threshold) {
24290e175a18SCurt Wohlgemuth 			wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
24300e175a18SCurt Wohlgemuth 						WB_REASON_TRY_TO_FREE_PAGES);
243166e1707bSBalbir Singh 			sc->may_writepage = 1;
24321da177e4SLinus Torvalds 		}
24335a1c9cbcSMel Gorman 	} while (--sc->priority >= 0 && !aborted_reclaim);
2434bb21c7ceSKOSAKI Motohiro 
24351da177e4SLinus Torvalds out:
2436873b4771SKeika Kobayashi 	delayacct_freepages_end();
2437873b4771SKeika Kobayashi 
2438bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2439bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2440bb21c7ceSKOSAKI Motohiro 
2441929bea7cSKOSAKI Motohiro 	/*
2442929bea7cSKOSAKI Motohiro 	 * As hibernation is going on, kswapd is freezed so that it can't mark
2443929bea7cSKOSAKI Motohiro 	 * the zone into all_unreclaimable. Thus bypassing all_unreclaimable
2444929bea7cSKOSAKI Motohiro 	 * check.
2445929bea7cSKOSAKI Motohiro 	 */
2446929bea7cSKOSAKI Motohiro 	if (oom_killer_disabled)
2447929bea7cSKOSAKI Motohiro 		return 0;
2448929bea7cSKOSAKI Motohiro 
24490cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
24500cee34fdSMel Gorman 	if (aborted_reclaim)
24517335084dSMel Gorman 		return 1;
24527335084dSMel Gorman 
2453bb21c7ceSKOSAKI Motohiro 	/* top priority shrink_zones still had more to do? don't OOM, then */
245489b5fae5SJohannes Weiner 	if (global_reclaim(sc) && !all_unreclaimable(zonelist, sc))
2455bb21c7ceSKOSAKI Motohiro 		return 1;
2456bb21c7ceSKOSAKI Motohiro 
2457bb21c7ceSKOSAKI Motohiro 	return 0;
24581da177e4SLinus Torvalds }
24591da177e4SLinus Torvalds 
24605515061dSMel Gorman static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
24615515061dSMel Gorman {
24625515061dSMel Gorman 	struct zone *zone;
24635515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
24645515061dSMel Gorman 	unsigned long free_pages = 0;
24655515061dSMel Gorman 	int i;
24665515061dSMel Gorman 	bool wmark_ok;
24675515061dSMel Gorman 
24685515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
24695515061dSMel Gorman 		zone = &pgdat->node_zones[i];
24705515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
24715515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
24725515061dSMel Gorman 	}
24735515061dSMel Gorman 
24745515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
24755515061dSMel Gorman 
24765515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
24775515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
24785515061dSMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx,
24795515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
24805515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
24815515061dSMel Gorman 	}
24825515061dSMel Gorman 
24835515061dSMel Gorman 	return wmark_ok;
24845515061dSMel Gorman }
24855515061dSMel Gorman 
24865515061dSMel Gorman /*
24875515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
24885515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
24895515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
249050694c28SMel Gorman  * when the low watermark is reached.
249150694c28SMel Gorman  *
249250694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
249350694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
24945515061dSMel Gorman  */
249550694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
24965515061dSMel Gorman 					nodemask_t *nodemask)
24975515061dSMel Gorman {
24985515061dSMel Gorman 	struct zone *zone;
24995515061dSMel Gorman 	int high_zoneidx = gfp_zone(gfp_mask);
25005515061dSMel Gorman 	pg_data_t *pgdat;
25015515061dSMel Gorman 
25025515061dSMel Gorman 	/*
25035515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
25045515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
25055515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
25065515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
25075515061dSMel Gorman 	 * processes to block on log_wait_commit().
25085515061dSMel Gorman 	 */
25095515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
251050694c28SMel Gorman 		goto out;
251150694c28SMel Gorman 
251250694c28SMel Gorman 	/*
251350694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
251450694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
251550694c28SMel Gorman 	 */
251650694c28SMel Gorman 	if (fatal_signal_pending(current))
251750694c28SMel Gorman 		goto out;
25185515061dSMel Gorman 
25195515061dSMel Gorman 	/* Check if the pfmemalloc reserves are ok */
25205515061dSMel Gorman 	first_zones_zonelist(zonelist, high_zoneidx, NULL, &zone);
25215515061dSMel Gorman 	pgdat = zone->zone_pgdat;
25225515061dSMel Gorman 	if (pfmemalloc_watermark_ok(pgdat))
252350694c28SMel Gorman 		goto out;
25245515061dSMel Gorman 
252568243e76SMel Gorman 	/* Account for the throttling */
252668243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
252768243e76SMel Gorman 
25285515061dSMel Gorman 	/*
25295515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
25305515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
25315515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
25325515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
25335515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
25345515061dSMel Gorman 	 * second before continuing.
25355515061dSMel Gorman 	 */
25365515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
25375515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
25385515061dSMel Gorman 			pfmemalloc_watermark_ok(pgdat), HZ);
253950694c28SMel Gorman 
254050694c28SMel Gorman 		goto check_pending;
25415515061dSMel Gorman 	}
25425515061dSMel Gorman 
25435515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
25445515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
25455515061dSMel Gorman 		pfmemalloc_watermark_ok(pgdat));
254650694c28SMel Gorman 
254750694c28SMel Gorman check_pending:
254850694c28SMel Gorman 	if (fatal_signal_pending(current))
254950694c28SMel Gorman 		return true;
255050694c28SMel Gorman 
255150694c28SMel Gorman out:
255250694c28SMel Gorman 	return false;
25535515061dSMel Gorman }
25545515061dSMel Gorman 
2555dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2556327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
255766e1707bSBalbir Singh {
255833906bc5SMel Gorman 	unsigned long nr_reclaimed;
255966e1707bSBalbir Singh 	struct scan_control sc = {
256021caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
256166e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
256222fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2563a6dc60f8SJohannes Weiner 		.may_unmap = 1,
25642e2e4259SKOSAKI Motohiro 		.may_swap = 1,
256566e1707bSBalbir Singh 		.order = order,
25669e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
2567f16015fbSJohannes Weiner 		.target_mem_cgroup = NULL,
2568327c0e96SKAMEZAWA Hiroyuki 		.nodemask = nodemask,
256966e1707bSBalbir Singh 	};
2570a09ed5e0SYing Han 	struct shrink_control shrink = {
2571a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
2572a09ed5e0SYing Han 	};
257366e1707bSBalbir Singh 
25745515061dSMel Gorman 	/*
257550694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
257650694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
257750694c28SMel Gorman 	 * point.
25785515061dSMel Gorman 	 */
257950694c28SMel Gorman 	if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
25805515061dSMel Gorman 		return 1;
25815515061dSMel Gorman 
258233906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
258333906bc5SMel Gorman 				sc.may_writepage,
258433906bc5SMel Gorman 				gfp_mask);
258533906bc5SMel Gorman 
2586a09ed5e0SYing Han 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
258733906bc5SMel Gorman 
258833906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
258933906bc5SMel Gorman 
259033906bc5SMel Gorman 	return nr_reclaimed;
259166e1707bSBalbir Singh }
259266e1707bSBalbir Singh 
2593c255a458SAndrew Morton #ifdef CONFIG_MEMCG
259466e1707bSBalbir Singh 
259572835c86SJohannes Weiner unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg,
25964e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
25970ae5e89cSYing Han 						struct zone *zone,
25980ae5e89cSYing Han 						unsigned long *nr_scanned)
25994e416953SBalbir Singh {
26004e416953SBalbir Singh 	struct scan_control sc = {
26010ae5e89cSYing Han 		.nr_scanned = 0,
2602b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
26034e416953SBalbir Singh 		.may_writepage = !laptop_mode,
26044e416953SBalbir Singh 		.may_unmap = 1,
26054e416953SBalbir Singh 		.may_swap = !noswap,
26064e416953SBalbir Singh 		.order = 0,
26079e3b2f8cSKonstantin Khlebnikov 		.priority = 0,
260872835c86SJohannes Weiner 		.target_mem_cgroup = memcg,
26094e416953SBalbir Singh 	};
2610f9be23d6SKonstantin Khlebnikov 	struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
26110ae5e89cSYing Han 
26124e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
26134e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2614bdce6d9eSKOSAKI Motohiro 
26159e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
2616bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
2617bdce6d9eSKOSAKI Motohiro 						      sc.gfp_mask);
2618bdce6d9eSKOSAKI Motohiro 
26194e416953SBalbir Singh 	/*
26204e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
26214e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
26224e416953SBalbir Singh 	 * if we don't reclaim here, the shrink_zone from balance_pgdat
26234e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
26244e416953SBalbir Singh 	 * the priority and make it zero.
26254e416953SBalbir Singh 	 */
2626f9be23d6SKonstantin Khlebnikov 	shrink_lruvec(lruvec, &sc);
2627bdce6d9eSKOSAKI Motohiro 
2628bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
2629bdce6d9eSKOSAKI Motohiro 
26300ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
26314e416953SBalbir Singh 	return sc.nr_reclaimed;
26324e416953SBalbir Singh }
26334e416953SBalbir Singh 
263472835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
26358c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
2636185efc0fSJohannes Weiner 					   bool noswap)
263766e1707bSBalbir Singh {
26384e416953SBalbir Singh 	struct zonelist *zonelist;
2639bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
2640889976dbSYing Han 	int nid;
264166e1707bSBalbir Singh 	struct scan_control sc = {
264266e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
2643a6dc60f8SJohannes Weiner 		.may_unmap = 1,
26442e2e4259SKOSAKI Motohiro 		.may_swap = !noswap,
264522fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
264666e1707bSBalbir Singh 		.order = 0,
26479e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
264872835c86SJohannes Weiner 		.target_mem_cgroup = memcg,
2649327c0e96SKAMEZAWA Hiroyuki 		.nodemask = NULL, /* we don't care the placement */
2650a09ed5e0SYing Han 		.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2651a09ed5e0SYing Han 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
2652a09ed5e0SYing Han 	};
2653a09ed5e0SYing Han 	struct shrink_control shrink = {
2654a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
265566e1707bSBalbir Singh 	};
265666e1707bSBalbir Singh 
2657889976dbSYing Han 	/*
2658889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
2659889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
2660889976dbSYing Han 	 * scan does not need to be the current node.
2661889976dbSYing Han 	 */
266272835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
2663889976dbSYing Han 
2664889976dbSYing Han 	zonelist = NODE_DATA(nid)->node_zonelists;
2665bdce6d9eSKOSAKI Motohiro 
2666bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
2667bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
2668bdce6d9eSKOSAKI Motohiro 					    sc.gfp_mask);
2669bdce6d9eSKOSAKI Motohiro 
2670a09ed5e0SYing Han 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
2671bdce6d9eSKOSAKI Motohiro 
2672bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
2673bdce6d9eSKOSAKI Motohiro 
2674bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
267566e1707bSBalbir Singh }
267666e1707bSBalbir Singh #endif
267766e1707bSBalbir Singh 
26789e3b2f8cSKonstantin Khlebnikov static void age_active_anon(struct zone *zone, struct scan_control *sc)
2679f16015fbSJohannes Weiner {
2680b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
2681b95a2f2dSJohannes Weiner 
2682b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
2683b95a2f2dSJohannes Weiner 		return;
2684b95a2f2dSJohannes Weiner 
2685b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
2686b95a2f2dSJohannes Weiner 	do {
2687c56d5c7dSKonstantin Khlebnikov 		struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
2688f16015fbSJohannes Weiner 
2689c56d5c7dSKonstantin Khlebnikov 		if (inactive_anon_is_low(lruvec))
26901a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
26919e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
2692b95a2f2dSJohannes Weiner 
2693b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
2694b95a2f2dSJohannes Weiner 	} while (memcg);
2695f16015fbSJohannes Weiner }
2696f16015fbSJohannes Weiner 
269760cefed4SJohannes Weiner static bool zone_balanced(struct zone *zone, int order,
269860cefed4SJohannes Weiner 			  unsigned long balance_gap, int classzone_idx)
269960cefed4SJohannes Weiner {
270060cefed4SJohannes Weiner 	if (!zone_watermark_ok_safe(zone, order, high_wmark_pages(zone) +
270160cefed4SJohannes Weiner 				    balance_gap, classzone_idx, 0))
270260cefed4SJohannes Weiner 		return false;
270360cefed4SJohannes Weiner 
2704d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && order &&
2705d84da3f9SKirill A. Shutemov 	    !compaction_suitable(zone, order))
270660cefed4SJohannes Weiner 		return false;
270760cefed4SJohannes Weiner 
270860cefed4SJohannes Weiner 	return true;
270960cefed4SJohannes Weiner }
271060cefed4SJohannes Weiner 
27111741c877SMel Gorman /*
27124ae0a48bSZlatko Calusic  * pgdat_balanced() is used when checking if a node is balanced.
27134ae0a48bSZlatko Calusic  *
27144ae0a48bSZlatko Calusic  * For order-0, all zones must be balanced!
27154ae0a48bSZlatko Calusic  *
27164ae0a48bSZlatko Calusic  * For high-order allocations only zones that meet watermarks and are in a
27174ae0a48bSZlatko Calusic  * zone allowed by the callers classzone_idx are added to balanced_pages. The
27184ae0a48bSZlatko Calusic  * total of balanced pages must be at least 25% of the zones allowed by
27194ae0a48bSZlatko Calusic  * classzone_idx for the node to be considered balanced. Forcing all zones to
27204ae0a48bSZlatko Calusic  * be balanced for high orders can cause excessive reclaim when there are
27214ae0a48bSZlatko Calusic  * imbalanced zones.
27221741c877SMel Gorman  * The choice of 25% is due to
27231741c877SMel Gorman  *   o a 16M DMA zone that is balanced will not balance a zone on any
27241741c877SMel Gorman  *     reasonable sized machine
27251741c877SMel Gorman  *   o On all other machines, the top zone must be at least a reasonable
272625985edcSLucas De Marchi  *     percentage of the middle zones. For example, on 32-bit x86, highmem
27271741c877SMel Gorman  *     would need to be at least 256M for it to be balance a whole node.
27281741c877SMel Gorman  *     Similarly, on x86-64 the Normal zone would need to be at least 1G
27291741c877SMel Gorman  *     to balance a node on its own. These seemed like reasonable ratios.
27301741c877SMel Gorman  */
27314ae0a48bSZlatko Calusic static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
27321741c877SMel Gorman {
2733b40da049SJiang Liu 	unsigned long managed_pages = 0;
27344ae0a48bSZlatko Calusic 	unsigned long balanced_pages = 0;
27351741c877SMel Gorman 	int i;
27361741c877SMel Gorman 
27374ae0a48bSZlatko Calusic 	/* Check the watermark levels */
27384ae0a48bSZlatko Calusic 	for (i = 0; i <= classzone_idx; i++) {
27394ae0a48bSZlatko Calusic 		struct zone *zone = pgdat->node_zones + i;
27401741c877SMel Gorman 
27414ae0a48bSZlatko Calusic 		if (!populated_zone(zone))
27424ae0a48bSZlatko Calusic 			continue;
27434ae0a48bSZlatko Calusic 
2744b40da049SJiang Liu 		managed_pages += zone->managed_pages;
27454ae0a48bSZlatko Calusic 
27464ae0a48bSZlatko Calusic 		/*
27474ae0a48bSZlatko Calusic 		 * A special case here:
27484ae0a48bSZlatko Calusic 		 *
27494ae0a48bSZlatko Calusic 		 * balance_pgdat() skips over all_unreclaimable after
27504ae0a48bSZlatko Calusic 		 * DEF_PRIORITY. Effectively, it considers them balanced so
27514ae0a48bSZlatko Calusic 		 * they must be considered balanced here as well!
27524ae0a48bSZlatko Calusic 		 */
27534ae0a48bSZlatko Calusic 		if (zone->all_unreclaimable) {
2754b40da049SJiang Liu 			balanced_pages += zone->managed_pages;
27554ae0a48bSZlatko Calusic 			continue;
27564ae0a48bSZlatko Calusic 		}
27574ae0a48bSZlatko Calusic 
27584ae0a48bSZlatko Calusic 		if (zone_balanced(zone, order, 0, i))
2759b40da049SJiang Liu 			balanced_pages += zone->managed_pages;
27604ae0a48bSZlatko Calusic 		else if (!order)
27614ae0a48bSZlatko Calusic 			return false;
27624ae0a48bSZlatko Calusic 	}
27634ae0a48bSZlatko Calusic 
27644ae0a48bSZlatko Calusic 	if (order)
2765b40da049SJiang Liu 		return balanced_pages >= (managed_pages >> 2);
27664ae0a48bSZlatko Calusic 	else
27674ae0a48bSZlatko Calusic 		return true;
27681741c877SMel Gorman }
27691741c877SMel Gorman 
27705515061dSMel Gorman /*
27715515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
27725515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
27735515061dSMel Gorman  *
27745515061dSMel Gorman  * Returns true if kswapd is ready to sleep
27755515061dSMel Gorman  */
27765515061dSMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, long remaining,
2777dc83edd9SMel Gorman 					int classzone_idx)
2778f50de2d3SMel Gorman {
2779f50de2d3SMel Gorman 	/* If a direct reclaimer woke kswapd within HZ/10, it's premature */
2780f50de2d3SMel Gorman 	if (remaining)
27815515061dSMel Gorman 		return false;
27825515061dSMel Gorman 
27835515061dSMel Gorman 	/*
27845515061dSMel Gorman 	 * There is a potential race between when kswapd checks its watermarks
27855515061dSMel Gorman 	 * and a process gets throttled. There is also a potential race if
27865515061dSMel Gorman 	 * processes get throttled, kswapd wakes, a large process exits therby
27875515061dSMel Gorman 	 * balancing the zones that causes kswapd to miss a wakeup. If kswapd
27885515061dSMel Gorman 	 * is going to sleep, no process should be sleeping on pfmemalloc_wait
27895515061dSMel Gorman 	 * so wake them now if necessary. If necessary, processes will wake
27905515061dSMel Gorman 	 * kswapd and get throttled again
27915515061dSMel Gorman 	 */
27925515061dSMel Gorman 	if (waitqueue_active(&pgdat->pfmemalloc_wait)) {
27935515061dSMel Gorman 		wake_up(&pgdat->pfmemalloc_wait);
27945515061dSMel Gorman 		return false;
27955515061dSMel Gorman 	}
2796f50de2d3SMel Gorman 
27974ae0a48bSZlatko Calusic 	return pgdat_balanced(pgdat, order, classzone_idx);
2798f50de2d3SMel Gorman }
2799f50de2d3SMel Gorman 
28001da177e4SLinus Torvalds /*
280175485363SMel Gorman  * kswapd shrinks the zone by the number of pages required to reach
280275485363SMel Gorman  * the high watermark.
2803b8e83b94SMel Gorman  *
2804b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
2805283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
2806283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
280775485363SMel Gorman  */
2808b8e83b94SMel Gorman static bool kswapd_shrink_zone(struct zone *zone,
28097c954f6dSMel Gorman 			       int classzone_idx,
281075485363SMel Gorman 			       struct scan_control *sc,
28112ab44f43SMel Gorman 			       unsigned long lru_pages,
28122ab44f43SMel Gorman 			       unsigned long *nr_attempted)
281375485363SMel Gorman {
281475485363SMel Gorman 	unsigned long nr_slab;
28157c954f6dSMel Gorman 	int testorder = sc->order;
28167c954f6dSMel Gorman 	unsigned long balance_gap;
281775485363SMel Gorman 	struct reclaim_state *reclaim_state = current->reclaim_state;
281875485363SMel Gorman 	struct shrink_control shrink = {
281975485363SMel Gorman 		.gfp_mask = sc->gfp_mask,
282075485363SMel Gorman 	};
28217c954f6dSMel Gorman 	bool lowmem_pressure;
282275485363SMel Gorman 
282375485363SMel Gorman 	/* Reclaim above the high watermark. */
282475485363SMel Gorman 	sc->nr_to_reclaim = max(SWAP_CLUSTER_MAX, high_wmark_pages(zone));
28257c954f6dSMel Gorman 
28267c954f6dSMel Gorman 	/*
28277c954f6dSMel Gorman 	 * Kswapd reclaims only single pages with compaction enabled. Trying
28287c954f6dSMel Gorman 	 * too hard to reclaim until contiguous free pages have become
28297c954f6dSMel Gorman 	 * available can hurt performance by evicting too much useful data
28307c954f6dSMel Gorman 	 * from memory. Do not reclaim more than needed for compaction.
28317c954f6dSMel Gorman 	 */
28327c954f6dSMel Gorman 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
28337c954f6dSMel Gorman 			compaction_suitable(zone, sc->order) !=
28347c954f6dSMel Gorman 				COMPACT_SKIPPED)
28357c954f6dSMel Gorman 		testorder = 0;
28367c954f6dSMel Gorman 
28377c954f6dSMel Gorman 	/*
28387c954f6dSMel Gorman 	 * We put equal pressure on every zone, unless one zone has way too
28397c954f6dSMel Gorman 	 * many pages free already. The "too many pages" is defined as the
28407c954f6dSMel Gorman 	 * high wmark plus a "gap" where the gap is either the low
28417c954f6dSMel Gorman 	 * watermark or 1% of the zone, whichever is smaller.
28427c954f6dSMel Gorman 	 */
28437c954f6dSMel Gorman 	balance_gap = min(low_wmark_pages(zone),
28447c954f6dSMel Gorman 		(zone->managed_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
28457c954f6dSMel Gorman 		KSWAPD_ZONE_BALANCE_GAP_RATIO);
28467c954f6dSMel Gorman 
28477c954f6dSMel Gorman 	/*
28487c954f6dSMel Gorman 	 * If there is no low memory pressure or the zone is balanced then no
28497c954f6dSMel Gorman 	 * reclaim is necessary
28507c954f6dSMel Gorman 	 */
28517c954f6dSMel Gorman 	lowmem_pressure = (buffer_heads_over_limit && is_highmem(zone));
28527c954f6dSMel Gorman 	if (!lowmem_pressure && zone_balanced(zone, testorder,
28537c954f6dSMel Gorman 						balance_gap, classzone_idx))
28547c954f6dSMel Gorman 		return true;
28557c954f6dSMel Gorman 
285675485363SMel Gorman 	shrink_zone(zone, sc);
28570ce3d744SDave Chinner 	nodes_clear(shrink.nodes_to_scan);
28580ce3d744SDave Chinner 	node_set(zone_to_nid(zone), shrink.nodes_to_scan);
285975485363SMel Gorman 
286075485363SMel Gorman 	reclaim_state->reclaimed_slab = 0;
286175485363SMel Gorman 	nr_slab = shrink_slab(&shrink, sc->nr_scanned, lru_pages);
286275485363SMel Gorman 	sc->nr_reclaimed += reclaim_state->reclaimed_slab;
286375485363SMel Gorman 
28642ab44f43SMel Gorman 	/* Account for the number of pages attempted to reclaim */
28652ab44f43SMel Gorman 	*nr_attempted += sc->nr_to_reclaim;
28662ab44f43SMel Gorman 
286775485363SMel Gorman 	if (nr_slab == 0 && !zone_reclaimable(zone))
286875485363SMel Gorman 		zone->all_unreclaimable = 1;
2869b8e83b94SMel Gorman 
2870283aba9fSMel Gorman 	zone_clear_flag(zone, ZONE_WRITEBACK);
2871283aba9fSMel Gorman 
28727c954f6dSMel Gorman 	/*
28737c954f6dSMel Gorman 	 * If a zone reaches its high watermark, consider it to be no longer
28747c954f6dSMel Gorman 	 * congested. It's possible there are dirty pages backed by congested
28757c954f6dSMel Gorman 	 * BDIs but as pressure is relieved, speculatively avoid congestion
28767c954f6dSMel Gorman 	 * waits.
28777c954f6dSMel Gorman 	 */
28787c954f6dSMel Gorman 	if (!zone->all_unreclaimable &&
28797c954f6dSMel Gorman 	    zone_balanced(zone, testorder, 0, classzone_idx)) {
28807c954f6dSMel Gorman 		zone_clear_flag(zone, ZONE_CONGESTED);
28817c954f6dSMel Gorman 		zone_clear_flag(zone, ZONE_TAIL_LRU_DIRTY);
28827c954f6dSMel Gorman 	}
28837c954f6dSMel Gorman 
2884b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
288575485363SMel Gorman }
288675485363SMel Gorman 
288775485363SMel Gorman /*
28881da177e4SLinus Torvalds  * For kswapd, balance_pgdat() will work across all this node's zones until
288941858966SMel Gorman  * they are all at high_wmark_pages(zone).
28901da177e4SLinus Torvalds  *
28910abdee2bSMel Gorman  * Returns the final order kswapd was reclaiming at
28921da177e4SLinus Torvalds  *
28931da177e4SLinus Torvalds  * There is special handling here for zones which are full of pinned pages.
28941da177e4SLinus Torvalds  * This can happen if the pages are all mlocked, or if they are all used by
28951da177e4SLinus Torvalds  * device drivers (say, ZONE_DMA).  Or if they are all in use by hugetlb.
28961da177e4SLinus Torvalds  * What we do is to detect the case where all pages in the zone have been
28971da177e4SLinus Torvalds  * scanned twice and there has been zero successful reclaim.  Mark the zone as
28981da177e4SLinus Torvalds  * dead and from now on, only perform a short scan.  Basically we're polling
28991da177e4SLinus Torvalds  * the zone for when the problem goes away.
29001da177e4SLinus Torvalds  *
29011da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
290241858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
290341858966SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
290441858966SMel Gorman  * lower zones regardless of the number of free pages in the lower zones. This
290541858966SMel Gorman  * interoperates with the page allocator fallback scheme to ensure that aging
290641858966SMel Gorman  * of pages is balanced across the zones.
29071da177e4SLinus Torvalds  */
290899504748SMel Gorman static unsigned long balance_pgdat(pg_data_t *pgdat, int order,
2909dc83edd9SMel Gorman 							int *classzone_idx)
29101da177e4SLinus Torvalds {
29111da177e4SLinus Torvalds 	int i;
291299504748SMel Gorman 	int end_zone = 0;	/* Inclusive.  0 = ZONE_DMA */
29130ae5e89cSYing Han 	unsigned long nr_soft_reclaimed;
29140ae5e89cSYing Han 	unsigned long nr_soft_scanned;
2915179e9639SAndrew Morton 	struct scan_control sc = {
2916179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
2917b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
2918a6dc60f8SJohannes Weiner 		.may_unmap = 1,
29192e2e4259SKOSAKI Motohiro 		.may_swap = 1,
2920b8e83b94SMel Gorman 		.may_writepage = !laptop_mode,
29215ad333ebSAndy Whitcroft 		.order = order,
2922f16015fbSJohannes Weiner 		.target_mem_cgroup = NULL,
2923179e9639SAndrew Morton 	};
2924f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
29251da177e4SLinus Torvalds 
29269e3b2f8cSKonstantin Khlebnikov 	do {
29271da177e4SLinus Torvalds 		unsigned long lru_pages = 0;
29282ab44f43SMel Gorman 		unsigned long nr_attempted = 0;
2929b8e83b94SMel Gorman 		bool raise_priority = true;
29302ab44f43SMel Gorman 		bool pgdat_needs_compaction = (order > 0);
2931b8e83b94SMel Gorman 
2932b8e83b94SMel Gorman 		sc.nr_reclaimed = 0;
29331da177e4SLinus Torvalds 
29341da177e4SLinus Torvalds 		/*
29351da177e4SLinus Torvalds 		 * Scan in the highmem->dma direction for the highest
29361da177e4SLinus Torvalds 		 * zone which needs scanning
29371da177e4SLinus Torvalds 		 */
29381da177e4SLinus Torvalds 		for (i = pgdat->nr_zones - 1; i >= 0; i--) {
29391da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
29401da177e4SLinus Torvalds 
2941f3fe6512SCon Kolivas 			if (!populated_zone(zone))
29421da177e4SLinus Torvalds 				continue;
29431da177e4SLinus Torvalds 
29449e3b2f8cSKonstantin Khlebnikov 			if (zone->all_unreclaimable &&
29459e3b2f8cSKonstantin Khlebnikov 			    sc.priority != DEF_PRIORITY)
29461da177e4SLinus Torvalds 				continue;
29471da177e4SLinus Torvalds 
2948556adecbSRik van Riel 			/*
2949556adecbSRik van Riel 			 * Do some background aging of the anon list, to give
2950556adecbSRik van Riel 			 * pages a chance to be referenced before reclaiming.
2951556adecbSRik van Riel 			 */
29529e3b2f8cSKonstantin Khlebnikov 			age_active_anon(zone, &sc);
2953556adecbSRik van Riel 
2954cc715d99SMel Gorman 			/*
2955cc715d99SMel Gorman 			 * If the number of buffer_heads in the machine
2956cc715d99SMel Gorman 			 * exceeds the maximum allowed level and this node
2957cc715d99SMel Gorman 			 * has a highmem zone, force kswapd to reclaim from
2958cc715d99SMel Gorman 			 * it to relieve lowmem pressure.
2959cc715d99SMel Gorman 			 */
2960cc715d99SMel Gorman 			if (buffer_heads_over_limit && is_highmem_idx(i)) {
2961cc715d99SMel Gorman 				end_zone = i;
2962cc715d99SMel Gorman 				break;
2963cc715d99SMel Gorman 			}
2964cc715d99SMel Gorman 
296560cefed4SJohannes Weiner 			if (!zone_balanced(zone, order, 0, 0)) {
29661da177e4SLinus Torvalds 				end_zone = i;
2967e1dbeda6SAndrew Morton 				break;
2968439423f6SShaohua Li 			} else {
2969d43006d5SMel Gorman 				/*
2970d43006d5SMel Gorman 				 * If balanced, clear the dirty and congested
2971d43006d5SMel Gorman 				 * flags
2972d43006d5SMel Gorman 				 */
2973439423f6SShaohua Li 				zone_clear_flag(zone, ZONE_CONGESTED);
2974d43006d5SMel Gorman 				zone_clear_flag(zone, ZONE_TAIL_LRU_DIRTY);
29751da177e4SLinus Torvalds 			}
29761da177e4SLinus Torvalds 		}
2977dafcb73eSZlatko Calusic 
2978b8e83b94SMel Gorman 		if (i < 0)
29791da177e4SLinus Torvalds 			goto out;
2980e1dbeda6SAndrew Morton 
29811da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
29821da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
29831da177e4SLinus Torvalds 
29842ab44f43SMel Gorman 			if (!populated_zone(zone))
29852ab44f43SMel Gorman 				continue;
29862ab44f43SMel Gorman 
2987adea02a1SWu Fengguang 			lru_pages += zone_reclaimable_pages(zone);
29882ab44f43SMel Gorman 
29892ab44f43SMel Gorman 			/*
29902ab44f43SMel Gorman 			 * If any zone is currently balanced then kswapd will
29912ab44f43SMel Gorman 			 * not call compaction as it is expected that the
29922ab44f43SMel Gorman 			 * necessary pages are already available.
29932ab44f43SMel Gorman 			 */
29942ab44f43SMel Gorman 			if (pgdat_needs_compaction &&
29952ab44f43SMel Gorman 					zone_watermark_ok(zone, order,
29962ab44f43SMel Gorman 						low_wmark_pages(zone),
29972ab44f43SMel Gorman 						*classzone_idx, 0))
29982ab44f43SMel Gorman 				pgdat_needs_compaction = false;
29991da177e4SLinus Torvalds 		}
30001da177e4SLinus Torvalds 
30011da177e4SLinus Torvalds 		/*
3002b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3003b7ea3c41SMel Gorman 		 * even in laptop mode.
3004b7ea3c41SMel Gorman 		 */
3005b7ea3c41SMel Gorman 		if (sc.priority < DEF_PRIORITY - 2)
3006b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3007b7ea3c41SMel Gorman 
3008b7ea3c41SMel Gorman 		/*
30091da177e4SLinus Torvalds 		 * Now scan the zone in the dma->highmem direction, stopping
30101da177e4SLinus Torvalds 		 * at the last zone which needs scanning.
30111da177e4SLinus Torvalds 		 *
30121da177e4SLinus Torvalds 		 * We do this because the page allocator works in the opposite
30131da177e4SLinus Torvalds 		 * direction.  This prevents the page allocator from allocating
30141da177e4SLinus Torvalds 		 * pages behind kswapd's direction of progress, which would
30151da177e4SLinus Torvalds 		 * cause too much scanning of the lower zones.
30161da177e4SLinus Torvalds 		 */
30171da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
30181da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
30191da177e4SLinus Torvalds 
3020f3fe6512SCon Kolivas 			if (!populated_zone(zone))
30211da177e4SLinus Torvalds 				continue;
30221da177e4SLinus Torvalds 
30239e3b2f8cSKonstantin Khlebnikov 			if (zone->all_unreclaimable &&
30249e3b2f8cSKonstantin Khlebnikov 			    sc.priority != DEF_PRIORITY)
30251da177e4SLinus Torvalds 				continue;
30261da177e4SLinus Torvalds 
30271da177e4SLinus Torvalds 			sc.nr_scanned = 0;
30284e416953SBalbir Singh 
30290ae5e89cSYing Han 			nr_soft_scanned = 0;
30304e416953SBalbir Singh 			/*
30314e416953SBalbir Singh 			 * Call soft limit reclaim before calling shrink_zone.
30324e416953SBalbir Singh 			 */
30330ae5e89cSYing Han 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
30340ae5e89cSYing Han 							order, sc.gfp_mask,
30350ae5e89cSYing Han 							&nr_soft_scanned);
30360ae5e89cSYing Han 			sc.nr_reclaimed += nr_soft_reclaimed;
303700918b6aSKOSAKI Motohiro 
303832a4330dSRik van Riel 			/*
30397c954f6dSMel Gorman 			 * There should be no need to raise the scanning
30407c954f6dSMel Gorman 			 * priority if enough pages are already being scanned
30417c954f6dSMel Gorman 			 * that that high watermark would be met at 100%
30427c954f6dSMel Gorman 			 * efficiency.
304332a4330dSRik van Riel 			 */
30447c954f6dSMel Gorman 			if (kswapd_shrink_zone(zone, end_zone, &sc,
30457c954f6dSMel Gorman 					lru_pages, &nr_attempted))
3046b8e83b94SMel Gorman 				raise_priority = false;
3047b8e83b94SMel Gorman 		}
3048d7868daeSMel Gorman 
30495515061dSMel Gorman 		/*
30505515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
30515515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
30525515061dSMel Gorman 		 * able to safely make forward progress. Wake them
30535515061dSMel Gorman 		 */
30545515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
30555515061dSMel Gorman 				pfmemalloc_watermark_ok(pgdat))
30565515061dSMel Gorman 			wake_up(&pgdat->pfmemalloc_wait);
30575515061dSMel Gorman 
30581da177e4SLinus Torvalds 		/*
3059b8e83b94SMel Gorman 		 * Fragmentation may mean that the system cannot be rebalanced
3060b8e83b94SMel Gorman 		 * for high-order allocations in all zones. If twice the
3061b8e83b94SMel Gorman 		 * allocation size has been reclaimed and the zones are still
3062b8e83b94SMel Gorman 		 * not balanced then recheck the watermarks at order-0 to
3063b8e83b94SMel Gorman 		 * prevent kswapd reclaiming excessively. Assume that a
3064b8e83b94SMel Gorman 		 * process requested a high-order can direct reclaim/compact.
30651da177e4SLinus Torvalds 		 */
3066b8e83b94SMel Gorman 		if (order && sc.nr_reclaimed >= 2UL << order)
306773ce02e9SKOSAKI Motohiro 			order = sc.order = 0;
306873ce02e9SKOSAKI Motohiro 
3069b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
3070b8e83b94SMel Gorman 		if (try_to_freeze() || kthread_should_stop())
3071b8e83b94SMel Gorman 			break;
3072b8e83b94SMel Gorman 
3073b8e83b94SMel Gorman 		/*
30742ab44f43SMel Gorman 		 * Compact if necessary and kswapd is reclaiming at least the
30752ab44f43SMel Gorman 		 * high watermark number of pages as requsted
30762ab44f43SMel Gorman 		 */
30772ab44f43SMel Gorman 		if (pgdat_needs_compaction && sc.nr_reclaimed > nr_attempted)
30782ab44f43SMel Gorman 			compact_pgdat(pgdat, order);
30792ab44f43SMel Gorman 
30802ab44f43SMel Gorman 		/*
3081b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3082b8e83b94SMel Gorman 		 * progress in reclaiming pages
3083b8e83b94SMel Gorman 		 */
3084b8e83b94SMel Gorman 		if (raise_priority || !sc.nr_reclaimed)
3085b8e83b94SMel Gorman 			sc.priority--;
30869aa41348SMel Gorman 	} while (sc.priority >= 1 &&
3087b8e83b94SMel Gorman 		 !pgdat_balanced(pgdat, order, *classzone_idx));
30881da177e4SLinus Torvalds 
3089b8e83b94SMel Gorman out:
30900abdee2bSMel Gorman 	/*
30915515061dSMel Gorman 	 * Return the order we were reclaiming at so prepare_kswapd_sleep()
30920abdee2bSMel Gorman 	 * makes a decision on the order we were last reclaiming at. However,
30930abdee2bSMel Gorman 	 * if another caller entered the allocator slow path while kswapd
30940abdee2bSMel Gorman 	 * was awake, order will remain at the higher level
30950abdee2bSMel Gorman 	 */
3096dc83edd9SMel Gorman 	*classzone_idx = end_zone;
30970abdee2bSMel Gorman 	return order;
30981da177e4SLinus Torvalds }
30991da177e4SLinus Torvalds 
3100dc83edd9SMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3101f0bc0a60SKOSAKI Motohiro {
3102f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3103f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3104f0bc0a60SKOSAKI Motohiro 
3105f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3106f0bc0a60SKOSAKI Motohiro 		return;
3107f0bc0a60SKOSAKI Motohiro 
3108f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3109f0bc0a60SKOSAKI Motohiro 
3110f0bc0a60SKOSAKI Motohiro 	/* Try to sleep for a short interval */
31115515061dSMel Gorman 	if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
3112f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
3113f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3114f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3115f0bc0a60SKOSAKI Motohiro 	}
3116f0bc0a60SKOSAKI Motohiro 
3117f0bc0a60SKOSAKI Motohiro 	/*
3118f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3119f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3120f0bc0a60SKOSAKI Motohiro 	 */
31215515061dSMel Gorman 	if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
3122f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3123f0bc0a60SKOSAKI Motohiro 
3124f0bc0a60SKOSAKI Motohiro 		/*
3125f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3126f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3127f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3128f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3129f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3130f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3131f0bc0a60SKOSAKI Motohiro 		 */
3132f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
31331c7e7f6cSAaditya Kumar 
313462997027SMel Gorman 		/*
313562997027SMel Gorman 		 * Compaction records what page blocks it recently failed to
313662997027SMel Gorman 		 * isolate pages from and skips them in the future scanning.
313762997027SMel Gorman 		 * When kswapd is going to sleep, it is reasonable to assume
313862997027SMel Gorman 		 * that pages and compaction may succeed so reset the cache.
313962997027SMel Gorman 		 */
314062997027SMel Gorman 		reset_isolation_suitable(pgdat);
314162997027SMel Gorman 
31421c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3143f0bc0a60SKOSAKI Motohiro 			schedule();
31441c7e7f6cSAaditya Kumar 
3145f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3146f0bc0a60SKOSAKI Motohiro 	} else {
3147f0bc0a60SKOSAKI Motohiro 		if (remaining)
3148f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3149f0bc0a60SKOSAKI Motohiro 		else
3150f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3151f0bc0a60SKOSAKI Motohiro 	}
3152f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3153f0bc0a60SKOSAKI Motohiro }
3154f0bc0a60SKOSAKI Motohiro 
31551da177e4SLinus Torvalds /*
31561da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
31571da177e4SLinus Torvalds  * from the init process.
31581da177e4SLinus Torvalds  *
31591da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
31601da177e4SLinus Torvalds  * free memory available even if there is no other activity
31611da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
31621da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
31631da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
31641da177e4SLinus Torvalds  *
31651da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
31661da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
31671da177e4SLinus Torvalds  */
31681da177e4SLinus Torvalds static int kswapd(void *p)
31691da177e4SLinus Torvalds {
3170215ddd66SMel Gorman 	unsigned long order, new_order;
3171d2ebd0f6SAlex,Shi 	unsigned balanced_order;
3172215ddd66SMel Gorman 	int classzone_idx, new_classzone_idx;
3173d2ebd0f6SAlex,Shi 	int balanced_classzone_idx;
31741da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
31751da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3176f0bc0a60SKOSAKI Motohiro 
31771da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
31781da177e4SLinus Torvalds 		.reclaimed_slab = 0,
31791da177e4SLinus Torvalds 	};
3180a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
31811da177e4SLinus Torvalds 
3182cf40bd16SNick Piggin 	lockdep_set_current_reclaim_state(GFP_KERNEL);
3183cf40bd16SNick Piggin 
3184174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3185c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
31861da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
31871da177e4SLinus Torvalds 
31881da177e4SLinus Torvalds 	/*
31891da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
31901da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
31911da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
31921da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
31931da177e4SLinus Torvalds 	 *
31941da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
31951da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
31961da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
31971da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
31981da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
31991da177e4SLinus Torvalds 	 */
3200930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
320183144186SRafael J. Wysocki 	set_freezable();
32021da177e4SLinus Torvalds 
3203215ddd66SMel Gorman 	order = new_order = 0;
3204d2ebd0f6SAlex,Shi 	balanced_order = 0;
3205215ddd66SMel Gorman 	classzone_idx = new_classzone_idx = pgdat->nr_zones - 1;
3206d2ebd0f6SAlex,Shi 	balanced_classzone_idx = classzone_idx;
32071da177e4SLinus Torvalds 	for ( ; ; ) {
32086f6313d4SJeff Liu 		bool ret;
32093e1d1d28SChristoph Lameter 
3210215ddd66SMel Gorman 		/*
3211215ddd66SMel Gorman 		 * If the last balance_pgdat was unsuccessful it's unlikely a
3212215ddd66SMel Gorman 		 * new request of a similar or harder type will succeed soon
3213215ddd66SMel Gorman 		 * so consider going to sleep on the basis we reclaimed at
3214215ddd66SMel Gorman 		 */
3215d2ebd0f6SAlex,Shi 		if (balanced_classzone_idx >= new_classzone_idx &&
3216d2ebd0f6SAlex,Shi 					balanced_order == new_order) {
32171da177e4SLinus Torvalds 			new_order = pgdat->kswapd_max_order;
321899504748SMel Gorman 			new_classzone_idx = pgdat->classzone_idx;
32191da177e4SLinus Torvalds 			pgdat->kswapd_max_order =  0;
3220215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
3221215ddd66SMel Gorman 		}
3222215ddd66SMel Gorman 
322399504748SMel Gorman 		if (order < new_order || classzone_idx > new_classzone_idx) {
32241da177e4SLinus Torvalds 			/*
32251da177e4SLinus Torvalds 			 * Don't sleep if someone wants a larger 'order'
322699504748SMel Gorman 			 * allocation or has tigher zone constraints
32271da177e4SLinus Torvalds 			 */
32281da177e4SLinus Torvalds 			order = new_order;
322999504748SMel Gorman 			classzone_idx = new_classzone_idx;
32301da177e4SLinus Torvalds 		} else {
3231d2ebd0f6SAlex,Shi 			kswapd_try_to_sleep(pgdat, balanced_order,
3232d2ebd0f6SAlex,Shi 						balanced_classzone_idx);
32331da177e4SLinus Torvalds 			order = pgdat->kswapd_max_order;
323499504748SMel Gorman 			classzone_idx = pgdat->classzone_idx;
3235f0dfcde0SAlex,Shi 			new_order = order;
3236f0dfcde0SAlex,Shi 			new_classzone_idx = classzone_idx;
32374d40502eSMel Gorman 			pgdat->kswapd_max_order = 0;
3238215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
32391da177e4SLinus Torvalds 		}
32401da177e4SLinus Torvalds 
32418fe23e05SDavid Rientjes 		ret = try_to_freeze();
32428fe23e05SDavid Rientjes 		if (kthread_should_stop())
32438fe23e05SDavid Rientjes 			break;
32448fe23e05SDavid Rientjes 
32458fe23e05SDavid Rientjes 		/*
32468fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
32478fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3248b1296cc4SRafael J. Wysocki 		 */
324933906bc5SMel Gorman 		if (!ret) {
325033906bc5SMel Gorman 			trace_mm_vmscan_kswapd_wake(pgdat->node_id, order);
3251d2ebd0f6SAlex,Shi 			balanced_classzone_idx = classzone_idx;
3252d2ebd0f6SAlex,Shi 			balanced_order = balance_pgdat(pgdat, order,
3253d2ebd0f6SAlex,Shi 						&balanced_classzone_idx);
32541da177e4SLinus Torvalds 		}
325533906bc5SMel Gorman 	}
3256b0a8cc58STakamori Yamaguchi 
3257b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
32581da177e4SLinus Torvalds 	return 0;
32591da177e4SLinus Torvalds }
32601da177e4SLinus Torvalds 
32611da177e4SLinus Torvalds /*
32621da177e4SLinus Torvalds  * A zone is low on free memory, so wake its kswapd task to service it.
32631da177e4SLinus Torvalds  */
326499504748SMel Gorman void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
32651da177e4SLinus Torvalds {
32661da177e4SLinus Torvalds 	pg_data_t *pgdat;
32671da177e4SLinus Torvalds 
3268f3fe6512SCon Kolivas 	if (!populated_zone(zone))
32691da177e4SLinus Torvalds 		return;
32701da177e4SLinus Torvalds 
327102a0e53dSPaul Jackson 	if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
32721da177e4SLinus Torvalds 		return;
327388f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
327499504748SMel Gorman 	if (pgdat->kswapd_max_order < order) {
327588f5acf8SMel Gorman 		pgdat->kswapd_max_order = order;
327699504748SMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx);
327799504748SMel Gorman 	}
32788d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
32791da177e4SLinus Torvalds 		return;
328088f5acf8SMel Gorman 	if (zone_watermark_ok_safe(zone, order, low_wmark_pages(zone), 0, 0))
328188f5acf8SMel Gorman 		return;
328288f5acf8SMel Gorman 
328388f5acf8SMel Gorman 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
32848d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
32851da177e4SLinus Torvalds }
32861da177e4SLinus Torvalds 
3287adea02a1SWu Fengguang /*
3288adea02a1SWu Fengguang  * The reclaimable count would be mostly accurate.
3289adea02a1SWu Fengguang  * The less reclaimable pages may be
3290adea02a1SWu Fengguang  * - mlocked pages, which will be moved to unevictable list when encountered
3291adea02a1SWu Fengguang  * - mapped pages, which may require several travels to be reclaimed
3292adea02a1SWu Fengguang  * - dirty pages, which is not "instantly" reclaimable
3293adea02a1SWu Fengguang  */
3294adea02a1SWu Fengguang unsigned long global_reclaimable_pages(void)
32954f98a2feSRik van Riel {
3296adea02a1SWu Fengguang 	int nr;
3297adea02a1SWu Fengguang 
3298adea02a1SWu Fengguang 	nr = global_page_state(NR_ACTIVE_FILE) +
3299adea02a1SWu Fengguang 	     global_page_state(NR_INACTIVE_FILE);
3300adea02a1SWu Fengguang 
3301ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
3302adea02a1SWu Fengguang 		nr += global_page_state(NR_ACTIVE_ANON) +
3303adea02a1SWu Fengguang 		      global_page_state(NR_INACTIVE_ANON);
3304adea02a1SWu Fengguang 
3305adea02a1SWu Fengguang 	return nr;
3306adea02a1SWu Fengguang }
3307adea02a1SWu Fengguang 
3308adea02a1SWu Fengguang unsigned long zone_reclaimable_pages(struct zone *zone)
3309adea02a1SWu Fengguang {
3310adea02a1SWu Fengguang 	int nr;
3311adea02a1SWu Fengguang 
3312adea02a1SWu Fengguang 	nr = zone_page_state(zone, NR_ACTIVE_FILE) +
3313adea02a1SWu Fengguang 	     zone_page_state(zone, NR_INACTIVE_FILE);
3314adea02a1SWu Fengguang 
3315ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
3316adea02a1SWu Fengguang 		nr += zone_page_state(zone, NR_ACTIVE_ANON) +
3317adea02a1SWu Fengguang 		      zone_page_state(zone, NR_INACTIVE_ANON);
3318adea02a1SWu Fengguang 
3319adea02a1SWu Fengguang 	return nr;
33204f98a2feSRik van Riel }
33214f98a2feSRik van Riel 
3322c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
33231da177e4SLinus Torvalds /*
33247b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3325d6277db4SRafael J. Wysocki  * freed pages.
3326d6277db4SRafael J. Wysocki  *
3327d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3328d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3329d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
33301da177e4SLinus Torvalds  */
33317b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
33321da177e4SLinus Torvalds {
3333d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3334d6277db4SRafael J. Wysocki 	struct scan_control sc = {
33357b51755cSKOSAKI Motohiro 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
33367b51755cSKOSAKI Motohiro 		.may_swap = 1,
33377b51755cSKOSAKI Motohiro 		.may_unmap = 1,
3338d6277db4SRafael J. Wysocki 		.may_writepage = 1,
33397b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
33407b51755cSKOSAKI Motohiro 		.hibernation_mode = 1,
33417b51755cSKOSAKI Motohiro 		.order = 0,
33429e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
33431da177e4SLinus Torvalds 	};
3344a09ed5e0SYing Han 	struct shrink_control shrink = {
3345a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
3346a09ed5e0SYing Han 	};
33477b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
33487b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
33497b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
33501da177e4SLinus Torvalds 
33517b51755cSKOSAKI Motohiro 	p->flags |= PF_MEMALLOC;
33527b51755cSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(sc.gfp_mask);
3353d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
33547b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3355d6277db4SRafael J. Wysocki 
3356a09ed5e0SYing Han 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
3357d6277db4SRafael J. Wysocki 
33587b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
33597b51755cSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
33607b51755cSKOSAKI Motohiro 	p->flags &= ~PF_MEMALLOC;
3361d6277db4SRafael J. Wysocki 
33627b51755cSKOSAKI Motohiro 	return nr_reclaimed;
33631da177e4SLinus Torvalds }
3364c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
33651da177e4SLinus Torvalds 
33661da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
33671da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
33681da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
33691da177e4SLinus Torvalds    restore their cpu bindings. */
3370fcb35a9bSGreg Kroah-Hartman static int cpu_callback(struct notifier_block *nfb, unsigned long action,
3371fcb35a9bSGreg Kroah-Hartman 			void *hcpu)
33721da177e4SLinus Torvalds {
337358c0a4a7SYasunori Goto 	int nid;
33741da177e4SLinus Torvalds 
33758bb78442SRafael J. Wysocki 	if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
337648fb2e24SLai Jiangshan 		for_each_node_state(nid, N_MEMORY) {
3377c5f59f08SMike Travis 			pg_data_t *pgdat = NODE_DATA(nid);
3378a70f7302SRusty Russell 			const struct cpumask *mask;
3379a70f7302SRusty Russell 
3380a70f7302SRusty Russell 			mask = cpumask_of_node(pgdat->node_id);
3381c5f59f08SMike Travis 
33823e597945SRusty Russell 			if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
33831da177e4SLinus Torvalds 				/* One of our CPUs online: restore mask */
3384c5f59f08SMike Travis 				set_cpus_allowed_ptr(pgdat->kswapd, mask);
33851da177e4SLinus Torvalds 		}
33861da177e4SLinus Torvalds 	}
33871da177e4SLinus Torvalds 	return NOTIFY_OK;
33881da177e4SLinus Torvalds }
33891da177e4SLinus Torvalds 
33903218ae14SYasunori Goto /*
33913218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
33923218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
33933218ae14SYasunori Goto  */
33943218ae14SYasunori Goto int kswapd_run(int nid)
33953218ae14SYasunori Goto {
33963218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
33973218ae14SYasunori Goto 	int ret = 0;
33983218ae14SYasunori Goto 
33993218ae14SYasunori Goto 	if (pgdat->kswapd)
34003218ae14SYasunori Goto 		return 0;
34013218ae14SYasunori Goto 
34023218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
34033218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
34043218ae14SYasunori Goto 		/* failure at boot is fatal */
34053218ae14SYasunori Goto 		BUG_ON(system_state == SYSTEM_BOOTING);
3406d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3407d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3408d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
34093218ae14SYasunori Goto 	}
34103218ae14SYasunori Goto 	return ret;
34113218ae14SYasunori Goto }
34123218ae14SYasunori Goto 
34138fe23e05SDavid Rientjes /*
3414d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3415d8adde17SJiang Liu  * hold lock_memory_hotplug().
34168fe23e05SDavid Rientjes  */
34178fe23e05SDavid Rientjes void kswapd_stop(int nid)
34188fe23e05SDavid Rientjes {
34198fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
34208fe23e05SDavid Rientjes 
3421d8adde17SJiang Liu 	if (kswapd) {
34228fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3423d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3424d8adde17SJiang Liu 	}
34258fe23e05SDavid Rientjes }
34268fe23e05SDavid Rientjes 
34271da177e4SLinus Torvalds static int __init kswapd_init(void)
34281da177e4SLinus Torvalds {
34293218ae14SYasunori Goto 	int nid;
343069e05944SAndrew Morton 
34311da177e4SLinus Torvalds 	swap_setup();
343248fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
34333218ae14SYasunori Goto  		kswapd_run(nid);
34341da177e4SLinus Torvalds 	hotcpu_notifier(cpu_callback, 0);
34351da177e4SLinus Torvalds 	return 0;
34361da177e4SLinus Torvalds }
34371da177e4SLinus Torvalds 
34381da177e4SLinus Torvalds module_init(kswapd_init)
34399eeff239SChristoph Lameter 
34409eeff239SChristoph Lameter #ifdef CONFIG_NUMA
34419eeff239SChristoph Lameter /*
34429eeff239SChristoph Lameter  * Zone reclaim mode
34439eeff239SChristoph Lameter  *
34449eeff239SChristoph Lameter  * If non-zero call zone_reclaim when the number of free pages falls below
34459eeff239SChristoph Lameter  * the watermarks.
34469eeff239SChristoph Lameter  */
34479eeff239SChristoph Lameter int zone_reclaim_mode __read_mostly;
34489eeff239SChristoph Lameter 
34491b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
34507d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
34511b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
34521b2ffb78SChristoph Lameter #define RECLAIM_SWAP (1<<2)	/* Swap pages out during reclaim */
34531b2ffb78SChristoph Lameter 
34549eeff239SChristoph Lameter /*
3455a92f7126SChristoph Lameter  * Priority for ZONE_RECLAIM. This determines the fraction of pages
3456a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3457a92f7126SChristoph Lameter  * a zone.
3458a92f7126SChristoph Lameter  */
3459a92f7126SChristoph Lameter #define ZONE_RECLAIM_PRIORITY 4
3460a92f7126SChristoph Lameter 
34619eeff239SChristoph Lameter /*
34629614634fSChristoph Lameter  * Percentage of pages in a zone that must be unmapped for zone_reclaim to
34639614634fSChristoph Lameter  * occur.
34649614634fSChristoph Lameter  */
34659614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
34669614634fSChristoph Lameter 
34679614634fSChristoph Lameter /*
34680ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
34690ff38490SChristoph Lameter  * slab reclaim needs to occur.
34700ff38490SChristoph Lameter  */
34710ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
34720ff38490SChristoph Lameter 
347390afa5deSMel Gorman static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
347490afa5deSMel Gorman {
347590afa5deSMel Gorman 	unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
347690afa5deSMel Gorman 	unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
347790afa5deSMel Gorman 		zone_page_state(zone, NR_ACTIVE_FILE);
347890afa5deSMel Gorman 
347990afa5deSMel Gorman 	/*
348090afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
348190afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
348290afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
348390afa5deSMel Gorman 	 */
348490afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
348590afa5deSMel Gorman }
348690afa5deSMel Gorman 
348790afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
348890afa5deSMel Gorman static long zone_pagecache_reclaimable(struct zone *zone)
348990afa5deSMel Gorman {
349090afa5deSMel Gorman 	long nr_pagecache_reclaimable;
349190afa5deSMel Gorman 	long delta = 0;
349290afa5deSMel Gorman 
349390afa5deSMel Gorman 	/*
349490afa5deSMel Gorman 	 * If RECLAIM_SWAP is set, then all file pages are considered
349590afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
349690afa5deSMel Gorman 	 * pages like swapcache and zone_unmapped_file_pages() provides
349790afa5deSMel Gorman 	 * a better estimate
349890afa5deSMel Gorman 	 */
349990afa5deSMel Gorman 	if (zone_reclaim_mode & RECLAIM_SWAP)
350090afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
350190afa5deSMel Gorman 	else
350290afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
350390afa5deSMel Gorman 
350490afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
350590afa5deSMel Gorman 	if (!(zone_reclaim_mode & RECLAIM_WRITE))
350690afa5deSMel Gorman 		delta += zone_page_state(zone, NR_FILE_DIRTY);
350790afa5deSMel Gorman 
350890afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
350990afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
351090afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
351190afa5deSMel Gorman 
351290afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
351390afa5deSMel Gorman }
351490afa5deSMel Gorman 
35150ff38490SChristoph Lameter /*
35169eeff239SChristoph Lameter  * Try to free up some pages from this zone through reclaim.
35179eeff239SChristoph Lameter  */
3518179e9639SAndrew Morton static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
35199eeff239SChristoph Lameter {
35207fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
352169e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
35229eeff239SChristoph Lameter 	struct task_struct *p = current;
35239eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
3524179e9639SAndrew Morton 	struct scan_control sc = {
3525179e9639SAndrew Morton 		.may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
3526a6dc60f8SJohannes Weiner 		.may_unmap = !!(zone_reclaim_mode & RECLAIM_SWAP),
35272e2e4259SKOSAKI Motohiro 		.may_swap = 1,
352862b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
352921caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
3530bd2f6199SJohannes Weiner 		.order = order,
35319e3b2f8cSKonstantin Khlebnikov 		.priority = ZONE_RECLAIM_PRIORITY,
3532179e9639SAndrew Morton 	};
3533a09ed5e0SYing Han 	struct shrink_control shrink = {
3534a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
3535a09ed5e0SYing Han 	};
353615748048SKOSAKI Motohiro 	unsigned long nr_slab_pages0, nr_slab_pages1;
35379eeff239SChristoph Lameter 
35389eeff239SChristoph Lameter 	cond_resched();
3539d4f7796eSChristoph Lameter 	/*
3540d4f7796eSChristoph Lameter 	 * We need to be able to allocate from the reserves for RECLAIM_SWAP
3541d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
3542d4f7796eSChristoph Lameter 	 * and RECLAIM_SWAP.
3543d4f7796eSChristoph Lameter 	 */
3544d4f7796eSChristoph Lameter 	p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
354576ca542dSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(gfp_mask);
35469eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
35479eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3548c84db23cSChristoph Lameter 
354990afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
3550a92f7126SChristoph Lameter 		/*
35510ff38490SChristoph Lameter 		 * Free memory by calling shrink zone with increasing
35520ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3553a92f7126SChristoph Lameter 		 */
3554a92f7126SChristoph Lameter 		do {
35559e3b2f8cSKonstantin Khlebnikov 			shrink_zone(zone, &sc);
35569e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
35570ff38490SChristoph Lameter 	}
3558a92f7126SChristoph Lameter 
355915748048SKOSAKI Motohiro 	nr_slab_pages0 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
356015748048SKOSAKI Motohiro 	if (nr_slab_pages0 > zone->min_slab_pages) {
35612a16e3f4SChristoph Lameter 		/*
35627fb2d46dSChristoph Lameter 		 * shrink_slab() does not currently allow us to determine how
35630ff38490SChristoph Lameter 		 * many pages were freed in this zone. So we take the current
35640ff38490SChristoph Lameter 		 * number of slab pages and shake the slab until it is reduced
35650ff38490SChristoph Lameter 		 * by the same nr_pages that we used for reclaiming unmapped
35660ff38490SChristoph Lameter 		 * pages.
35672a16e3f4SChristoph Lameter 		 */
35680ce3d744SDave Chinner 		nodes_clear(shrink.nodes_to_scan);
35690ce3d744SDave Chinner 		node_set(zone_to_nid(zone), shrink.nodes_to_scan);
35704dc4b3d9SKOSAKI Motohiro 		for (;;) {
35714dc4b3d9SKOSAKI Motohiro 			unsigned long lru_pages = zone_reclaimable_pages(zone);
35724dc4b3d9SKOSAKI Motohiro 
35734dc4b3d9SKOSAKI Motohiro 			/* No reclaimable slab or very low memory pressure */
35741495f230SYing Han 			if (!shrink_slab(&shrink, sc.nr_scanned, lru_pages))
35754dc4b3d9SKOSAKI Motohiro 				break;
35764dc4b3d9SKOSAKI Motohiro 
35774dc4b3d9SKOSAKI Motohiro 			/* Freed enough memory */
35784dc4b3d9SKOSAKI Motohiro 			nr_slab_pages1 = zone_page_state(zone,
35794dc4b3d9SKOSAKI Motohiro 							NR_SLAB_RECLAIMABLE);
35804dc4b3d9SKOSAKI Motohiro 			if (nr_slab_pages1 + nr_pages <= nr_slab_pages0)
35814dc4b3d9SKOSAKI Motohiro 				break;
35824dc4b3d9SKOSAKI Motohiro 		}
358383e33a47SChristoph Lameter 
358483e33a47SChristoph Lameter 		/*
358583e33a47SChristoph Lameter 		 * Update nr_reclaimed by the number of slab pages we
358683e33a47SChristoph Lameter 		 * reclaimed from this zone.
358783e33a47SChristoph Lameter 		 */
358815748048SKOSAKI Motohiro 		nr_slab_pages1 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
358915748048SKOSAKI Motohiro 		if (nr_slab_pages1 < nr_slab_pages0)
359015748048SKOSAKI Motohiro 			sc.nr_reclaimed += nr_slab_pages0 - nr_slab_pages1;
35912a16e3f4SChristoph Lameter 	}
35922a16e3f4SChristoph Lameter 
35939eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3594d4f7796eSChristoph Lameter 	current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
359576ca542dSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
3596a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
35979eeff239SChristoph Lameter }
3598179e9639SAndrew Morton 
3599179e9639SAndrew Morton int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
3600179e9639SAndrew Morton {
3601179e9639SAndrew Morton 	int node_id;
3602d773ed6bSDavid Rientjes 	int ret;
3603179e9639SAndrew Morton 
3604179e9639SAndrew Morton 	/*
36050ff38490SChristoph Lameter 	 * Zone reclaim reclaims unmapped file backed pages and
36060ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
360734aa1330SChristoph Lameter 	 *
36089614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
36099614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
36109614634fSChristoph Lameter 	 * thrown out if the zone is overallocated. So we do not reclaim
36119614634fSChristoph Lameter 	 * if less than a specified percentage of the zone is used by
36129614634fSChristoph Lameter 	 * unmapped file backed pages.
3613179e9639SAndrew Morton 	 */
361490afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
361590afa5deSMel Gorman 	    zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
3616fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3617179e9639SAndrew Morton 
361893e4a89aSKOSAKI Motohiro 	if (zone->all_unreclaimable)
3619fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3620d773ed6bSDavid Rientjes 
3621179e9639SAndrew Morton 	/*
3622d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3623179e9639SAndrew Morton 	 */
3624d773ed6bSDavid Rientjes 	if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
3625fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3626179e9639SAndrew Morton 
3627179e9639SAndrew Morton 	/*
3628179e9639SAndrew Morton 	 * Only run zone reclaim on the local zone or on zones that do not
3629179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3630179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3631179e9639SAndrew Morton 	 * as wide as possible.
3632179e9639SAndrew Morton 	 */
363389fa3024SChristoph Lameter 	node_id = zone_to_nid(zone);
363437c0708dSChristoph Lameter 	if (node_state(node_id, N_CPU) && node_id != numa_node_id())
3635fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3636d773ed6bSDavid Rientjes 
3637d773ed6bSDavid Rientjes 	if (zone_test_and_set_flag(zone, ZONE_RECLAIM_LOCKED))
3638fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3639fa5e084eSMel Gorman 
3640d773ed6bSDavid Rientjes 	ret = __zone_reclaim(zone, gfp_mask, order);
3641d773ed6bSDavid Rientjes 	zone_clear_flag(zone, ZONE_RECLAIM_LOCKED);
3642d773ed6bSDavid Rientjes 
364324cf7251SMel Gorman 	if (!ret)
364424cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
364524cf7251SMel Gorman 
3646d773ed6bSDavid Rientjes 	return ret;
3647179e9639SAndrew Morton }
36489eeff239SChristoph Lameter #endif
3649894bc310SLee Schermerhorn 
3650894bc310SLee Schermerhorn /*
3651894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3652894bc310SLee Schermerhorn  * @page: the page to test
3653894bc310SLee Schermerhorn  *
3654894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
365539b5f29aSHugh Dickins  * lists vs unevictable list.
3656894bc310SLee Schermerhorn  *
3657894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3658ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3659b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3660ba9ddf49SLee Schermerhorn  *
3661894bc310SLee Schermerhorn  */
366239b5f29aSHugh Dickins int page_evictable(struct page *page)
3663894bc310SLee Schermerhorn {
366439b5f29aSHugh Dickins 	return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3665894bc310SLee Schermerhorn }
366689e004eaSLee Schermerhorn 
366785046579SHugh Dickins #ifdef CONFIG_SHMEM
366889e004eaSLee Schermerhorn /**
366924513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
367024513264SHugh Dickins  * @pages:	array of pages to check
367124513264SHugh Dickins  * @nr_pages:	number of pages to check
367289e004eaSLee Schermerhorn  *
367324513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
367485046579SHugh Dickins  *
367585046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
367689e004eaSLee Schermerhorn  */
367724513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
367889e004eaSLee Schermerhorn {
3679925b7673SJohannes Weiner 	struct lruvec *lruvec;
368024513264SHugh Dickins 	struct zone *zone = NULL;
368124513264SHugh Dickins 	int pgscanned = 0;
368224513264SHugh Dickins 	int pgrescued = 0;
368389e004eaSLee Schermerhorn 	int i;
368489e004eaSLee Schermerhorn 
368524513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
368624513264SHugh Dickins 		struct page *page = pages[i];
368724513264SHugh Dickins 		struct zone *pagezone;
368889e004eaSLee Schermerhorn 
368924513264SHugh Dickins 		pgscanned++;
369024513264SHugh Dickins 		pagezone = page_zone(page);
369189e004eaSLee Schermerhorn 		if (pagezone != zone) {
369289e004eaSLee Schermerhorn 			if (zone)
369389e004eaSLee Schermerhorn 				spin_unlock_irq(&zone->lru_lock);
369489e004eaSLee Schermerhorn 			zone = pagezone;
369589e004eaSLee Schermerhorn 			spin_lock_irq(&zone->lru_lock);
369689e004eaSLee Schermerhorn 		}
3697fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
369889e004eaSLee Schermerhorn 
369924513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
370024513264SHugh Dickins 			continue;
370189e004eaSLee Schermerhorn 
370239b5f29aSHugh Dickins 		if (page_evictable(page)) {
370324513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
370424513264SHugh Dickins 
370524513264SHugh Dickins 			VM_BUG_ON(PageActive(page));
370624513264SHugh Dickins 			ClearPageUnevictable(page);
3707fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3708fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
370924513264SHugh Dickins 			pgrescued++;
371089e004eaSLee Schermerhorn 		}
371189e004eaSLee Schermerhorn 	}
371224513264SHugh Dickins 
371324513264SHugh Dickins 	if (zone) {
371424513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
371524513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
371624513264SHugh Dickins 		spin_unlock_irq(&zone->lru_lock);
371724513264SHugh Dickins 	}
371885046579SHugh Dickins }
371985046579SHugh Dickins #endif /* CONFIG_SHMEM */
3720af936a16SLee Schermerhorn 
3721264e56d8SJohannes Weiner static void warn_scan_unevictable_pages(void)
3722af936a16SLee Schermerhorn {
3723264e56d8SJohannes Weiner 	printk_once(KERN_WARNING
372425bd91bdSKOSAKI Motohiro 		    "%s: The scan_unevictable_pages sysctl/node-interface has been "
3725264e56d8SJohannes Weiner 		    "disabled for lack of a legitimate use case.  If you have "
372625bd91bdSKOSAKI Motohiro 		    "one, please send an email to linux-mm@kvack.org.\n",
372725bd91bdSKOSAKI Motohiro 		    current->comm);
3728af936a16SLee Schermerhorn }
3729af936a16SLee Schermerhorn 
3730af936a16SLee Schermerhorn /*
3731af936a16SLee Schermerhorn  * scan_unevictable_pages [vm] sysctl handler.  On demand re-scan of
3732af936a16SLee Schermerhorn  * all nodes' unevictable lists for evictable pages
3733af936a16SLee Schermerhorn  */
3734af936a16SLee Schermerhorn unsigned long scan_unevictable_pages;
3735af936a16SLee Schermerhorn 
3736af936a16SLee Schermerhorn int scan_unevictable_handler(struct ctl_table *table, int write,
37378d65af78SAlexey Dobriyan 			   void __user *buffer,
3738af936a16SLee Schermerhorn 			   size_t *length, loff_t *ppos)
3739af936a16SLee Schermerhorn {
3740264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
37418d65af78SAlexey Dobriyan 	proc_doulongvec_minmax(table, write, buffer, length, ppos);
3742af936a16SLee Schermerhorn 	scan_unevictable_pages = 0;
3743af936a16SLee Schermerhorn 	return 0;
3744af936a16SLee Schermerhorn }
3745af936a16SLee Schermerhorn 
3746e4455abbSThadeu Lima de Souza Cascardo #ifdef CONFIG_NUMA
3747af936a16SLee Schermerhorn /*
3748af936a16SLee Schermerhorn  * per node 'scan_unevictable_pages' attribute.  On demand re-scan of
3749af936a16SLee Schermerhorn  * a specified node's per zone unevictable lists for evictable pages.
3750af936a16SLee Schermerhorn  */
3751af936a16SLee Schermerhorn 
375210fbcf4cSKay Sievers static ssize_t read_scan_unevictable_node(struct device *dev,
375310fbcf4cSKay Sievers 					  struct device_attribute *attr,
3754af936a16SLee Schermerhorn 					  char *buf)
3755af936a16SLee Schermerhorn {
3756264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
3757af936a16SLee Schermerhorn 	return sprintf(buf, "0\n");	/* always zero; should fit... */
3758af936a16SLee Schermerhorn }
3759af936a16SLee Schermerhorn 
376010fbcf4cSKay Sievers static ssize_t write_scan_unevictable_node(struct device *dev,
376110fbcf4cSKay Sievers 					   struct device_attribute *attr,
3762af936a16SLee Schermerhorn 					const char *buf, size_t count)
3763af936a16SLee Schermerhorn {
3764264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
3765af936a16SLee Schermerhorn 	return 1;
3766af936a16SLee Schermerhorn }
3767af936a16SLee Schermerhorn 
3768af936a16SLee Schermerhorn 
376910fbcf4cSKay Sievers static DEVICE_ATTR(scan_unevictable_pages, S_IRUGO | S_IWUSR,
3770af936a16SLee Schermerhorn 			read_scan_unevictable_node,
3771af936a16SLee Schermerhorn 			write_scan_unevictable_node);
3772af936a16SLee Schermerhorn 
3773af936a16SLee Schermerhorn int scan_unevictable_register_node(struct node *node)
3774af936a16SLee Schermerhorn {
377510fbcf4cSKay Sievers 	return device_create_file(&node->dev, &dev_attr_scan_unevictable_pages);
3776af936a16SLee Schermerhorn }
3777af936a16SLee Schermerhorn 
3778af936a16SLee Schermerhorn void scan_unevictable_unregister_node(struct node *node)
3779af936a16SLee Schermerhorn {
378010fbcf4cSKay Sievers 	device_remove_file(&node->dev, &dev_attr_scan_unevictable_pages);
3781af936a16SLee Schermerhorn }
3782e4455abbSThadeu Lima de Souza Cascardo #endif
3783