xref: /openbmc/linux/mm/vmscan.c (revision 24f7c6b981fb70084757382da464ea85d72af300)
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 /*
1581da177e4SLinus Torvalds  * Add a shrinker callback to be called from the vm
1591da177e4SLinus Torvalds  */
1608e1f936bSRusty Russell void register_shrinker(struct shrinker *shrinker)
1611da177e4SLinus Torvalds {
16283aeeadaSKonstantin Khlebnikov 	atomic_long_set(&shrinker->nr_in_batch, 0);
1631da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
1641da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
1651da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
1661da177e4SLinus Torvalds }
1678e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
1681da177e4SLinus Torvalds 
1691da177e4SLinus Torvalds /*
1701da177e4SLinus Torvalds  * Remove one
1711da177e4SLinus Torvalds  */
1728e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
1731da177e4SLinus Torvalds {
1741da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
1751da177e4SLinus Torvalds 	list_del(&shrinker->list);
1761da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
1771da177e4SLinus Torvalds }
1788e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
1791da177e4SLinus Torvalds 
1801495f230SYing Han static inline int do_shrinker_shrink(struct shrinker *shrinker,
1811495f230SYing Han 				     struct shrink_control *sc,
1821495f230SYing Han 				     unsigned long nr_to_scan)
1831495f230SYing Han {
1841495f230SYing Han 	sc->nr_to_scan = nr_to_scan;
1851495f230SYing Han 	return (*shrinker->shrink)(shrinker, sc);
1861495f230SYing Han }
1871495f230SYing Han 
1881da177e4SLinus Torvalds #define SHRINK_BATCH 128
1891da177e4SLinus Torvalds /*
1901da177e4SLinus Torvalds  * Call the shrink functions to age shrinkable caches
1911da177e4SLinus Torvalds  *
1921da177e4SLinus Torvalds  * Here we assume it costs one seek to replace a lru page and that it also
1931da177e4SLinus Torvalds  * takes a seek to recreate a cache object.  With this in mind we age equal
1941da177e4SLinus Torvalds  * percentages of the lru and ageable caches.  This should balance the seeks
1951da177e4SLinus Torvalds  * generated by these structures.
1961da177e4SLinus Torvalds  *
197183ff22bSSimon Arlott  * If the vm encountered mapped pages on the LRU it increase the pressure on
1981da177e4SLinus Torvalds  * slab to avoid swapping.
1991da177e4SLinus Torvalds  *
2001da177e4SLinus Torvalds  * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
2011da177e4SLinus Torvalds  *
2021da177e4SLinus Torvalds  * `lru_pages' represents the number of on-LRU pages in all the zones which
2031da177e4SLinus Torvalds  * are eligible for the caller's allocation attempt.  It is used for balancing
2041da177e4SLinus Torvalds  * slab reclaim versus page reclaim.
205b15e0905Sakpm@osdl.org  *
206b15e0905Sakpm@osdl.org  * Returns the number of slab objects which we shrunk.
2071da177e4SLinus Torvalds  */
208*24f7c6b9SDave Chinner unsigned long shrink_slab(struct shrink_control *shrinkctl,
2091495f230SYing Han 			  unsigned long nr_pages_scanned,
21069e05944SAndrew Morton 			  unsigned long lru_pages)
2111da177e4SLinus Torvalds {
2121da177e4SLinus Torvalds 	struct shrinker *shrinker;
213*24f7c6b9SDave Chinner 	unsigned long freed = 0;
2141da177e4SLinus Torvalds 
2151495f230SYing Han 	if (nr_pages_scanned == 0)
2161495f230SYing Han 		nr_pages_scanned = SWAP_CLUSTER_MAX;
2171da177e4SLinus Torvalds 
218f06590bdSMinchan Kim 	if (!down_read_trylock(&shrinker_rwsem)) {
219*24f7c6b9SDave Chinner 		/*
220*24f7c6b9SDave Chinner 		 * If we would return 0, our callers would understand that we
221*24f7c6b9SDave Chinner 		 * have nothing else to shrink and give up trying. By returning
222*24f7c6b9SDave Chinner 		 * 1 we keep it going and assume we'll be able to shrink next
223*24f7c6b9SDave Chinner 		 * time.
224*24f7c6b9SDave Chinner 		 */
225*24f7c6b9SDave Chinner 		freed = 1;
226f06590bdSMinchan Kim 		goto out;
227f06590bdSMinchan Kim 	}
2281da177e4SLinus Torvalds 
2291da177e4SLinus Torvalds 	list_for_each_entry(shrinker, &shrinker_list, list) {
2301da177e4SLinus Torvalds 		unsigned long long delta;
231635697c6SKonstantin Khlebnikov 		long total_scan;
232635697c6SKonstantin Khlebnikov 		long max_pass;
233acf92b48SDave Chinner 		long nr;
234acf92b48SDave Chinner 		long new_nr;
235e9299f50SDave Chinner 		long batch_size = shrinker->batch ? shrinker->batch
236e9299f50SDave Chinner 						  : SHRINK_BATCH;
2371da177e4SLinus Torvalds 
238*24f7c6b9SDave Chinner 		if (shrinker->count_objects)
239*24f7c6b9SDave Chinner 			max_pass = shrinker->count_objects(shrinker, shrinkctl);
240*24f7c6b9SDave Chinner 		else
241*24f7c6b9SDave Chinner 			max_pass = do_shrinker_shrink(shrinker, shrinkctl, 0);
242*24f7c6b9SDave Chinner 		if (max_pass == 0)
243635697c6SKonstantin Khlebnikov 			continue;
244635697c6SKonstantin Khlebnikov 
245acf92b48SDave Chinner 		/*
246acf92b48SDave Chinner 		 * copy the current shrinker scan count into a local variable
247acf92b48SDave Chinner 		 * and zero it so that other concurrent shrinker invocations
248acf92b48SDave Chinner 		 * don't also do this scanning work.
249acf92b48SDave Chinner 		 */
25083aeeadaSKonstantin Khlebnikov 		nr = atomic_long_xchg(&shrinker->nr_in_batch, 0);
251acf92b48SDave Chinner 
252acf92b48SDave Chinner 		total_scan = nr;
2531495f230SYing Han 		delta = (4 * nr_pages_scanned) / shrinker->seeks;
254ea164d73SAndrea Arcangeli 		delta *= max_pass;
2551da177e4SLinus Torvalds 		do_div(delta, lru_pages + 1);
256acf92b48SDave Chinner 		total_scan += delta;
257acf92b48SDave Chinner 		if (total_scan < 0) {
258*24f7c6b9SDave Chinner 			printk(KERN_ERR
259*24f7c6b9SDave Chinner 			"shrink_slab: %pF negative objects to delete nr=%ld\n",
260acf92b48SDave Chinner 			       shrinker->shrink, total_scan);
261acf92b48SDave Chinner 			total_scan = max_pass;
262ea164d73SAndrea Arcangeli 		}
263ea164d73SAndrea Arcangeli 
264ea164d73SAndrea Arcangeli 		/*
2653567b59aSDave Chinner 		 * We need to avoid excessive windup on filesystem shrinkers
2663567b59aSDave Chinner 		 * due to large numbers of GFP_NOFS allocations causing the
2673567b59aSDave Chinner 		 * shrinkers to return -1 all the time. This results in a large
2683567b59aSDave Chinner 		 * nr being built up so when a shrink that can do some work
2693567b59aSDave Chinner 		 * comes along it empties the entire cache due to nr >>>
2703567b59aSDave Chinner 		 * max_pass.  This is bad for sustaining a working set in
2713567b59aSDave Chinner 		 * memory.
2723567b59aSDave Chinner 		 *
2733567b59aSDave Chinner 		 * Hence only allow the shrinker to scan the entire cache when
2743567b59aSDave Chinner 		 * a large delta change is calculated directly.
2753567b59aSDave Chinner 		 */
2763567b59aSDave Chinner 		if (delta < max_pass / 4)
2773567b59aSDave Chinner 			total_scan = min(total_scan, max_pass / 2);
2783567b59aSDave Chinner 
2793567b59aSDave Chinner 		/*
280ea164d73SAndrea Arcangeli 		 * Avoid risking looping forever due to too large nr value:
281ea164d73SAndrea Arcangeli 		 * never try to free more than twice the estimate number of
282ea164d73SAndrea Arcangeli 		 * freeable entries.
283ea164d73SAndrea Arcangeli 		 */
284acf92b48SDave Chinner 		if (total_scan > max_pass * 2)
285acf92b48SDave Chinner 			total_scan = max_pass * 2;
2861da177e4SLinus Torvalds 
287*24f7c6b9SDave Chinner 		trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
28809576073SDave Chinner 					nr_pages_scanned, lru_pages,
28909576073SDave Chinner 					max_pass, delta, total_scan);
29009576073SDave Chinner 
291e9299f50SDave Chinner 		while (total_scan >= batch_size) {
2921da177e4SLinus Torvalds 
293*24f7c6b9SDave Chinner 			if (shrinker->scan_objects) {
294*24f7c6b9SDave Chinner 				unsigned long ret;
295*24f7c6b9SDave Chinner 				shrinkctl->nr_to_scan = batch_size;
296*24f7c6b9SDave Chinner 				ret = shrinker->scan_objects(shrinker, shrinkctl);
297*24f7c6b9SDave Chinner 
298*24f7c6b9SDave Chinner 				if (ret == SHRINK_STOP)
2991da177e4SLinus Torvalds 					break;
300*24f7c6b9SDave Chinner 				freed += ret;
301*24f7c6b9SDave Chinner 			} else {
302*24f7c6b9SDave Chinner 				int nr_before;
303*24f7c6b9SDave Chinner 				long ret;
304*24f7c6b9SDave Chinner 
305*24f7c6b9SDave Chinner 				nr_before = do_shrinker_shrink(shrinker, shrinkctl, 0);
306*24f7c6b9SDave Chinner 				ret = do_shrinker_shrink(shrinker, shrinkctl,
307*24f7c6b9SDave Chinner 								batch_size);
308*24f7c6b9SDave Chinner 				if (ret == -1)
309*24f7c6b9SDave Chinner 					break;
310*24f7c6b9SDave Chinner 				if (ret < nr_before)
311*24f7c6b9SDave Chinner 					freed += nr_before - ret;
312*24f7c6b9SDave Chinner 			}
313*24f7c6b9SDave Chinner 
314e9299f50SDave Chinner 			count_vm_events(SLABS_SCANNED, batch_size);
315e9299f50SDave Chinner 			total_scan -= batch_size;
3161da177e4SLinus Torvalds 
3171da177e4SLinus Torvalds 			cond_resched();
3181da177e4SLinus Torvalds 		}
3191da177e4SLinus Torvalds 
320acf92b48SDave Chinner 		/*
321acf92b48SDave Chinner 		 * move the unused scan count back into the shrinker in a
322acf92b48SDave Chinner 		 * manner that handles concurrent updates. If we exhausted the
323acf92b48SDave Chinner 		 * scan, there is no need to do an update.
324acf92b48SDave Chinner 		 */
32583aeeadaSKonstantin Khlebnikov 		if (total_scan > 0)
32683aeeadaSKonstantin Khlebnikov 			new_nr = atomic_long_add_return(total_scan,
32783aeeadaSKonstantin Khlebnikov 					&shrinker->nr_in_batch);
32883aeeadaSKonstantin Khlebnikov 		else
32983aeeadaSKonstantin Khlebnikov 			new_nr = atomic_long_read(&shrinker->nr_in_batch);
330acf92b48SDave Chinner 
331*24f7c6b9SDave Chinner 		trace_mm_shrink_slab_end(shrinker, freed, nr, new_nr);
3321da177e4SLinus Torvalds 	}
3331da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
334f06590bdSMinchan Kim out:
335f06590bdSMinchan Kim 	cond_resched();
336*24f7c6b9SDave Chinner 	return freed;
3371da177e4SLinus Torvalds }
3381da177e4SLinus Torvalds 
3391da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
3401da177e4SLinus Torvalds {
341ceddc3a5SJohannes Weiner 	/*
342ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
343ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
344ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
345ceddc3a5SJohannes Weiner 	 */
346edcf4748SJohannes Weiner 	return page_count(page) - page_has_private(page) == 2;
3471da177e4SLinus Torvalds }
3481da177e4SLinus Torvalds 
3497d3579e8SKOSAKI Motohiro static int may_write_to_queue(struct backing_dev_info *bdi,
3507d3579e8SKOSAKI Motohiro 			      struct scan_control *sc)
3511da177e4SLinus Torvalds {
352930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
3531da177e4SLinus Torvalds 		return 1;
3541da177e4SLinus Torvalds 	if (!bdi_write_congested(bdi))
3551da177e4SLinus Torvalds 		return 1;
3561da177e4SLinus Torvalds 	if (bdi == current->backing_dev_info)
3571da177e4SLinus Torvalds 		return 1;
3581da177e4SLinus Torvalds 	return 0;
3591da177e4SLinus Torvalds }
3601da177e4SLinus Torvalds 
3611da177e4SLinus Torvalds /*
3621da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
3631da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
3641da177e4SLinus Torvalds  * fsync(), msync() or close().
3651da177e4SLinus Torvalds  *
3661da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
3671da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
3681da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
3691da177e4SLinus Torvalds  *
3701da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
3711da177e4SLinus Torvalds  * __GFP_FS.
3721da177e4SLinus Torvalds  */
3731da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
3741da177e4SLinus Torvalds 				struct page *page, int error)
3751da177e4SLinus Torvalds {
3767eaceaccSJens Axboe 	lock_page(page);
3773e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
3783e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
3791da177e4SLinus Torvalds 	unlock_page(page);
3801da177e4SLinus Torvalds }
3811da177e4SLinus Torvalds 
38204e62a29SChristoph Lameter /* possible outcome of pageout() */
38304e62a29SChristoph Lameter typedef enum {
38404e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
38504e62a29SChristoph Lameter 	PAGE_KEEP,
38604e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
38704e62a29SChristoph Lameter 	PAGE_ACTIVATE,
38804e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
38904e62a29SChristoph Lameter 	PAGE_SUCCESS,
39004e62a29SChristoph Lameter 	/* page is clean and locked */
39104e62a29SChristoph Lameter 	PAGE_CLEAN,
39204e62a29SChristoph Lameter } pageout_t;
39304e62a29SChristoph Lameter 
3941da177e4SLinus Torvalds /*
3951742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
3961742f19fSAndrew Morton  * Calls ->writepage().
3971da177e4SLinus Torvalds  */
398c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
3997d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
4001da177e4SLinus Torvalds {
4011da177e4SLinus Torvalds 	/*
4021da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
4031da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
4041da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
4051da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
4061da177e4SLinus Torvalds 	 * PagePrivate for that.
4071da177e4SLinus Torvalds 	 *
4086aceb53bSVincent Li 	 * If this process is currently in __generic_file_aio_write() against
4091da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
4101da177e4SLinus Torvalds 	 * will block.
4111da177e4SLinus Torvalds 	 *
4121da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
4131da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
4141da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
4151da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
4161da177e4SLinus Torvalds 	 */
4171da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
4181da177e4SLinus Torvalds 		return PAGE_KEEP;
4191da177e4SLinus Torvalds 	if (!mapping) {
4201da177e4SLinus Torvalds 		/*
4211da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
4221da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
4231da177e4SLinus Torvalds 		 */
424266cf658SDavid Howells 		if (page_has_private(page)) {
4251da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
4261da177e4SLinus Torvalds 				ClearPageDirty(page);
427d40cee24SHarvey Harrison 				printk("%s: orphaned page\n", __func__);
4281da177e4SLinus Torvalds 				return PAGE_CLEAN;
4291da177e4SLinus Torvalds 			}
4301da177e4SLinus Torvalds 		}
4311da177e4SLinus Torvalds 		return PAGE_KEEP;
4321da177e4SLinus Torvalds 	}
4331da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
4341da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
4350e093d99SMel Gorman 	if (!may_write_to_queue(mapping->backing_dev_info, sc))
4361da177e4SLinus Torvalds 		return PAGE_KEEP;
4371da177e4SLinus Torvalds 
4381da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
4391da177e4SLinus Torvalds 		int res;
4401da177e4SLinus Torvalds 		struct writeback_control wbc = {
4411da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
4421da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
443111ebb6eSOGAWA Hirofumi 			.range_start = 0,
444111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
4451da177e4SLinus Torvalds 			.for_reclaim = 1,
4461da177e4SLinus Torvalds 		};
4471da177e4SLinus Torvalds 
4481da177e4SLinus Torvalds 		SetPageReclaim(page);
4491da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
4501da177e4SLinus Torvalds 		if (res < 0)
4511da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
452994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
4531da177e4SLinus Torvalds 			ClearPageReclaim(page);
4541da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
4551da177e4SLinus Torvalds 		}
456c661b078SAndy Whitcroft 
4571da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
4581da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
4591da177e4SLinus Torvalds 			ClearPageReclaim(page);
4601da177e4SLinus Torvalds 		}
46123b9da55SMel Gorman 		trace_mm_vmscan_writepage(page, trace_reclaim_flags(page));
462e129b5c2SAndrew Morton 		inc_zone_page_state(page, NR_VMSCAN_WRITE);
4631da177e4SLinus Torvalds 		return PAGE_SUCCESS;
4641da177e4SLinus Torvalds 	}
4651da177e4SLinus Torvalds 
4661da177e4SLinus Torvalds 	return PAGE_CLEAN;
4671da177e4SLinus Torvalds }
4681da177e4SLinus Torvalds 
469a649fd92SAndrew Morton /*
470e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
471e286781dSNick Piggin  * gets returned with a refcount of 0.
472a649fd92SAndrew Morton  */
473e286781dSNick Piggin static int __remove_mapping(struct address_space *mapping, struct page *page)
47449d2e9ccSChristoph Lameter {
47528e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
47628e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
47749d2e9ccSChristoph Lameter 
47819fd6231SNick Piggin 	spin_lock_irq(&mapping->tree_lock);
47949d2e9ccSChristoph Lameter 	/*
4800fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
4810fd0e6b0SNick Piggin 	 *
4820fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
4830fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
4840fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
4850fd0e6b0SNick Piggin 	 * here, then the following race may occur:
4860fd0e6b0SNick Piggin 	 *
4870fd0e6b0SNick Piggin 	 * get_user_pages(&page);
4880fd0e6b0SNick Piggin 	 * [user mapping goes away]
4890fd0e6b0SNick Piggin 	 * write_to(page);
4900fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
4910fd0e6b0SNick Piggin 	 * SetPageDirty(page);
4920fd0e6b0SNick Piggin 	 * put_page(page);
4930fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
4940fd0e6b0SNick Piggin 	 *
4950fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
4960fd0e6b0SNick Piggin 	 *
4970fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
4980fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
4990fd0e6b0SNick Piggin 	 * load is not satisfied before that of page->_count.
5000fd0e6b0SNick Piggin 	 *
5010fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
5020fd0e6b0SNick Piggin 	 * and thus under tree_lock, then this ordering is not required.
50349d2e9ccSChristoph Lameter 	 */
504e286781dSNick Piggin 	if (!page_freeze_refs(page, 2))
50549d2e9ccSChristoph Lameter 		goto cannot_free;
506e286781dSNick Piggin 	/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
507e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
508e286781dSNick Piggin 		page_unfreeze_refs(page, 2);
50949d2e9ccSChristoph Lameter 		goto cannot_free;
510e286781dSNick Piggin 	}
51149d2e9ccSChristoph Lameter 
51249d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
51349d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
51449d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
51519fd6231SNick Piggin 		spin_unlock_irq(&mapping->tree_lock);
516cb4b86baSKAMEZAWA Hiroyuki 		swapcache_free(swap, page);
517e286781dSNick Piggin 	} else {
5186072d13cSLinus Torvalds 		void (*freepage)(struct page *);
5196072d13cSLinus Torvalds 
5206072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
5216072d13cSLinus Torvalds 
522e64a782fSMinchan Kim 		__delete_from_page_cache(page);
52319fd6231SNick Piggin 		spin_unlock_irq(&mapping->tree_lock);
524e767e056SDaisuke Nishimura 		mem_cgroup_uncharge_cache_page(page);
5256072d13cSLinus Torvalds 
5266072d13cSLinus Torvalds 		if (freepage != NULL)
5276072d13cSLinus Torvalds 			freepage(page);
528e286781dSNick Piggin 	}
529e286781dSNick Piggin 
53049d2e9ccSChristoph Lameter 	return 1;
53149d2e9ccSChristoph Lameter 
53249d2e9ccSChristoph Lameter cannot_free:
53319fd6231SNick Piggin 	spin_unlock_irq(&mapping->tree_lock);
53449d2e9ccSChristoph Lameter 	return 0;
53549d2e9ccSChristoph Lameter }
53649d2e9ccSChristoph Lameter 
5371da177e4SLinus Torvalds /*
538e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
539e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
540e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
541e286781dSNick Piggin  * this page.
542e286781dSNick Piggin  */
543e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
544e286781dSNick Piggin {
545e286781dSNick Piggin 	if (__remove_mapping(mapping, page)) {
546e286781dSNick Piggin 		/*
547e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
548e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
549e286781dSNick Piggin 		 * atomic operation.
550e286781dSNick Piggin 		 */
551e286781dSNick Piggin 		page_unfreeze_refs(page, 1);
552e286781dSNick Piggin 		return 1;
553e286781dSNick Piggin 	}
554e286781dSNick Piggin 	return 0;
555e286781dSNick Piggin }
556e286781dSNick Piggin 
557894bc310SLee Schermerhorn /**
558894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
559894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
560894bc310SLee Schermerhorn  *
561894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
562894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
563894bc310SLee Schermerhorn  *
564894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
565894bc310SLee Schermerhorn  */
566894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
567894bc310SLee Schermerhorn {
568894bc310SLee Schermerhorn 	int lru;
569bbfd28eeSLee Schermerhorn 	int was_unevictable = PageUnevictable(page);
570894bc310SLee Schermerhorn 
571894bc310SLee Schermerhorn 	VM_BUG_ON(PageLRU(page));
572894bc310SLee Schermerhorn 
573894bc310SLee Schermerhorn redo:
574894bc310SLee Schermerhorn 	ClearPageUnevictable(page);
575894bc310SLee Schermerhorn 
57639b5f29aSHugh Dickins 	if (page_evictable(page)) {
577894bc310SLee Schermerhorn 		/*
578894bc310SLee Schermerhorn 		 * For evictable pages, we can use the cache.
579894bc310SLee Schermerhorn 		 * In event of a race, worst case is we end up with an
580894bc310SLee Schermerhorn 		 * unevictable page on [in]active list.
581894bc310SLee Schermerhorn 		 * We know how to handle that.
582894bc310SLee Schermerhorn 		 */
583c53954a0SMel Gorman 		lru = page_lru_base_type(page);
584c53954a0SMel Gorman 		lru_cache_add(page);
585894bc310SLee Schermerhorn 	} else {
586894bc310SLee Schermerhorn 		/*
587894bc310SLee Schermerhorn 		 * Put unevictable pages directly on zone's unevictable
588894bc310SLee Schermerhorn 		 * list.
589894bc310SLee Schermerhorn 		 */
590894bc310SLee Schermerhorn 		lru = LRU_UNEVICTABLE;
591894bc310SLee Schermerhorn 		add_page_to_unevictable_list(page);
5926a7b9548SJohannes Weiner 		/*
59321ee9f39SMinchan Kim 		 * When racing with an mlock or AS_UNEVICTABLE clearing
59421ee9f39SMinchan Kim 		 * (page is unlocked) make sure that if the other thread
59521ee9f39SMinchan Kim 		 * does not observe our setting of PG_lru and fails
59624513264SHugh Dickins 		 * isolation/check_move_unevictable_pages,
59721ee9f39SMinchan Kim 		 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
5986a7b9548SJohannes Weiner 		 * the page back to the evictable list.
5996a7b9548SJohannes Weiner 		 *
60021ee9f39SMinchan Kim 		 * The other side is TestClearPageMlocked() or shmem_lock().
6016a7b9548SJohannes Weiner 		 */
6026a7b9548SJohannes Weiner 		smp_mb();
603894bc310SLee Schermerhorn 	}
604894bc310SLee Schermerhorn 
605894bc310SLee Schermerhorn 	/*
606894bc310SLee Schermerhorn 	 * page's status can change while we move it among lru. If an evictable
607894bc310SLee Schermerhorn 	 * page is on unevictable list, it never be freed. To avoid that,
608894bc310SLee Schermerhorn 	 * check after we added it to the list, again.
609894bc310SLee Schermerhorn 	 */
61039b5f29aSHugh Dickins 	if (lru == LRU_UNEVICTABLE && page_evictable(page)) {
611894bc310SLee Schermerhorn 		if (!isolate_lru_page(page)) {
612894bc310SLee Schermerhorn 			put_page(page);
613894bc310SLee Schermerhorn 			goto redo;
614894bc310SLee Schermerhorn 		}
615894bc310SLee Schermerhorn 		/* This means someone else dropped this page from LRU
616894bc310SLee Schermerhorn 		 * So, it will be freed or putback to LRU again. There is
617894bc310SLee Schermerhorn 		 * nothing to do here.
618894bc310SLee Schermerhorn 		 */
619894bc310SLee Schermerhorn 	}
620894bc310SLee Schermerhorn 
621bbfd28eeSLee Schermerhorn 	if (was_unevictable && lru != LRU_UNEVICTABLE)
622bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGRESCUED);
623bbfd28eeSLee Schermerhorn 	else if (!was_unevictable && lru == LRU_UNEVICTABLE)
624bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGCULLED);
625bbfd28eeSLee Schermerhorn 
626894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
627894bc310SLee Schermerhorn }
628894bc310SLee Schermerhorn 
629dfc8d636SJohannes Weiner enum page_references {
630dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
631dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
63264574746SJohannes Weiner 	PAGEREF_KEEP,
633dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
634dfc8d636SJohannes Weiner };
635dfc8d636SJohannes Weiner 
636dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
637dfc8d636SJohannes Weiner 						  struct scan_control *sc)
638dfc8d636SJohannes Weiner {
63964574746SJohannes Weiner 	int referenced_ptes, referenced_page;
640dfc8d636SJohannes Weiner 	unsigned long vm_flags;
641dfc8d636SJohannes Weiner 
642c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
643c3ac9a8aSJohannes Weiner 					  &vm_flags);
64464574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
645dfc8d636SJohannes Weiner 
646dfc8d636SJohannes Weiner 	/*
647dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
648dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
649dfc8d636SJohannes Weiner 	 */
650dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
651dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
652dfc8d636SJohannes Weiner 
65364574746SJohannes Weiner 	if (referenced_ptes) {
654e4898273SMichal Hocko 		if (PageSwapBacked(page))
65564574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
65664574746SJohannes Weiner 		/*
65764574746SJohannes Weiner 		 * All mapped pages start out with page table
65864574746SJohannes Weiner 		 * references from the instantiating fault, so we need
65964574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
66064574746SJohannes Weiner 		 * than once.
66164574746SJohannes Weiner 		 *
66264574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
66364574746SJohannes Weiner 		 * inactive list.  Another page table reference will
66464574746SJohannes Weiner 		 * lead to its activation.
66564574746SJohannes Weiner 		 *
66664574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
66764574746SJohannes Weiner 		 * so that recently deactivated but used pages are
66864574746SJohannes Weiner 		 * quickly recovered.
66964574746SJohannes Weiner 		 */
67064574746SJohannes Weiner 		SetPageReferenced(page);
67164574746SJohannes Weiner 
67234dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
673dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
674dfc8d636SJohannes Weiner 
675c909e993SKonstantin Khlebnikov 		/*
676c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
677c909e993SKonstantin Khlebnikov 		 */
678c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
679c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
680c909e993SKonstantin Khlebnikov 
68164574746SJohannes Weiner 		return PAGEREF_KEEP;
68264574746SJohannes Weiner 	}
68364574746SJohannes Weiner 
684dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
6852e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
686dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
68764574746SJohannes Weiner 
68864574746SJohannes Weiner 	return PAGEREF_RECLAIM;
689dfc8d636SJohannes Weiner }
690dfc8d636SJohannes Weiner 
691e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
692e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
693e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
694e2be15f6SMel Gorman {
695b4597226SMel Gorman 	struct address_space *mapping;
696b4597226SMel Gorman 
697e2be15f6SMel Gorman 	/*
698e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
699e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
700e2be15f6SMel Gorman 	 */
701e2be15f6SMel Gorman 	if (!page_is_file_cache(page)) {
702e2be15f6SMel Gorman 		*dirty = false;
703e2be15f6SMel Gorman 		*writeback = false;
704e2be15f6SMel Gorman 		return;
705e2be15f6SMel Gorman 	}
706e2be15f6SMel Gorman 
707e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
708e2be15f6SMel Gorman 	*dirty = PageDirty(page);
709e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
710b4597226SMel Gorman 
711b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
712b4597226SMel Gorman 	if (!page_has_private(page))
713b4597226SMel Gorman 		return;
714b4597226SMel Gorman 
715b4597226SMel Gorman 	mapping = page_mapping(page);
716b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
717b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
718e2be15f6SMel Gorman }
719e2be15f6SMel Gorman 
720e286781dSNick Piggin /*
7211742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
7221da177e4SLinus Torvalds  */
7231742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
7246a18adb3SKonstantin Khlebnikov 				      struct zone *zone,
725f84f6e2bSMel Gorman 				      struct scan_control *sc,
72602c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
7278e950282SMel Gorman 				      unsigned long *ret_nr_dirty,
728d43006d5SMel Gorman 				      unsigned long *ret_nr_unqueued_dirty,
7298e950282SMel Gorman 				      unsigned long *ret_nr_congested,
73002c6de8dSMinchan Kim 				      unsigned long *ret_nr_writeback,
731b1a6f21eSMel Gorman 				      unsigned long *ret_nr_immediate,
73202c6de8dSMinchan Kim 				      bool force_reclaim)
7331da177e4SLinus Torvalds {
7341da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
735abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
7361da177e4SLinus Torvalds 	int pgactivate = 0;
737d43006d5SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
7380e093d99SMel Gorman 	unsigned long nr_dirty = 0;
7390e093d99SMel Gorman 	unsigned long nr_congested = 0;
74005ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
74192df3a72SMel Gorman 	unsigned long nr_writeback = 0;
742b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
7431da177e4SLinus Torvalds 
7441da177e4SLinus Torvalds 	cond_resched();
7451da177e4SLinus Torvalds 
74669980e31STim Chen 	mem_cgroup_uncharge_start();
7471da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
7481da177e4SLinus Torvalds 		struct address_space *mapping;
7491da177e4SLinus Torvalds 		struct page *page;
7501da177e4SLinus Torvalds 		int may_enter_fs;
75102c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
752e2be15f6SMel Gorman 		bool dirty, writeback;
7531da177e4SLinus Torvalds 
7541da177e4SLinus Torvalds 		cond_resched();
7551da177e4SLinus Torvalds 
7561da177e4SLinus Torvalds 		page = lru_to_page(page_list);
7571da177e4SLinus Torvalds 		list_del(&page->lru);
7581da177e4SLinus Torvalds 
759529ae9aaSNick Piggin 		if (!trylock_page(page))
7601da177e4SLinus Torvalds 			goto keep;
7611da177e4SLinus Torvalds 
762725d704eSNick Piggin 		VM_BUG_ON(PageActive(page));
7636a18adb3SKonstantin Khlebnikov 		VM_BUG_ON(page_zone(page) != zone);
7641da177e4SLinus Torvalds 
7651da177e4SLinus Torvalds 		sc->nr_scanned++;
76680e43426SChristoph Lameter 
76739b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
768b291f000SNick Piggin 			goto cull_mlocked;
769894bc310SLee Schermerhorn 
770a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
77180e43426SChristoph Lameter 			goto keep_locked;
77280e43426SChristoph Lameter 
7731da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
7741da177e4SLinus Torvalds 		if (page_mapped(page) || PageSwapCache(page))
7751da177e4SLinus Torvalds 			sc->nr_scanned++;
7761da177e4SLinus Torvalds 
777c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
778c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
779c661b078SAndy Whitcroft 
780e62e384eSMichal Hocko 		/*
781e2be15f6SMel Gorman 		 * The number of dirty pages determines if a zone is marked
782e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
783e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
784e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
785e2be15f6SMel Gorman 		 */
786e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
787e2be15f6SMel Gorman 		if (dirty || writeback)
788e2be15f6SMel Gorman 			nr_dirty++;
789e2be15f6SMel Gorman 
790e2be15f6SMel Gorman 		if (dirty && !writeback)
791e2be15f6SMel Gorman 			nr_unqueued_dirty++;
792e2be15f6SMel Gorman 
793d04e8acdSMel Gorman 		/*
794d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
795d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
796d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
797d04e8acdSMel Gorman 		 * end of the LRU a second time.
798d04e8acdSMel Gorman 		 */
799e2be15f6SMel Gorman 		mapping = page_mapping(page);
800d04e8acdSMel Gorman 		if ((mapping && bdi_write_congested(mapping->backing_dev_info)) ||
801d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
802e2be15f6SMel Gorman 			nr_congested++;
803e2be15f6SMel Gorman 
804e2be15f6SMel Gorman 		/*
805283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
806283aba9fSMel Gorman 		 * are three cases to consider.
807e62e384eSMichal Hocko 		 *
808283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
809283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
810283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
811283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
812283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
813283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
814283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
815b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
816b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
817c3b94f44SHugh Dickins 		 *
818283aba9fSMel Gorman 		 * 2) Global reclaim encounters a page, memcg encounters a
819283aba9fSMel Gorman 		 *    page that is not marked for immediate reclaim or
820283aba9fSMel Gorman 		 *    the caller does not have __GFP_IO. In this case mark
821283aba9fSMel Gorman 		 *    the page for immediate reclaim and continue scanning.
822283aba9fSMel Gorman 		 *
823283aba9fSMel Gorman 		 *    __GFP_IO is checked  because a loop driver thread might
824283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
825283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
826283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
827283aba9fSMel Gorman 		 *    would probably show more reasons.
828283aba9fSMel Gorman 		 *
829283aba9fSMel Gorman 		 *    Don't require __GFP_FS, since we're not going into the
830283aba9fSMel Gorman 		 *    FS, just waiting on its writeback completion. Worryingly,
831283aba9fSMel Gorman 		 *    ext4 gfs2 and xfs allocate pages with
832283aba9fSMel Gorman 		 *    grab_cache_page_write_begin(,,AOP_FLAG_NOFS), so testing
833283aba9fSMel Gorman 		 *    may_enter_fs here is liable to OOM on them.
834283aba9fSMel Gorman 		 *
835283aba9fSMel Gorman 		 * 3) memcg encounters a page that is not already marked
836283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
837283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
838283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
839283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
840e62e384eSMichal Hocko 		 */
841283aba9fSMel Gorman 		if (PageWriteback(page)) {
842283aba9fSMel Gorman 			/* Case 1 above */
843283aba9fSMel Gorman 			if (current_is_kswapd() &&
844283aba9fSMel Gorman 			    PageReclaim(page) &&
845283aba9fSMel Gorman 			    zone_is_reclaim_writeback(zone)) {
846b1a6f21eSMel Gorman 				nr_immediate++;
847b1a6f21eSMel Gorman 				goto keep_locked;
848283aba9fSMel Gorman 
849283aba9fSMel Gorman 			/* Case 2 above */
850283aba9fSMel Gorman 			} else if (global_reclaim(sc) ||
851c3b94f44SHugh Dickins 			    !PageReclaim(page) || !(sc->gfp_mask & __GFP_IO)) {
852c3b94f44SHugh Dickins 				/*
853c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
854c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
855c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
856c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
857c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
858c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
859c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
860c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
861c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
862c3b94f44SHugh Dickins 				 */
863c3b94f44SHugh Dickins 				SetPageReclaim(page);
86492df3a72SMel Gorman 				nr_writeback++;
865283aba9fSMel Gorman 
866c3b94f44SHugh Dickins 				goto keep_locked;
867283aba9fSMel Gorman 
868283aba9fSMel Gorman 			/* Case 3 above */
869283aba9fSMel Gorman 			} else {
870c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
871e62e384eSMichal Hocko 			}
872283aba9fSMel Gorman 		}
8731da177e4SLinus Torvalds 
87402c6de8dSMinchan Kim 		if (!force_reclaim)
8756a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
87602c6de8dSMinchan Kim 
877dfc8d636SJohannes Weiner 		switch (references) {
878dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
8791da177e4SLinus Torvalds 			goto activate_locked;
88064574746SJohannes Weiner 		case PAGEREF_KEEP:
88164574746SJohannes Weiner 			goto keep_locked;
882dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
883dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
884dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
885dfc8d636SJohannes Weiner 		}
8861da177e4SLinus Torvalds 
8871da177e4SLinus Torvalds 		/*
8881da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
8891da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
8901da177e4SLinus Torvalds 		 */
891b291f000SNick Piggin 		if (PageAnon(page) && !PageSwapCache(page)) {
89263eb6b93SHugh Dickins 			if (!(sc->gfp_mask & __GFP_IO))
89363eb6b93SHugh Dickins 				goto keep_locked;
8945bc7b8acSShaohua Li 			if (!add_to_swap(page, page_list))
8951da177e4SLinus Torvalds 				goto activate_locked;
89663eb6b93SHugh Dickins 			may_enter_fs = 1;
8971da177e4SLinus Torvalds 
898e2be15f6SMel Gorman 			/* Adding to swap updated mapping */
8991da177e4SLinus Torvalds 			mapping = page_mapping(page);
900e2be15f6SMel Gorman 		}
9011da177e4SLinus Torvalds 
9021da177e4SLinus Torvalds 		/*
9031da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
9041da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
9051da177e4SLinus Torvalds 		 */
9061da177e4SLinus Torvalds 		if (page_mapped(page) && mapping) {
90702c6de8dSMinchan Kim 			switch (try_to_unmap(page, ttu_flags)) {
9081da177e4SLinus Torvalds 			case SWAP_FAIL:
9091da177e4SLinus Torvalds 				goto activate_locked;
9101da177e4SLinus Torvalds 			case SWAP_AGAIN:
9111da177e4SLinus Torvalds 				goto keep_locked;
912b291f000SNick Piggin 			case SWAP_MLOCK:
913b291f000SNick Piggin 				goto cull_mlocked;
9141da177e4SLinus Torvalds 			case SWAP_SUCCESS:
9151da177e4SLinus Torvalds 				; /* try to free the page below */
9161da177e4SLinus Torvalds 			}
9171da177e4SLinus Torvalds 		}
9181da177e4SLinus Torvalds 
9191da177e4SLinus Torvalds 		if (PageDirty(page)) {
920ee72886dSMel Gorman 			/*
921ee72886dSMel Gorman 			 * Only kswapd can writeback filesystem pages to
922d43006d5SMel Gorman 			 * avoid risk of stack overflow but only writeback
923d43006d5SMel Gorman 			 * if many dirty pages have been encountered.
924ee72886dSMel Gorman 			 */
925f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
9269e3b2f8cSKonstantin Khlebnikov 					(!current_is_kswapd() ||
927d43006d5SMel Gorman 					 !zone_is_reclaim_dirty(zone))) {
92849ea7eb6SMel Gorman 				/*
92949ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
93049ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
93149ea7eb6SMel Gorman 				 * except we already have the page isolated
93249ea7eb6SMel Gorman 				 * and know it's dirty
93349ea7eb6SMel Gorman 				 */
93449ea7eb6SMel Gorman 				inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE);
93549ea7eb6SMel Gorman 				SetPageReclaim(page);
93649ea7eb6SMel Gorman 
937ee72886dSMel Gorman 				goto keep_locked;
938ee72886dSMel Gorman 			}
939ee72886dSMel Gorman 
940dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
9411da177e4SLinus Torvalds 				goto keep_locked;
9424dd4b920SAndrew Morton 			if (!may_enter_fs)
9431da177e4SLinus Torvalds 				goto keep_locked;
94452a8363eSChristoph Lameter 			if (!sc->may_writepage)
9451da177e4SLinus Torvalds 				goto keep_locked;
9461da177e4SLinus Torvalds 
9471da177e4SLinus Torvalds 			/* Page is dirty, try to write it out here */
9487d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
9491da177e4SLinus Torvalds 			case PAGE_KEEP:
9501da177e4SLinus Torvalds 				goto keep_locked;
9511da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
9521da177e4SLinus Torvalds 				goto activate_locked;
9531da177e4SLinus Torvalds 			case PAGE_SUCCESS:
9547d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
95541ac1999SMel Gorman 					goto keep;
9567d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
9571da177e4SLinus Torvalds 					goto keep;
9587d3579e8SKOSAKI Motohiro 
9591da177e4SLinus Torvalds 				/*
9601da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
9611da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
9621da177e4SLinus Torvalds 				 */
963529ae9aaSNick Piggin 				if (!trylock_page(page))
9641da177e4SLinus Torvalds 					goto keep;
9651da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
9661da177e4SLinus Torvalds 					goto keep_locked;
9671da177e4SLinus Torvalds 				mapping = page_mapping(page);
9681da177e4SLinus Torvalds 			case PAGE_CLEAN:
9691da177e4SLinus Torvalds 				; /* try to free the page below */
9701da177e4SLinus Torvalds 			}
9711da177e4SLinus Torvalds 		}
9721da177e4SLinus Torvalds 
9731da177e4SLinus Torvalds 		/*
9741da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
9751da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
9761da177e4SLinus Torvalds 		 * the page as well.
9771da177e4SLinus Torvalds 		 *
9781da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
9791da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
9801da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
9811da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
9821da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
9831da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
9841da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
9851da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
9861da177e4SLinus Torvalds 		 *
9871da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
9881da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
9891da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
9901da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
9911da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
9921da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
9931da177e4SLinus Torvalds 		 */
994266cf658SDavid Howells 		if (page_has_private(page)) {
9951da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
9961da177e4SLinus Torvalds 				goto activate_locked;
997e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
998e286781dSNick Piggin 				unlock_page(page);
999e286781dSNick Piggin 				if (put_page_testzero(page))
10001da177e4SLinus Torvalds 					goto free_it;
1001e286781dSNick Piggin 				else {
1002e286781dSNick Piggin 					/*
1003e286781dSNick Piggin 					 * rare race with speculative reference.
1004e286781dSNick Piggin 					 * the speculative reference will free
1005e286781dSNick Piggin 					 * this page shortly, so we may
1006e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1007e286781dSNick Piggin 					 * leave it off the LRU).
1008e286781dSNick Piggin 					 */
1009e286781dSNick Piggin 					nr_reclaimed++;
1010e286781dSNick Piggin 					continue;
1011e286781dSNick Piggin 				}
1012e286781dSNick Piggin 			}
10131da177e4SLinus Torvalds 		}
10141da177e4SLinus Torvalds 
1015e286781dSNick Piggin 		if (!mapping || !__remove_mapping(mapping, page))
101649d2e9ccSChristoph Lameter 			goto keep_locked;
10171da177e4SLinus Torvalds 
1018a978d6f5SNick Piggin 		/*
1019a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
1020a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
1021a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
1022a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
1023a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
1024a978d6f5SNick Piggin 		 */
1025a978d6f5SNick Piggin 		__clear_page_locked(page);
1026e286781dSNick Piggin free_it:
102705ff5137SAndrew Morton 		nr_reclaimed++;
1028abe4c3b5SMel Gorman 
1029abe4c3b5SMel Gorman 		/*
1030abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1031abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1032abe4c3b5SMel Gorman 		 */
1033abe4c3b5SMel Gorman 		list_add(&page->lru, &free_pages);
10341da177e4SLinus Torvalds 		continue;
10351da177e4SLinus Torvalds 
1036b291f000SNick Piggin cull_mlocked:
103763d6c5adSHugh Dickins 		if (PageSwapCache(page))
103863d6c5adSHugh Dickins 			try_to_free_swap(page);
1039b291f000SNick Piggin 		unlock_page(page);
1040b291f000SNick Piggin 		putback_lru_page(page);
1041b291f000SNick Piggin 		continue;
1042b291f000SNick Piggin 
10431da177e4SLinus Torvalds activate_locked:
104468a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
104568a22394SRik van Riel 		if (PageSwapCache(page) && vm_swap_full())
1046a2c43eedSHugh Dickins 			try_to_free_swap(page);
1047894bc310SLee Schermerhorn 		VM_BUG_ON(PageActive(page));
10481da177e4SLinus Torvalds 		SetPageActive(page);
10491da177e4SLinus Torvalds 		pgactivate++;
10501da177e4SLinus Torvalds keep_locked:
10511da177e4SLinus Torvalds 		unlock_page(page);
10521da177e4SLinus Torvalds keep:
10531da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1054b291f000SNick Piggin 		VM_BUG_ON(PageLRU(page) || PageUnevictable(page));
10551da177e4SLinus Torvalds 	}
1056abe4c3b5SMel Gorman 
1057cc59850eSKonstantin Khlebnikov 	free_hot_cold_page_list(&free_pages, 1);
1058abe4c3b5SMel Gorman 
10591da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1060f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
106169980e31STim Chen 	mem_cgroup_uncharge_end();
10628e950282SMel Gorman 	*ret_nr_dirty += nr_dirty;
10638e950282SMel Gorman 	*ret_nr_congested += nr_congested;
1064d43006d5SMel Gorman 	*ret_nr_unqueued_dirty += nr_unqueued_dirty;
106592df3a72SMel Gorman 	*ret_nr_writeback += nr_writeback;
1066b1a6f21eSMel Gorman 	*ret_nr_immediate += nr_immediate;
106705ff5137SAndrew Morton 	return nr_reclaimed;
10681da177e4SLinus Torvalds }
10691da177e4SLinus Torvalds 
107002c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
107102c6de8dSMinchan Kim 					    struct list_head *page_list)
107202c6de8dSMinchan Kim {
107302c6de8dSMinchan Kim 	struct scan_control sc = {
107402c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
107502c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
107602c6de8dSMinchan Kim 		.may_unmap = 1,
107702c6de8dSMinchan Kim 	};
10788e950282SMel Gorman 	unsigned long ret, dummy1, dummy2, dummy3, dummy4, dummy5;
107902c6de8dSMinchan Kim 	struct page *page, *next;
108002c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
108102c6de8dSMinchan Kim 
108202c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
108302c6de8dSMinchan Kim 		if (page_is_file_cache(page) && !PageDirty(page)) {
108402c6de8dSMinchan Kim 			ClearPageActive(page);
108502c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
108602c6de8dSMinchan Kim 		}
108702c6de8dSMinchan Kim 	}
108802c6de8dSMinchan Kim 
108902c6de8dSMinchan Kim 	ret = shrink_page_list(&clean_pages, zone, &sc,
109002c6de8dSMinchan Kim 			TTU_UNMAP|TTU_IGNORE_ACCESS,
10918e950282SMel Gorman 			&dummy1, &dummy2, &dummy3, &dummy4, &dummy5, true);
109202c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
109302c6de8dSMinchan Kim 	__mod_zone_page_state(zone, NR_ISOLATED_FILE, -ret);
109402c6de8dSMinchan Kim 	return ret;
109502c6de8dSMinchan Kim }
109602c6de8dSMinchan Kim 
10975ad333ebSAndy Whitcroft /*
10985ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
10995ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
11005ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
11015ad333ebSAndy Whitcroft  *
11025ad333ebSAndy Whitcroft  * page:	page to consider
11035ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
11045ad333ebSAndy Whitcroft  *
11055ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
11065ad333ebSAndy Whitcroft  */
1107f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
11085ad333ebSAndy Whitcroft {
11095ad333ebSAndy Whitcroft 	int ret = -EINVAL;
11105ad333ebSAndy Whitcroft 
11115ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
11125ad333ebSAndy Whitcroft 	if (!PageLRU(page))
11135ad333ebSAndy Whitcroft 		return ret;
11145ad333ebSAndy Whitcroft 
1115e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1116e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1117894bc310SLee Schermerhorn 		return ret;
1118894bc310SLee Schermerhorn 
11195ad333ebSAndy Whitcroft 	ret = -EBUSY;
112008e552c6SKAMEZAWA Hiroyuki 
1121c8244935SMel Gorman 	/*
1122c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1123c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1124c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1125c8244935SMel Gorman 	 *
1126c8244935SMel Gorman 	 * ISOLATE_CLEAN means that only clean pages should be isolated. This
1127c8244935SMel Gorman 	 * is used by reclaim when it is cannot write to backing storage
1128c8244935SMel Gorman 	 *
1129c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1130c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1131c8244935SMel Gorman 	 */
1132c8244935SMel Gorman 	if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
1133c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1134c8244935SMel Gorman 		if (PageWriteback(page))
113539deaf85SMinchan Kim 			return ret;
113639deaf85SMinchan Kim 
1137c8244935SMel Gorman 		if (PageDirty(page)) {
1138c8244935SMel Gorman 			struct address_space *mapping;
1139c8244935SMel Gorman 
1140c8244935SMel Gorman 			/* ISOLATE_CLEAN means only clean pages */
1141c8244935SMel Gorman 			if (mode & ISOLATE_CLEAN)
1142c8244935SMel Gorman 				return ret;
1143c8244935SMel Gorman 
1144c8244935SMel Gorman 			/*
1145c8244935SMel Gorman 			 * Only pages without mappings or that have a
1146c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
1147c8244935SMel Gorman 			 * without blocking
1148c8244935SMel Gorman 			 */
1149c8244935SMel Gorman 			mapping = page_mapping(page);
1150c8244935SMel Gorman 			if (mapping && !mapping->a_ops->migratepage)
1151c8244935SMel Gorman 				return ret;
1152c8244935SMel Gorman 		}
1153c8244935SMel Gorman 	}
1154c8244935SMel Gorman 
1155f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1156f80c0673SMinchan Kim 		return ret;
1157f80c0673SMinchan Kim 
11585ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
11595ad333ebSAndy Whitcroft 		/*
11605ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
11615ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
11625ad333ebSAndy Whitcroft 		 * page release code relies on it.
11635ad333ebSAndy Whitcroft 		 */
11645ad333ebSAndy Whitcroft 		ClearPageLRU(page);
11655ad333ebSAndy Whitcroft 		ret = 0;
11665ad333ebSAndy Whitcroft 	}
11675ad333ebSAndy Whitcroft 
11685ad333ebSAndy Whitcroft 	return ret;
11695ad333ebSAndy Whitcroft }
11705ad333ebSAndy Whitcroft 
117149d2e9ccSChristoph Lameter /*
11721da177e4SLinus Torvalds  * zone->lru_lock is heavily contended.  Some of the functions that
11731da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
11741da177e4SLinus Torvalds  * and working on them outside the LRU lock.
11751da177e4SLinus Torvalds  *
11761da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
11771da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
11781da177e4SLinus Torvalds  *
11791da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
11801da177e4SLinus Torvalds  *
11811da177e4SLinus Torvalds  * @nr_to_scan:	The number of pages to look through on the list.
11825dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
11831da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1184f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1185fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
11865ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
11873cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
11881da177e4SLinus Torvalds  *
11891da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
11901da177e4SLinus Torvalds  */
119169e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
11925dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1193fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
11943cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
11951da177e4SLinus Torvalds {
119675b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
119769e05944SAndrew Morton 	unsigned long nr_taken = 0;
1198c9b02d97SWu Fengguang 	unsigned long scan;
11991da177e4SLinus Torvalds 
1200c9b02d97SWu Fengguang 	for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
12015ad333ebSAndy Whitcroft 		struct page *page;
1202fa9add64SHugh Dickins 		int nr_pages;
12035ad333ebSAndy Whitcroft 
12041da177e4SLinus Torvalds 		page = lru_to_page(src);
12051da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
12061da177e4SLinus Torvalds 
1207725d704eSNick Piggin 		VM_BUG_ON(!PageLRU(page));
12088d438f96SNick Piggin 
1209f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
12105ad333ebSAndy Whitcroft 		case 0:
1211fa9add64SHugh Dickins 			nr_pages = hpage_nr_pages(page);
1212fa9add64SHugh Dickins 			mem_cgroup_update_lru_size(lruvec, lru, -nr_pages);
12135ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
1214fa9add64SHugh Dickins 			nr_taken += nr_pages;
12155ad333ebSAndy Whitcroft 			break;
12167c8ee9a8SNick Piggin 
12175ad333ebSAndy Whitcroft 		case -EBUSY:
12185ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
12195ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
12205ad333ebSAndy Whitcroft 			continue;
12215ad333ebSAndy Whitcroft 
12225ad333ebSAndy Whitcroft 		default:
12235ad333ebSAndy Whitcroft 			BUG();
12245ad333ebSAndy Whitcroft 		}
12255ad333ebSAndy Whitcroft 	}
12261da177e4SLinus Torvalds 
1227f626012dSHugh Dickins 	*nr_scanned = scan;
122875b00af7SHugh Dickins 	trace_mm_vmscan_lru_isolate(sc->order, nr_to_scan, scan,
122975b00af7SHugh Dickins 				    nr_taken, mode, is_file_lru(lru));
12301da177e4SLinus Torvalds 	return nr_taken;
12311da177e4SLinus Torvalds }
12321da177e4SLinus Torvalds 
123362695a84SNick Piggin /**
123462695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
123562695a84SNick Piggin  * @page: page to isolate from its LRU list
123662695a84SNick Piggin  *
123762695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
123862695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
123962695a84SNick Piggin  *
124062695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
124162695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
124262695a84SNick Piggin  *
124362695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1244894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1245894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1246894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
124762695a84SNick Piggin  *
124862695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
124962695a84SNick Piggin  * found will be decremented.
125062695a84SNick Piggin  *
125162695a84SNick Piggin  * Restrictions:
125262695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
125362695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
125462695a84SNick Piggin  *     without a stable reference).
125562695a84SNick Piggin  * (2) the lru_lock must not be held.
125662695a84SNick Piggin  * (3) interrupts must be enabled.
125762695a84SNick Piggin  */
125862695a84SNick Piggin int isolate_lru_page(struct page *page)
125962695a84SNick Piggin {
126062695a84SNick Piggin 	int ret = -EBUSY;
126162695a84SNick Piggin 
12620c917313SKonstantin Khlebnikov 	VM_BUG_ON(!page_count(page));
12630c917313SKonstantin Khlebnikov 
126462695a84SNick Piggin 	if (PageLRU(page)) {
126562695a84SNick Piggin 		struct zone *zone = page_zone(page);
1266fa9add64SHugh Dickins 		struct lruvec *lruvec;
126762695a84SNick Piggin 
126862695a84SNick Piggin 		spin_lock_irq(&zone->lru_lock);
1269fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
12700c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1271894bc310SLee Schermerhorn 			int lru = page_lru(page);
12720c917313SKonstantin Khlebnikov 			get_page(page);
127362695a84SNick Piggin 			ClearPageLRU(page);
1274fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1275fa9add64SHugh Dickins 			ret = 0;
127662695a84SNick Piggin 		}
127762695a84SNick Piggin 		spin_unlock_irq(&zone->lru_lock);
127862695a84SNick Piggin 	}
127962695a84SNick Piggin 	return ret;
128062695a84SNick Piggin }
128162695a84SNick Piggin 
12825ad333ebSAndy Whitcroft /*
1283d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1284d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1285d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1286d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1287d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
128835cd7815SRik van Riel  */
128935cd7815SRik van Riel static int too_many_isolated(struct zone *zone, int file,
129035cd7815SRik van Riel 		struct scan_control *sc)
129135cd7815SRik van Riel {
129235cd7815SRik van Riel 	unsigned long inactive, isolated;
129335cd7815SRik van Riel 
129435cd7815SRik van Riel 	if (current_is_kswapd())
129535cd7815SRik van Riel 		return 0;
129635cd7815SRik van Riel 
129789b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
129835cd7815SRik van Riel 		return 0;
129935cd7815SRik van Riel 
130035cd7815SRik van Riel 	if (file) {
130135cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_FILE);
130235cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_FILE);
130335cd7815SRik van Riel 	} else {
130435cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_ANON);
130535cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_ANON);
130635cd7815SRik van Riel 	}
130735cd7815SRik van Riel 
13083cf23841SFengguang Wu 	/*
13093cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
13103cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
13113cf23841SFengguang Wu 	 * deadlock.
13123cf23841SFengguang Wu 	 */
13133cf23841SFengguang Wu 	if ((sc->gfp_mask & GFP_IOFS) == GFP_IOFS)
13143cf23841SFengguang Wu 		inactive >>= 3;
13153cf23841SFengguang Wu 
131635cd7815SRik van Riel 	return isolated > inactive;
131735cd7815SRik van Riel }
131835cd7815SRik van Riel 
131966635629SMel Gorman static noinline_for_stack void
132075b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
132166635629SMel Gorman {
132227ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
132327ac81d8SKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
13243f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
132566635629SMel Gorman 
132666635629SMel Gorman 	/*
132766635629SMel Gorman 	 * Put back any unfreeable pages.
132866635629SMel Gorman 	 */
132966635629SMel Gorman 	while (!list_empty(page_list)) {
13303f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
133166635629SMel Gorman 		int lru;
13323f79768fSHugh Dickins 
133366635629SMel Gorman 		VM_BUG_ON(PageLRU(page));
133466635629SMel Gorman 		list_del(&page->lru);
133539b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
133666635629SMel Gorman 			spin_unlock_irq(&zone->lru_lock);
133766635629SMel Gorman 			putback_lru_page(page);
133866635629SMel Gorman 			spin_lock_irq(&zone->lru_lock);
133966635629SMel Gorman 			continue;
134066635629SMel Gorman 		}
1341fa9add64SHugh Dickins 
1342fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
1343fa9add64SHugh Dickins 
13447a608572SLinus Torvalds 		SetPageLRU(page);
134566635629SMel Gorman 		lru = page_lru(page);
1346fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1347fa9add64SHugh Dickins 
134866635629SMel Gorman 		if (is_active_lru(lru)) {
134966635629SMel Gorman 			int file = is_file_lru(lru);
13509992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
13519992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
135266635629SMel Gorman 		}
13532bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
13542bcf8879SHugh Dickins 			__ClearPageLRU(page);
13552bcf8879SHugh Dickins 			__ClearPageActive(page);
1356fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
13572bcf8879SHugh Dickins 
13582bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
135966635629SMel Gorman 				spin_unlock_irq(&zone->lru_lock);
13602bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
136166635629SMel Gorman 				spin_lock_irq(&zone->lru_lock);
13622bcf8879SHugh Dickins 			} else
13632bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
136466635629SMel Gorman 		}
136566635629SMel Gorman 	}
136666635629SMel Gorman 
13673f79768fSHugh Dickins 	/*
13683f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
13693f79768fSHugh Dickins 	 */
13703f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
137166635629SMel Gorman }
137266635629SMel Gorman 
137366635629SMel Gorman /*
13741742f19fSAndrew Morton  * shrink_inactive_list() is a helper for shrink_zone().  It returns the number
13751742f19fSAndrew Morton  * of reclaimed pages
13761da177e4SLinus Torvalds  */
137766635629SMel Gorman static noinline_for_stack unsigned long
13781a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
13799e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
13801da177e4SLinus Torvalds {
13811da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1382e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
138305ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1384e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
13858e950282SMel Gorman 	unsigned long nr_dirty = 0;
13868e950282SMel Gorman 	unsigned long nr_congested = 0;
1387e2be15f6SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
138892df3a72SMel Gorman 	unsigned long nr_writeback = 0;
1389b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
1390f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
13913cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
13921a93be0eSKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
13931a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
139478dc583dSKOSAKI Motohiro 
139535cd7815SRik van Riel 	while (unlikely(too_many_isolated(zone, file, sc))) {
139658355c78SKOSAKI Motohiro 		congestion_wait(BLK_RW_ASYNC, HZ/10);
139735cd7815SRik van Riel 
139835cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
139935cd7815SRik van Riel 		if (fatal_signal_pending(current))
140035cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
140135cd7815SRik van Riel 	}
140235cd7815SRik van Riel 
14031da177e4SLinus Torvalds 	lru_add_drain();
1404f80c0673SMinchan Kim 
1405f80c0673SMinchan Kim 	if (!sc->may_unmap)
140661317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1407f80c0673SMinchan Kim 	if (!sc->may_writepage)
140861317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1409f80c0673SMinchan Kim 
14101da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
14111da177e4SLinus Torvalds 
14125dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
14135dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
141495d918fcSKonstantin Khlebnikov 
141595d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
141695d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
141795d918fcSKonstantin Khlebnikov 
141889b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
1419e247dbceSKOSAKI Motohiro 		zone->pages_scanned += nr_scanned;
1420b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
142175b00af7SHugh Dickins 			__count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scanned);
1422b35ea17bSKOSAKI Motohiro 		else
142375b00af7SHugh Dickins 			__count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scanned);
1424b35ea17bSKOSAKI Motohiro 	}
142566635629SMel Gorman 	spin_unlock_irq(&zone->lru_lock);
1426d563c050SHillf Danton 
1427d563c050SHillf Danton 	if (nr_taken == 0)
142866635629SMel Gorman 		return 0;
1429b35ea17bSKOSAKI Motohiro 
143002c6de8dSMinchan Kim 	nr_reclaimed = shrink_page_list(&page_list, zone, sc, TTU_UNMAP,
14318e950282SMel Gorman 				&nr_dirty, &nr_unqueued_dirty, &nr_congested,
14328e950282SMel Gorman 				&nr_writeback, &nr_immediate,
1433b1a6f21eSMel Gorman 				false);
1434c661b078SAndy Whitcroft 
14353f79768fSHugh Dickins 	spin_lock_irq(&zone->lru_lock);
14363f79768fSHugh Dickins 
143795d918fcSKonstantin Khlebnikov 	reclaim_stat->recent_scanned[file] += nr_taken;
1438d563c050SHillf Danton 
1439904249aaSYing Han 	if (global_reclaim(sc)) {
1440b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1441904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_KSWAPD, zone,
1442904249aaSYing Han 					       nr_reclaimed);
1443904249aaSYing Han 		else
1444904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_DIRECT, zone,
1445904249aaSYing Han 					       nr_reclaimed);
1446904249aaSYing Han 	}
1447a74609faSNick Piggin 
144827ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
14493f79768fSHugh Dickins 
145095d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
14513f79768fSHugh Dickins 
14523f79768fSHugh Dickins 	spin_unlock_irq(&zone->lru_lock);
14533f79768fSHugh Dickins 
14543f79768fSHugh Dickins 	free_hot_cold_page_list(&page_list, 1);
1455e11da5b4SMel Gorman 
145692df3a72SMel Gorman 	/*
145792df3a72SMel Gorman 	 * If reclaim is isolating dirty pages under writeback, it implies
145892df3a72SMel Gorman 	 * that the long-lived page allocation rate is exceeding the page
145992df3a72SMel Gorman 	 * laundering rate. Either the global limits are not being effective
146092df3a72SMel Gorman 	 * at throttling processes due to the page distribution throughout
146192df3a72SMel Gorman 	 * zones or there is heavy usage of a slow backing device. The
146292df3a72SMel Gorman 	 * only option is to throttle from reclaim context which is not ideal
146392df3a72SMel Gorman 	 * as there is no guarantee the dirtying process is throttled in the
146492df3a72SMel Gorman 	 * same way balance_dirty_pages() manages.
146592df3a72SMel Gorman 	 *
14668e950282SMel Gorman 	 * Once a zone is flagged ZONE_WRITEBACK, kswapd will count the number
14678e950282SMel Gorman 	 * of pages under pages flagged for immediate reclaim and stall if any
14688e950282SMel Gorman 	 * are encountered in the nr_immediate check below.
146992df3a72SMel Gorman 	 */
1470918fc718SMel Gorman 	if (nr_writeback && nr_writeback == nr_taken)
1471283aba9fSMel Gorman 		zone_set_flag(zone, ZONE_WRITEBACK);
147292df3a72SMel Gorman 
1473d43006d5SMel Gorman 	/*
1474b1a6f21eSMel Gorman 	 * memcg will stall in page writeback so only consider forcibly
1475b1a6f21eSMel Gorman 	 * stalling for global reclaim
1476d43006d5SMel Gorman 	 */
1477b1a6f21eSMel Gorman 	if (global_reclaim(sc)) {
1478b1a6f21eSMel Gorman 		/*
14798e950282SMel Gorman 		 * Tag a zone as congested if all the dirty pages scanned were
14808e950282SMel Gorman 		 * backed by a congested BDI and wait_iff_congested will stall.
14818e950282SMel Gorman 		 */
14828e950282SMel Gorman 		if (nr_dirty && nr_dirty == nr_congested)
14838e950282SMel Gorman 			zone_set_flag(zone, ZONE_CONGESTED);
14848e950282SMel Gorman 
14858e950282SMel Gorman 		/*
1486b1a6f21eSMel Gorman 		 * If dirty pages are scanned that are not queued for IO, it
1487b1a6f21eSMel Gorman 		 * implies that flushers are not keeping up. In this case, flag
1488b1a6f21eSMel Gorman 		 * the zone ZONE_TAIL_LRU_DIRTY and kswapd will start writing
1489b1a6f21eSMel Gorman 		 * pages from reclaim context. It will forcibly stall in the
1490b1a6f21eSMel Gorman 		 * next check.
1491b1a6f21eSMel Gorman 		 */
1492b1a6f21eSMel Gorman 		if (nr_unqueued_dirty == nr_taken)
1493d43006d5SMel Gorman 			zone_set_flag(zone, ZONE_TAIL_LRU_DIRTY);
1494b1a6f21eSMel Gorman 
1495b1a6f21eSMel Gorman 		/*
1496b1a6f21eSMel Gorman 		 * In addition, if kswapd scans pages marked marked for
1497b1a6f21eSMel Gorman 		 * immediate reclaim and under writeback (nr_immediate), it
1498b1a6f21eSMel Gorman 		 * implies that pages are cycling through the LRU faster than
1499b1a6f21eSMel Gorman 		 * they are written so also forcibly stall.
1500b1a6f21eSMel Gorman 		 */
1501b1a6f21eSMel Gorman 		if (nr_unqueued_dirty == nr_taken || nr_immediate)
1502b1a6f21eSMel Gorman 			congestion_wait(BLK_RW_ASYNC, HZ/10);
1503e2be15f6SMel Gorman 	}
1504d43006d5SMel Gorman 
15058e950282SMel Gorman 	/*
15068e950282SMel Gorman 	 * Stall direct reclaim for IO completions if underlying BDIs or zone
15078e950282SMel Gorman 	 * is congested. Allow kswapd to continue until it starts encountering
15088e950282SMel Gorman 	 * unqueued dirty pages or cycling through the LRU too quickly.
15098e950282SMel Gorman 	 */
15108e950282SMel Gorman 	if (!sc->hibernation_mode && !current_is_kswapd())
15118e950282SMel Gorman 		wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10);
15128e950282SMel Gorman 
1513e11da5b4SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(zone->zone_pgdat->node_id,
1514e11da5b4SMel Gorman 		zone_idx(zone),
1515e11da5b4SMel Gorman 		nr_scanned, nr_reclaimed,
15169e3b2f8cSKonstantin Khlebnikov 		sc->priority,
151723b9da55SMel Gorman 		trace_shrink_flags(file));
151805ff5137SAndrew Morton 	return nr_reclaimed;
15191da177e4SLinus Torvalds }
15201da177e4SLinus Torvalds 
15213bb1a852SMartin Bligh /*
15221cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
15231cfb419bSKAMEZAWA Hiroyuki  *
15241cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
15251cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
15261cfb419bSKAMEZAWA Hiroyuki  *
15271cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
15281cfb419bSKAMEZAWA Hiroyuki  * appropriate to hold zone->lru_lock across the whole operation.  But if
15291cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
15301cfb419bSKAMEZAWA Hiroyuki  * should drop zone->lru_lock around each page.  It's impossible to balance
15311cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
15321cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
15331cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
15341cfb419bSKAMEZAWA Hiroyuki  *
15351cfb419bSKAMEZAWA Hiroyuki  * The downside is that we have to touch page->_count against each page.
15361cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
15371cfb419bSKAMEZAWA Hiroyuki  */
15381cfb419bSKAMEZAWA Hiroyuki 
1539fa9add64SHugh Dickins static void move_active_pages_to_lru(struct lruvec *lruvec,
15403eb4140fSWu Fengguang 				     struct list_head *list,
15412bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
15423eb4140fSWu Fengguang 				     enum lru_list lru)
15433eb4140fSWu Fengguang {
1544fa9add64SHugh Dickins 	struct zone *zone = lruvec_zone(lruvec);
15453eb4140fSWu Fengguang 	unsigned long pgmoved = 0;
15463eb4140fSWu Fengguang 	struct page *page;
1547fa9add64SHugh Dickins 	int nr_pages;
15483eb4140fSWu Fengguang 
15493eb4140fSWu Fengguang 	while (!list_empty(list)) {
15503eb4140fSWu Fengguang 		page = lru_to_page(list);
1551fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
15523eb4140fSWu Fengguang 
15533eb4140fSWu Fengguang 		VM_BUG_ON(PageLRU(page));
15543eb4140fSWu Fengguang 		SetPageLRU(page);
15553eb4140fSWu Fengguang 
1556fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
1557fa9add64SHugh Dickins 		mem_cgroup_update_lru_size(lruvec, lru, nr_pages);
1558925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
1559fa9add64SHugh Dickins 		pgmoved += nr_pages;
15603eb4140fSWu Fengguang 
15612bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
15622bcf8879SHugh Dickins 			__ClearPageLRU(page);
15632bcf8879SHugh Dickins 			__ClearPageActive(page);
1564fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
15652bcf8879SHugh Dickins 
15662bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
15673eb4140fSWu Fengguang 				spin_unlock_irq(&zone->lru_lock);
15682bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
15693eb4140fSWu Fengguang 				spin_lock_irq(&zone->lru_lock);
15702bcf8879SHugh Dickins 			} else
15712bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
15723eb4140fSWu Fengguang 		}
15733eb4140fSWu Fengguang 	}
15743eb4140fSWu Fengguang 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved);
15753eb4140fSWu Fengguang 	if (!is_active_lru(lru))
15763eb4140fSWu Fengguang 		__count_vm_events(PGDEACTIVATE, pgmoved);
15773eb4140fSWu Fengguang }
15781cfb419bSKAMEZAWA Hiroyuki 
1579f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
15801a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1581f16015fbSJohannes Weiner 			       struct scan_control *sc,
15829e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
15831cfb419bSKAMEZAWA Hiroyuki {
158444c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1585f626012dSHugh Dickins 	unsigned long nr_scanned;
15866fe6b7e3SWu Fengguang 	unsigned long vm_flags;
15871cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
15888cab4754SWu Fengguang 	LIST_HEAD(l_active);
1589b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
15901cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
15911a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
159244c241f1SKOSAKI Motohiro 	unsigned long nr_rotated = 0;
1593f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
15943cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
15951a93be0eSKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
15961cfb419bSKAMEZAWA Hiroyuki 
15971da177e4SLinus Torvalds 	lru_add_drain();
1598f80c0673SMinchan Kim 
1599f80c0673SMinchan Kim 	if (!sc->may_unmap)
160061317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1601f80c0673SMinchan Kim 	if (!sc->may_writepage)
160261317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1603f80c0673SMinchan Kim 
16041da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
1605925b7673SJohannes Weiner 
16065dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
16075dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
160889b5fae5SJohannes Weiner 	if (global_reclaim(sc))
1609f626012dSHugh Dickins 		zone->pages_scanned += nr_scanned;
161089b5fae5SJohannes Weiner 
1611b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
16121cfb419bSKAMEZAWA Hiroyuki 
1613f626012dSHugh Dickins 	__count_zone_vm_events(PGREFILL, zone, nr_scanned);
16143cb99451SKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
1615a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
16161da177e4SLinus Torvalds 	spin_unlock_irq(&zone->lru_lock);
16171da177e4SLinus Torvalds 
16181da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
16191da177e4SLinus Torvalds 		cond_resched();
16201da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
16211da177e4SLinus Torvalds 		list_del(&page->lru);
16227e9cd484SRik van Riel 
162339b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1624894bc310SLee Schermerhorn 			putback_lru_page(page);
1625894bc310SLee Schermerhorn 			continue;
1626894bc310SLee Schermerhorn 		}
1627894bc310SLee Schermerhorn 
1628cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
1629cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
1630cc715d99SMel Gorman 				if (page_has_private(page))
1631cc715d99SMel Gorman 					try_to_release_page(page, 0);
1632cc715d99SMel Gorman 				unlock_page(page);
1633cc715d99SMel Gorman 			}
1634cc715d99SMel Gorman 		}
1635cc715d99SMel Gorman 
1636c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
1637c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
16389992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
16398cab4754SWu Fengguang 			/*
16408cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
16418cab4754SWu Fengguang 			 * give them one more trip around the active list. So
16428cab4754SWu Fengguang 			 * that executable code get better chances to stay in
16438cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
16448cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
16458cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
16468cab4754SWu Fengguang 			 * so we ignore them here.
16478cab4754SWu Fengguang 			 */
164841e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
16498cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
16508cab4754SWu Fengguang 				continue;
16518cab4754SWu Fengguang 			}
16528cab4754SWu Fengguang 		}
16537e9cd484SRik van Riel 
16545205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
16551da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
16561da177e4SLinus Torvalds 	}
16571da177e4SLinus Torvalds 
1658b555749aSAndrew Morton 	/*
16598cab4754SWu Fengguang 	 * Move pages back to the lru list.
1660b555749aSAndrew Morton 	 */
16612a1dc509SJohannes Weiner 	spin_lock_irq(&zone->lru_lock);
16624f98a2feSRik van Riel 	/*
16638cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
16648cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
16658cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
16668cab4754SWu Fengguang 	 * get_scan_ratio.
1667556adecbSRik van Riel 	 */
1668b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
1669556adecbSRik van Riel 
1670fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
1671fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1672a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1673f8891e5eSChristoph Lameter 	spin_unlock_irq(&zone->lru_lock);
16742bcf8879SHugh Dickins 
16752bcf8879SHugh Dickins 	free_hot_cold_page_list(&l_hold, 1);
16761da177e4SLinus Torvalds }
16771da177e4SLinus Torvalds 
167874e3f3c3SMinchan Kim #ifdef CONFIG_SWAP
167914797e23SKOSAKI Motohiro static int inactive_anon_is_low_global(struct zone *zone)
1680f89eb90eSKOSAKI Motohiro {
1681f89eb90eSKOSAKI Motohiro 	unsigned long active, inactive;
1682f89eb90eSKOSAKI Motohiro 
1683f89eb90eSKOSAKI Motohiro 	active = zone_page_state(zone, NR_ACTIVE_ANON);
1684f89eb90eSKOSAKI Motohiro 	inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1685f89eb90eSKOSAKI Motohiro 
1686f89eb90eSKOSAKI Motohiro 	if (inactive * zone->inactive_ratio < active)
1687f89eb90eSKOSAKI Motohiro 		return 1;
1688f89eb90eSKOSAKI Motohiro 
1689f89eb90eSKOSAKI Motohiro 	return 0;
1690f89eb90eSKOSAKI Motohiro }
1691f89eb90eSKOSAKI Motohiro 
169214797e23SKOSAKI Motohiro /**
169314797e23SKOSAKI Motohiro  * inactive_anon_is_low - check if anonymous pages need to be deactivated
1694c56d5c7dSKonstantin Khlebnikov  * @lruvec: LRU vector to check
169514797e23SKOSAKI Motohiro  *
169614797e23SKOSAKI Motohiro  * Returns true if the zone does not have enough inactive anon pages,
169714797e23SKOSAKI Motohiro  * meaning some active anon pages need to be deactivated.
169814797e23SKOSAKI Motohiro  */
1699c56d5c7dSKonstantin Khlebnikov static int inactive_anon_is_low(struct lruvec *lruvec)
170014797e23SKOSAKI Motohiro {
170174e3f3c3SMinchan Kim 	/*
170274e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
170374e3f3c3SMinchan Kim 	 * is pointless.
170474e3f3c3SMinchan Kim 	 */
170574e3f3c3SMinchan Kim 	if (!total_swap_pages)
170674e3f3c3SMinchan Kim 		return 0;
170774e3f3c3SMinchan Kim 
1708c3c787e8SHugh Dickins 	if (!mem_cgroup_disabled())
1709c56d5c7dSKonstantin Khlebnikov 		return mem_cgroup_inactive_anon_is_low(lruvec);
1710f16015fbSJohannes Weiner 
1711c56d5c7dSKonstantin Khlebnikov 	return inactive_anon_is_low_global(lruvec_zone(lruvec));
171214797e23SKOSAKI Motohiro }
171374e3f3c3SMinchan Kim #else
1714c56d5c7dSKonstantin Khlebnikov static inline int inactive_anon_is_low(struct lruvec *lruvec)
171574e3f3c3SMinchan Kim {
171674e3f3c3SMinchan Kim 	return 0;
171774e3f3c3SMinchan Kim }
171874e3f3c3SMinchan Kim #endif
171914797e23SKOSAKI Motohiro 
172056e49d21SRik van Riel /**
172156e49d21SRik van Riel  * inactive_file_is_low - check if file pages need to be deactivated
1722c56d5c7dSKonstantin Khlebnikov  * @lruvec: LRU vector to check
172356e49d21SRik van Riel  *
172456e49d21SRik van Riel  * When the system is doing streaming IO, memory pressure here
172556e49d21SRik van Riel  * ensures that active file pages get deactivated, until more
172656e49d21SRik van Riel  * than half of the file pages are on the inactive list.
172756e49d21SRik van Riel  *
172856e49d21SRik van Riel  * Once we get to that situation, protect the system's working
172956e49d21SRik van Riel  * set from being evicted by disabling active file page aging.
173056e49d21SRik van Riel  *
173156e49d21SRik van Riel  * This uses a different ratio than the anonymous pages, because
173256e49d21SRik van Riel  * the page cache uses a use-once replacement algorithm.
173356e49d21SRik van Riel  */
1734c56d5c7dSKonstantin Khlebnikov static int inactive_file_is_low(struct lruvec *lruvec)
173556e49d21SRik van Riel {
1736e3790144SJohannes Weiner 	unsigned long inactive;
1737e3790144SJohannes Weiner 	unsigned long active;
173856e49d21SRik van Riel 
1739e3790144SJohannes Weiner 	inactive = get_lru_size(lruvec, LRU_INACTIVE_FILE);
1740e3790144SJohannes Weiner 	active = get_lru_size(lruvec, LRU_ACTIVE_FILE);
1741e3790144SJohannes Weiner 
1742e3790144SJohannes Weiner 	return active > inactive;
174356e49d21SRik van Riel }
174456e49d21SRik van Riel 
174575b00af7SHugh Dickins static int inactive_list_is_low(struct lruvec *lruvec, enum lru_list lru)
1746b39415b2SRik van Riel {
174775b00af7SHugh Dickins 	if (is_file_lru(lru))
1748c56d5c7dSKonstantin Khlebnikov 		return inactive_file_is_low(lruvec);
1749b39415b2SRik van Riel 	else
1750c56d5c7dSKonstantin Khlebnikov 		return inactive_anon_is_low(lruvec);
1751b39415b2SRik van Riel }
1752b39415b2SRik van Riel 
17534f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
17541a93be0eSKonstantin Khlebnikov 				 struct lruvec *lruvec, struct scan_control *sc)
1755b69408e8SChristoph Lameter {
1756b39415b2SRik van Riel 	if (is_active_lru(lru)) {
175775b00af7SHugh Dickins 		if (inactive_list_is_low(lruvec, lru))
17581a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
1759556adecbSRik van Riel 		return 0;
1760556adecbSRik van Riel 	}
1761556adecbSRik van Riel 
17621a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
1763b69408e8SChristoph Lameter }
1764b69408e8SChristoph Lameter 
17653d58ab5cSKonstantin Khlebnikov static int vmscan_swappiness(struct scan_control *sc)
17661f4c025bSKAMEZAWA Hiroyuki {
176789b5fae5SJohannes Weiner 	if (global_reclaim(sc))
17681f4c025bSKAMEZAWA Hiroyuki 		return vm_swappiness;
17693d58ab5cSKonstantin Khlebnikov 	return mem_cgroup_swappiness(sc->target_mem_cgroup);
17701f4c025bSKAMEZAWA Hiroyuki }
17711f4c025bSKAMEZAWA Hiroyuki 
17729a265114SJohannes Weiner enum scan_balance {
17739a265114SJohannes Weiner 	SCAN_EQUAL,
17749a265114SJohannes Weiner 	SCAN_FRACT,
17759a265114SJohannes Weiner 	SCAN_ANON,
17769a265114SJohannes Weiner 	SCAN_FILE,
17779a265114SJohannes Weiner };
17789a265114SJohannes Weiner 
17791da177e4SLinus Torvalds /*
17804f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
17814f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
17824f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
17834f98a2feSRik van Riel  * onto the active list instead of evict.
17844f98a2feSRik van Riel  *
1785be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
1786be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
17874f98a2feSRik van Riel  */
178890126375SKonstantin Khlebnikov static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
17899e3b2f8cSKonstantin Khlebnikov 			   unsigned long *nr)
17904f98a2feSRik van Riel {
179190126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
17929a265114SJohannes Weiner 	u64 fraction[2];
17939a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
179490126375SKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
17959a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
17969a265114SJohannes Weiner 	enum scan_balance scan_balance;
17979a265114SJohannes Weiner 	unsigned long anon, file, free;
17989a265114SJohannes Weiner 	bool force_scan = false;
17999a265114SJohannes Weiner 	unsigned long ap, fp;
18009a265114SJohannes Weiner 	enum lru_list lru;
1801246e87a9SKAMEZAWA Hiroyuki 
1802f11c0ca5SJohannes Weiner 	/*
1803f11c0ca5SJohannes Weiner 	 * If the zone or memcg is small, nr[l] can be 0.  This
1804f11c0ca5SJohannes Weiner 	 * results in no scanning on this priority and a potential
1805f11c0ca5SJohannes Weiner 	 * priority drop.  Global direct reclaim can go to the next
1806f11c0ca5SJohannes Weiner 	 * zone and tends to have no problems. Global kswapd is for
1807f11c0ca5SJohannes Weiner 	 * zone balancing and it needs to scan a minimum amount. When
1808f11c0ca5SJohannes Weiner 	 * reclaiming for a memcg, a priority drop can cause high
1809f11c0ca5SJohannes Weiner 	 * latencies, so it's better to scan a minimum amount there as
1810f11c0ca5SJohannes Weiner 	 * well.
1811f11c0ca5SJohannes Weiner 	 */
181290126375SKonstantin Khlebnikov 	if (current_is_kswapd() && zone->all_unreclaimable)
1813a4d3e9e7SJohannes Weiner 		force_scan = true;
181489b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
1815a4d3e9e7SJohannes Weiner 		force_scan = true;
181676a33fc3SShaohua Li 
181776a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
1818ec8acf20SShaohua Li 	if (!sc->may_swap || (get_nr_swap_pages() <= 0)) {
18199a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
182076a33fc3SShaohua Li 		goto out;
182176a33fc3SShaohua Li 	}
18224f98a2feSRik van Riel 
182310316b31SJohannes Weiner 	/*
182410316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
182510316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
182610316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
182710316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
182810316b31SJohannes Weiner 	 * too expensive.
182910316b31SJohannes Weiner 	 */
183010316b31SJohannes Weiner 	if (!global_reclaim(sc) && !vmscan_swappiness(sc)) {
18319a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
183210316b31SJohannes Weiner 		goto out;
183310316b31SJohannes Weiner 	}
183410316b31SJohannes Weiner 
183510316b31SJohannes Weiner 	/*
183610316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
183710316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
183810316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
183910316b31SJohannes Weiner 	 */
184010316b31SJohannes Weiner 	if (!sc->priority && vmscan_swappiness(sc)) {
18419a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
184210316b31SJohannes Weiner 		goto out;
184310316b31SJohannes Weiner 	}
184410316b31SJohannes Weiner 
18454d7dcca2SHugh Dickins 	anon  = get_lru_size(lruvec, LRU_ACTIVE_ANON) +
18464d7dcca2SHugh Dickins 		get_lru_size(lruvec, LRU_INACTIVE_ANON);
18474d7dcca2SHugh Dickins 	file  = get_lru_size(lruvec, LRU_ACTIVE_FILE) +
18484d7dcca2SHugh Dickins 		get_lru_size(lruvec, LRU_INACTIVE_FILE);
1849a4d3e9e7SJohannes Weiner 
185011d16c25SJohannes Weiner 	/*
185111d16c25SJohannes Weiner 	 * If it's foreseeable that reclaiming the file cache won't be
185211d16c25SJohannes Weiner 	 * enough to get the zone back into a desirable shape, we have
185311d16c25SJohannes Weiner 	 * to swap.  Better start now and leave the - probably heavily
185411d16c25SJohannes Weiner 	 * thrashing - remaining file pages alone.
185511d16c25SJohannes Weiner 	 */
185689b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
185790126375SKonstantin Khlebnikov 		free = zone_page_state(zone, NR_FREE_PAGES);
185890126375SKonstantin Khlebnikov 		if (unlikely(file + free <= high_wmark_pages(zone))) {
18599a265114SJohannes Weiner 			scan_balance = SCAN_ANON;
186076a33fc3SShaohua Li 			goto out;
18617c5bd705SJohannes Weiner 		}
18627c5bd705SJohannes Weiner 	}
18637c5bd705SJohannes Weiner 
1864e9868505SRik van Riel 	/*
18657c5bd705SJohannes Weiner 	 * There is enough inactive page cache, do not reclaim
18667c5bd705SJohannes Weiner 	 * anything from the anonymous working set right now.
1867e9868505SRik van Riel 	 */
18687c5bd705SJohannes Weiner 	if (!inactive_file_is_low(lruvec)) {
18699a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
1870e9868505SRik van Riel 		goto out;
18714f98a2feSRik van Riel 	}
18724f98a2feSRik van Riel 
18739a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
18749a265114SJohannes Weiner 
18754f98a2feSRik van Riel 	/*
187658c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
187758c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
187858c37f6eSKOSAKI Motohiro 	 */
18793d58ab5cSKonstantin Khlebnikov 	anon_prio = vmscan_swappiness(sc);
188075b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
188158c37f6eSKOSAKI Motohiro 
188258c37f6eSKOSAKI Motohiro 	/*
18834f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
18844f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
18854f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
18864f98a2feSRik van Riel 	 *
18874f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
18884f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
18894f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
18904f98a2feSRik van Riel 	 *
18914f98a2feSRik van Riel 	 * anon in [0], file in [1]
18924f98a2feSRik van Riel 	 */
189390126375SKonstantin Khlebnikov 	spin_lock_irq(&zone->lru_lock);
189458c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
18956e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
18966e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
18974f98a2feSRik van Riel 	}
18984f98a2feSRik van Riel 
18996e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
19006e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
19016e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
19024f98a2feSRik van Riel 	}
19034f98a2feSRik van Riel 
19044f98a2feSRik van Riel 	/*
190500d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
190600d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
190700d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
19084f98a2feSRik van Riel 	 */
1909fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
19106e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
19114f98a2feSRik van Riel 
1912fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
19136e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
191490126375SKonstantin Khlebnikov 	spin_unlock_irq(&zone->lru_lock);
19154f98a2feSRik van Riel 
191676a33fc3SShaohua Li 	fraction[0] = ap;
191776a33fc3SShaohua Li 	fraction[1] = fp;
191876a33fc3SShaohua Li 	denominator = ap + fp + 1;
191976a33fc3SShaohua Li out:
19204111304dSHugh Dickins 	for_each_evictable_lru(lru) {
19214111304dSHugh Dickins 		int file = is_file_lru(lru);
1922d778df51SJohannes Weiner 		unsigned long size;
192376a33fc3SShaohua Li 		unsigned long scan;
192476a33fc3SShaohua Li 
1925d778df51SJohannes Weiner 		size = get_lru_size(lruvec, lru);
1926d778df51SJohannes Weiner 		scan = size >> sc->priority;
19279a265114SJohannes Weiner 
1928f11c0ca5SJohannes Weiner 		if (!scan && force_scan)
1929d778df51SJohannes Weiner 			scan = min(size, SWAP_CLUSTER_MAX);
19309a265114SJohannes Weiner 
19319a265114SJohannes Weiner 		switch (scan_balance) {
19329a265114SJohannes Weiner 		case SCAN_EQUAL:
19339a265114SJohannes Weiner 			/* Scan lists relative to size */
19349a265114SJohannes Weiner 			break;
19359a265114SJohannes Weiner 		case SCAN_FRACT:
19369a265114SJohannes Weiner 			/*
19379a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
19389a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
19399a265114SJohannes Weiner 			 */
194076a33fc3SShaohua Li 			scan = div64_u64(scan * fraction[file], denominator);
19419a265114SJohannes Weiner 			break;
19429a265114SJohannes Weiner 		case SCAN_FILE:
19439a265114SJohannes Weiner 		case SCAN_ANON:
19449a265114SJohannes Weiner 			/* Scan one type exclusively */
19459a265114SJohannes Weiner 			if ((scan_balance == SCAN_FILE) != file)
19469a265114SJohannes Weiner 				scan = 0;
19479a265114SJohannes Weiner 			break;
19489a265114SJohannes Weiner 		default:
19499a265114SJohannes Weiner 			/* Look ma, no brain */
19509a265114SJohannes Weiner 			BUG();
19519a265114SJohannes Weiner 		}
19524111304dSHugh Dickins 		nr[lru] = scan;
195376a33fc3SShaohua Li 	}
19546e08a369SWu Fengguang }
19554f98a2feSRik van Riel 
19569b4f98cdSJohannes Weiner /*
19579b4f98cdSJohannes Weiner  * This is a basic per-zone page freer.  Used by both kswapd and direct reclaim.
19589b4f98cdSJohannes Weiner  */
19599b4f98cdSJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
19609b4f98cdSJohannes Weiner {
19619b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
1962e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
19639b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
19649b4f98cdSJohannes Weiner 	enum lru_list lru;
19659b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
19669b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
19679b4f98cdSJohannes Weiner 	struct blk_plug plug;
1968e82e0561SMel Gorman 	bool scan_adjusted = false;
19699b4f98cdSJohannes Weiner 
19709b4f98cdSJohannes Weiner 	get_scan_count(lruvec, sc, nr);
19719b4f98cdSJohannes Weiner 
1972e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
1973e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
1974e82e0561SMel Gorman 
19759b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
19769b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
19779b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
1978e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
1979e82e0561SMel Gorman 		unsigned long nr_scanned;
1980e82e0561SMel Gorman 
19819b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
19829b4f98cdSJohannes Weiner 			if (nr[lru]) {
19839b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
19849b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
19859b4f98cdSJohannes Weiner 
19869b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
19879b4f98cdSJohannes Weiner 							    lruvec, sc);
19889b4f98cdSJohannes Weiner 			}
19899b4f98cdSJohannes Weiner 		}
1990e82e0561SMel Gorman 
1991e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
1992e82e0561SMel Gorman 			continue;
1993e82e0561SMel Gorman 
19949b4f98cdSJohannes Weiner 		/*
1995e82e0561SMel Gorman 		 * For global direct reclaim, reclaim only the number of pages
1996e82e0561SMel Gorman 		 * requested. Less care is taken to scan proportionally as it
1997e82e0561SMel Gorman 		 * is more important to minimise direct reclaim stall latency
1998e82e0561SMel Gorman 		 * than it is to properly age the LRU lists.
19999b4f98cdSJohannes Weiner 		 */
2000e82e0561SMel Gorman 		if (global_reclaim(sc) && !current_is_kswapd())
20019b4f98cdSJohannes Weiner 			break;
2002e82e0561SMel Gorman 
2003e82e0561SMel Gorman 		/*
2004e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
2005e82e0561SMel Gorman 		 * requested. Ensure that the anon and file LRUs shrink
2006e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2007e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2008e82e0561SMel Gorman 		 * proportional to the original scan target.
2009e82e0561SMel Gorman 		 */
2010e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2011e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2012e82e0561SMel Gorman 
2013e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2014e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2015e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2016e82e0561SMel Gorman 			lru = LRU_BASE;
2017e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2018e82e0561SMel Gorman 		} else {
2019e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2020e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2021e82e0561SMel Gorman 			lru = LRU_FILE;
2022e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2023e82e0561SMel Gorman 		}
2024e82e0561SMel Gorman 
2025e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2026e82e0561SMel Gorman 		nr[lru] = 0;
2027e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2028e82e0561SMel Gorman 
2029e82e0561SMel Gorman 		/*
2030e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2031e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2032e82e0561SMel Gorman 		 */
2033e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2034e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2035e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2036e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2037e82e0561SMel Gorman 
2038e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2039e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2040e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2041e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2042e82e0561SMel Gorman 
2043e82e0561SMel Gorman 		scan_adjusted = true;
20449b4f98cdSJohannes Weiner 	}
20459b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
20469b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
20479b4f98cdSJohannes Weiner 
20489b4f98cdSJohannes Weiner 	/*
20499b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
20509b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
20519b4f98cdSJohannes Weiner 	 */
20529b4f98cdSJohannes Weiner 	if (inactive_anon_is_low(lruvec))
20539b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
20549b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
20559b4f98cdSJohannes Weiner 
20569b4f98cdSJohannes Weiner 	throttle_vm_writeout(sc->gfp_mask);
20579b4f98cdSJohannes Weiner }
20589b4f98cdSJohannes Weiner 
205923b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
20609e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
206123b9da55SMel Gorman {
2062d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
206323b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
20649e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
206523b9da55SMel Gorman 		return true;
206623b9da55SMel Gorman 
206723b9da55SMel Gorman 	return false;
206823b9da55SMel Gorman }
206923b9da55SMel Gorman 
20704f98a2feSRik van Riel /*
207123b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
207223b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
207323b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
207423b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
207523b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
20763e7d3449SMel Gorman  */
20779b4f98cdSJohannes Weiner static inline bool should_continue_reclaim(struct zone *zone,
20783e7d3449SMel Gorman 					unsigned long nr_reclaimed,
20793e7d3449SMel Gorman 					unsigned long nr_scanned,
20803e7d3449SMel Gorman 					struct scan_control *sc)
20813e7d3449SMel Gorman {
20823e7d3449SMel Gorman 	unsigned long pages_for_compaction;
20833e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
20843e7d3449SMel Gorman 
20853e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
20869e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
20873e7d3449SMel Gorman 		return false;
20883e7d3449SMel Gorman 
20892876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
20902876592fSMel Gorman 	if (sc->gfp_mask & __GFP_REPEAT) {
20913e7d3449SMel Gorman 		/*
20922876592fSMel Gorman 		 * For __GFP_REPEAT allocations, stop reclaiming if the
20932876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
20942876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
20952876592fSMel Gorman 		 * expensive but a __GFP_REPEAT caller really wants to succeed
20963e7d3449SMel Gorman 		 */
20973e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
20983e7d3449SMel Gorman 			return false;
20992876592fSMel Gorman 	} else {
21002876592fSMel Gorman 		/*
21012876592fSMel Gorman 		 * For non-__GFP_REPEAT allocations which can presumably
21022876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
21032876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
21042876592fSMel Gorman 		 * pages that were scanned. This will return to the
21052876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
21062876592fSMel Gorman 		 * the resulting allocation attempt fails
21072876592fSMel Gorman 		 */
21082876592fSMel Gorman 		if (!nr_reclaimed)
21092876592fSMel Gorman 			return false;
21102876592fSMel Gorman 	}
21113e7d3449SMel Gorman 
21123e7d3449SMel Gorman 	/*
21133e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
21143e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
21153e7d3449SMel Gorman 	 */
21163e7d3449SMel Gorman 	pages_for_compaction = (2UL << sc->order);
21179b4f98cdSJohannes Weiner 	inactive_lru_pages = zone_page_state(zone, NR_INACTIVE_FILE);
2118ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
21199b4f98cdSJohannes Weiner 		inactive_lru_pages += zone_page_state(zone, NR_INACTIVE_ANON);
21203e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
21213e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
21223e7d3449SMel Gorman 		return true;
21233e7d3449SMel Gorman 
21243e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
21259b4f98cdSJohannes Weiner 	switch (compaction_suitable(zone, sc->order)) {
21263e7d3449SMel Gorman 	case COMPACT_PARTIAL:
21273e7d3449SMel Gorman 	case COMPACT_CONTINUE:
21283e7d3449SMel Gorman 		return false;
21293e7d3449SMel Gorman 	default:
21303e7d3449SMel Gorman 		return true;
21313e7d3449SMel Gorman 	}
21323e7d3449SMel Gorman }
21333e7d3449SMel Gorman 
21349e3b2f8cSKonstantin Khlebnikov static void shrink_zone(struct zone *zone, struct scan_control *sc)
2135f16015fbSJohannes Weiner {
21369b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
21379b4f98cdSJohannes Weiner 
21389b4f98cdSJohannes Weiner 	do {
21395660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
21405660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
21415660048cSJohannes Weiner 			.zone = zone,
21429e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
21435660048cSJohannes Weiner 		};
21445660048cSJohannes Weiner 		struct mem_cgroup *memcg;
21455660048cSJohannes Weiner 
21469b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
21479b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
21489b4f98cdSJohannes Weiner 
21495660048cSJohannes Weiner 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
21505660048cSJohannes Weiner 		do {
21519b4f98cdSJohannes Weiner 			struct lruvec *lruvec;
21529b4f98cdSJohannes Weiner 
21539b4f98cdSJohannes Weiner 			lruvec = mem_cgroup_zone_lruvec(zone, memcg);
21545660048cSJohannes Weiner 
2155f9be23d6SKonstantin Khlebnikov 			shrink_lruvec(lruvec, sc);
2156f9be23d6SKonstantin Khlebnikov 
21575660048cSJohannes Weiner 			/*
2158a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2159a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
21609b4f98cdSJohannes Weiner 			 * zone.
2161a394cb8eSMichal Hocko 			 *
2162a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2163a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2164a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2165a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
21665660048cSJohannes Weiner 			 */
2167a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2168a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
21695660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
21705660048cSJohannes Weiner 				break;
21715660048cSJohannes Weiner 			}
21725660048cSJohannes Weiner 			memcg = mem_cgroup_iter(root, memcg, &reclaim);
21735660048cSJohannes Weiner 		} while (memcg);
217470ddf637SAnton Vorontsov 
217570ddf637SAnton Vorontsov 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup,
217670ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
217770ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
217870ddf637SAnton Vorontsov 
21799b4f98cdSJohannes Weiner 	} while (should_continue_reclaim(zone, sc->nr_reclaimed - nr_reclaimed,
21809b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
2181f16015fbSJohannes Weiner }
2182f16015fbSJohannes Weiner 
2183fe4b1b24SMel Gorman /* Returns true if compaction should go ahead for a high-order request */
2184fe4b1b24SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2185fe4b1b24SMel Gorman {
2186fe4b1b24SMel Gorman 	unsigned long balance_gap, watermark;
2187fe4b1b24SMel Gorman 	bool watermark_ok;
2188fe4b1b24SMel Gorman 
2189fe4b1b24SMel Gorman 	/* Do not consider compaction for orders reclaim is meant to satisfy */
2190fe4b1b24SMel Gorman 	if (sc->order <= PAGE_ALLOC_COSTLY_ORDER)
2191fe4b1b24SMel Gorman 		return false;
2192fe4b1b24SMel Gorman 
2193fe4b1b24SMel Gorman 	/*
2194fe4b1b24SMel Gorman 	 * Compaction takes time to run and there are potentially other
2195fe4b1b24SMel Gorman 	 * callers using the pages just freed. Continue reclaiming until
2196fe4b1b24SMel Gorman 	 * there is a buffer of free pages available to give compaction
2197fe4b1b24SMel Gorman 	 * a reasonable chance of completing and allocating the page
2198fe4b1b24SMel Gorman 	 */
2199fe4b1b24SMel Gorman 	balance_gap = min(low_wmark_pages(zone),
2200b40da049SJiang Liu 		(zone->managed_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
2201fe4b1b24SMel Gorman 			KSWAPD_ZONE_BALANCE_GAP_RATIO);
2202fe4b1b24SMel Gorman 	watermark = high_wmark_pages(zone) + balance_gap + (2UL << sc->order);
2203fe4b1b24SMel Gorman 	watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, 0, 0);
2204fe4b1b24SMel Gorman 
2205fe4b1b24SMel Gorman 	/*
2206fe4b1b24SMel Gorman 	 * If compaction is deferred, reclaim up to a point where
2207fe4b1b24SMel Gorman 	 * compaction will have a chance of success when re-enabled
2208fe4b1b24SMel Gorman 	 */
2209aff62249SRik van Riel 	if (compaction_deferred(zone, sc->order))
2210fe4b1b24SMel Gorman 		return watermark_ok;
2211fe4b1b24SMel Gorman 
2212fe4b1b24SMel Gorman 	/* If compaction is not ready to start, keep reclaiming */
2213fe4b1b24SMel Gorman 	if (!compaction_suitable(zone, sc->order))
2214fe4b1b24SMel Gorman 		return false;
2215fe4b1b24SMel Gorman 
2216fe4b1b24SMel Gorman 	return watermark_ok;
2217fe4b1b24SMel Gorman }
2218fe4b1b24SMel Gorman 
22191da177e4SLinus Torvalds /*
22201da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
22211da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
22221da177e4SLinus Torvalds  * request.
22231da177e4SLinus Torvalds  *
222441858966SMel Gorman  * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
222541858966SMel Gorman  * Because:
22261da177e4SLinus Torvalds  * a) The caller may be trying to free *extra* pages to satisfy a higher-order
22271da177e4SLinus Torvalds  *    allocation or
222841858966SMel Gorman  * b) The target zone may be at high_wmark_pages(zone) but the lower zones
222941858966SMel Gorman  *    must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
223041858966SMel Gorman  *    zone defense algorithm.
22311da177e4SLinus Torvalds  *
22321da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
22331da177e4SLinus Torvalds  * scan then give up on it.
2234e0c23279SMel Gorman  *
2235e0c23279SMel Gorman  * This function returns true if a zone is being reclaimed for a costly
2236fe4b1b24SMel Gorman  * high-order allocation and compaction is ready to begin. This indicates to
22370cee34fdSMel Gorman  * the caller that it should consider retrying the allocation instead of
22380cee34fdSMel Gorman  * further reclaim.
22391da177e4SLinus Torvalds  */
22409e3b2f8cSKonstantin Khlebnikov static bool shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
22411da177e4SLinus Torvalds {
2242dd1a239fSMel Gorman 	struct zoneref *z;
224354a6eb5cSMel Gorman 	struct zone *zone;
2244d149e3b2SYing Han 	unsigned long nr_soft_reclaimed;
2245d149e3b2SYing Han 	unsigned long nr_soft_scanned;
22460cee34fdSMel Gorman 	bool aborted_reclaim = false;
22471cfb419bSKAMEZAWA Hiroyuki 
2248cc715d99SMel Gorman 	/*
2249cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2250cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2251cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2252cc715d99SMel Gorman 	 */
2253cc715d99SMel Gorman 	if (buffer_heads_over_limit)
2254cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
2255cc715d99SMel Gorman 
2256d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2257d4debc66SMel Gorman 					gfp_zone(sc->gfp_mask), sc->nodemask) {
2258f3fe6512SCon Kolivas 		if (!populated_zone(zone))
22591da177e4SLinus Torvalds 			continue;
22601cfb419bSKAMEZAWA Hiroyuki 		/*
22611cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
22621cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
22631cfb419bSKAMEZAWA Hiroyuki 		 */
226489b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
226502a0e53dSPaul Jackson 			if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
22661da177e4SLinus Torvalds 				continue;
22679e3b2f8cSKonstantin Khlebnikov 			if (zone->all_unreclaimable &&
22689e3b2f8cSKonstantin Khlebnikov 					sc->priority != DEF_PRIORITY)
22691da177e4SLinus Torvalds 				continue;	/* Let kswapd poll it */
2270d84da3f9SKirill A. Shutemov 			if (IS_ENABLED(CONFIG_COMPACTION)) {
2271e0887c19SRik van Riel 				/*
2272e0c23279SMel Gorman 				 * If we already have plenty of memory free for
2273e0c23279SMel Gorman 				 * compaction in this zone, don't free any more.
2274e0c23279SMel Gorman 				 * Even though compaction is invoked for any
2275e0c23279SMel Gorman 				 * non-zero order, only frequent costly order
2276e0c23279SMel Gorman 				 * reclamation is disruptive enough to become a
2277c7cfa37bSCopot Alexandru 				 * noticeable problem, like transparent huge
2278c7cfa37bSCopot Alexandru 				 * page allocations.
2279e0887c19SRik van Riel 				 */
2280fe4b1b24SMel Gorman 				if (compaction_ready(zone, sc)) {
22810cee34fdSMel Gorman 					aborted_reclaim = true;
2282e0887c19SRik van Riel 					continue;
2283e0887c19SRik van Riel 				}
2284e0c23279SMel Gorman 			}
2285ac34a1a3SKAMEZAWA Hiroyuki 			/*
2286ac34a1a3SKAMEZAWA Hiroyuki 			 * This steals pages from memory cgroups over softlimit
2287ac34a1a3SKAMEZAWA Hiroyuki 			 * and returns the number of reclaimed pages and
2288ac34a1a3SKAMEZAWA Hiroyuki 			 * scanned pages. This works for global memory pressure
2289ac34a1a3SKAMEZAWA Hiroyuki 			 * and balancing, not for a memcg's limit.
2290ac34a1a3SKAMEZAWA Hiroyuki 			 */
2291d149e3b2SYing Han 			nr_soft_scanned = 0;
2292d149e3b2SYing Han 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
2293d149e3b2SYing Han 						sc->order, sc->gfp_mask,
2294d149e3b2SYing Han 						&nr_soft_scanned);
2295d149e3b2SYing Han 			sc->nr_reclaimed += nr_soft_reclaimed;
2296ac34a1a3SKAMEZAWA Hiroyuki 			sc->nr_scanned += nr_soft_scanned;
2297ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2298ac34a1a3SKAMEZAWA Hiroyuki 		}
2299d149e3b2SYing Han 
23009e3b2f8cSKonstantin Khlebnikov 		shrink_zone(zone, sc);
23011da177e4SLinus Torvalds 	}
2302e0c23279SMel Gorman 
23030cee34fdSMel Gorman 	return aborted_reclaim;
2304d1908362SMinchan Kim }
2305d1908362SMinchan Kim 
2306d1908362SMinchan Kim static bool zone_reclaimable(struct zone *zone)
2307d1908362SMinchan Kim {
2308d1908362SMinchan Kim 	return zone->pages_scanned < zone_reclaimable_pages(zone) * 6;
2309d1908362SMinchan Kim }
2310d1908362SMinchan Kim 
2311929bea7cSKOSAKI Motohiro /* All zones in zonelist are unreclaimable? */
2312d1908362SMinchan Kim static bool all_unreclaimable(struct zonelist *zonelist,
2313d1908362SMinchan Kim 		struct scan_control *sc)
2314d1908362SMinchan Kim {
2315d1908362SMinchan Kim 	struct zoneref *z;
2316d1908362SMinchan Kim 	struct zone *zone;
2317d1908362SMinchan Kim 
2318d1908362SMinchan Kim 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2319d1908362SMinchan Kim 			gfp_zone(sc->gfp_mask), sc->nodemask) {
2320d1908362SMinchan Kim 		if (!populated_zone(zone))
2321d1908362SMinchan Kim 			continue;
2322d1908362SMinchan Kim 		if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2323d1908362SMinchan Kim 			continue;
2324929bea7cSKOSAKI Motohiro 		if (!zone->all_unreclaimable)
2325929bea7cSKOSAKI Motohiro 			return false;
2326d1908362SMinchan Kim 	}
2327d1908362SMinchan Kim 
2328929bea7cSKOSAKI Motohiro 	return true;
23291da177e4SLinus Torvalds }
23301da177e4SLinus Torvalds 
23311da177e4SLinus Torvalds /*
23321da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
23331da177e4SLinus Torvalds  *
23341da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
23351da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
23361da177e4SLinus Torvalds  *
23371da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
23381da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
23395b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
23405b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
23415b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
23425b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2343a41f24eaSNishanth Aravamudan  *
2344a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2345a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
23461da177e4SLinus Torvalds  */
2347dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
2348a09ed5e0SYing Han 					struct scan_control *sc,
2349a09ed5e0SYing Han 					struct shrink_control *shrink)
23501da177e4SLinus Torvalds {
235169e05944SAndrew Morton 	unsigned long total_scanned = 0;
23521da177e4SLinus Torvalds 	struct reclaim_state *reclaim_state = current->reclaim_state;
2353dd1a239fSMel Gorman 	struct zoneref *z;
235454a6eb5cSMel Gorman 	struct zone *zone;
235522fba335SKOSAKI Motohiro 	unsigned long writeback_threshold;
23560cee34fdSMel Gorman 	bool aborted_reclaim;
23571da177e4SLinus Torvalds 
2358873b4771SKeika Kobayashi 	delayacct_freepages_start();
2359873b4771SKeika Kobayashi 
236089b5fae5SJohannes Weiner 	if (global_reclaim(sc))
2361f8891e5eSChristoph Lameter 		count_vm_event(ALLOCSTALL);
23621da177e4SLinus Torvalds 
23639e3b2f8cSKonstantin Khlebnikov 	do {
236470ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
236570ddf637SAnton Vorontsov 				sc->priority);
236666e1707bSBalbir Singh 		sc->nr_scanned = 0;
23679e3b2f8cSKonstantin Khlebnikov 		aborted_reclaim = shrink_zones(zonelist, sc);
2368e0c23279SMel Gorman 
236966e1707bSBalbir Singh 		/*
23705a1c9cbcSMel Gorman 		 * Don't shrink slabs when reclaiming memory from over limit
23715a1c9cbcSMel Gorman 		 * cgroups but do shrink slab at least once when aborting
23725a1c9cbcSMel Gorman 		 * reclaim for compaction to avoid unevenly scanning file/anon
23735a1c9cbcSMel Gorman 		 * LRU pages over slab pages.
237466e1707bSBalbir Singh 		 */
237589b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2376c6a8a8c5SKOSAKI Motohiro 			unsigned long lru_pages = 0;
2377d4debc66SMel Gorman 			for_each_zone_zonelist(zone, z, zonelist,
2378d4debc66SMel Gorman 					gfp_zone(sc->gfp_mask)) {
2379c6a8a8c5SKOSAKI Motohiro 				if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2380c6a8a8c5SKOSAKI Motohiro 					continue;
2381c6a8a8c5SKOSAKI Motohiro 
2382c6a8a8c5SKOSAKI Motohiro 				lru_pages += zone_reclaimable_pages(zone);
2383c6a8a8c5SKOSAKI Motohiro 			}
2384c6a8a8c5SKOSAKI Motohiro 
23851495f230SYing Han 			shrink_slab(shrink, sc->nr_scanned, lru_pages);
23861da177e4SLinus Torvalds 			if (reclaim_state) {
2387a79311c1SRik van Riel 				sc->nr_reclaimed += reclaim_state->reclaimed_slab;
23881da177e4SLinus Torvalds 				reclaim_state->reclaimed_slab = 0;
23891da177e4SLinus Torvalds 			}
239091a45470SKAMEZAWA Hiroyuki 		}
239166e1707bSBalbir Singh 		total_scanned += sc->nr_scanned;
2392bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
23931da177e4SLinus Torvalds 			goto out;
23941da177e4SLinus Torvalds 
23951da177e4SLinus Torvalds 		/*
23960e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
23970e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
23980e50ce3bSMinchan Kim 		 */
23990e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
24000e50ce3bSMinchan Kim 			sc->may_writepage = 1;
24010e50ce3bSMinchan Kim 
24020e50ce3bSMinchan Kim 		/*
24031da177e4SLinus Torvalds 		 * Try to write back as many pages as we just scanned.  This
24041da177e4SLinus Torvalds 		 * tends to cause slow streaming writers to write data to the
24051da177e4SLinus Torvalds 		 * disk smoothly, at the dirtying rate, which is nice.   But
24061da177e4SLinus Torvalds 		 * that's undesirable in laptop mode, where we *want* lumpy
24071da177e4SLinus Torvalds 		 * writeout.  So in laptop mode, write out the whole world.
24081da177e4SLinus Torvalds 		 */
240922fba335SKOSAKI Motohiro 		writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
241022fba335SKOSAKI Motohiro 		if (total_scanned > writeback_threshold) {
24110e175a18SCurt Wohlgemuth 			wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
24120e175a18SCurt Wohlgemuth 						WB_REASON_TRY_TO_FREE_PAGES);
241366e1707bSBalbir Singh 			sc->may_writepage = 1;
24141da177e4SLinus Torvalds 		}
24155a1c9cbcSMel Gorman 	} while (--sc->priority >= 0 && !aborted_reclaim);
2416bb21c7ceSKOSAKI Motohiro 
24171da177e4SLinus Torvalds out:
2418873b4771SKeika Kobayashi 	delayacct_freepages_end();
2419873b4771SKeika Kobayashi 
2420bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2421bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2422bb21c7ceSKOSAKI Motohiro 
2423929bea7cSKOSAKI Motohiro 	/*
2424929bea7cSKOSAKI Motohiro 	 * As hibernation is going on, kswapd is freezed so that it can't mark
2425929bea7cSKOSAKI Motohiro 	 * the zone into all_unreclaimable. Thus bypassing all_unreclaimable
2426929bea7cSKOSAKI Motohiro 	 * check.
2427929bea7cSKOSAKI Motohiro 	 */
2428929bea7cSKOSAKI Motohiro 	if (oom_killer_disabled)
2429929bea7cSKOSAKI Motohiro 		return 0;
2430929bea7cSKOSAKI Motohiro 
24310cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
24320cee34fdSMel Gorman 	if (aborted_reclaim)
24337335084dSMel Gorman 		return 1;
24347335084dSMel Gorman 
2435bb21c7ceSKOSAKI Motohiro 	/* top priority shrink_zones still had more to do? don't OOM, then */
243689b5fae5SJohannes Weiner 	if (global_reclaim(sc) && !all_unreclaimable(zonelist, sc))
2437bb21c7ceSKOSAKI Motohiro 		return 1;
2438bb21c7ceSKOSAKI Motohiro 
2439bb21c7ceSKOSAKI Motohiro 	return 0;
24401da177e4SLinus Torvalds }
24411da177e4SLinus Torvalds 
24425515061dSMel Gorman static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
24435515061dSMel Gorman {
24445515061dSMel Gorman 	struct zone *zone;
24455515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
24465515061dSMel Gorman 	unsigned long free_pages = 0;
24475515061dSMel Gorman 	int i;
24485515061dSMel Gorman 	bool wmark_ok;
24495515061dSMel Gorman 
24505515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
24515515061dSMel Gorman 		zone = &pgdat->node_zones[i];
24525515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
24535515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
24545515061dSMel Gorman 	}
24555515061dSMel Gorman 
24565515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
24575515061dSMel Gorman 
24585515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
24595515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
24605515061dSMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx,
24615515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
24625515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
24635515061dSMel Gorman 	}
24645515061dSMel Gorman 
24655515061dSMel Gorman 	return wmark_ok;
24665515061dSMel Gorman }
24675515061dSMel Gorman 
24685515061dSMel Gorman /*
24695515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
24705515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
24715515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
247250694c28SMel Gorman  * when the low watermark is reached.
247350694c28SMel Gorman  *
247450694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
247550694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
24765515061dSMel Gorman  */
247750694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
24785515061dSMel Gorman 					nodemask_t *nodemask)
24795515061dSMel Gorman {
24805515061dSMel Gorman 	struct zone *zone;
24815515061dSMel Gorman 	int high_zoneidx = gfp_zone(gfp_mask);
24825515061dSMel Gorman 	pg_data_t *pgdat;
24835515061dSMel Gorman 
24845515061dSMel Gorman 	/*
24855515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
24865515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
24875515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
24885515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
24895515061dSMel Gorman 	 * processes to block on log_wait_commit().
24905515061dSMel Gorman 	 */
24915515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
249250694c28SMel Gorman 		goto out;
249350694c28SMel Gorman 
249450694c28SMel Gorman 	/*
249550694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
249650694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
249750694c28SMel Gorman 	 */
249850694c28SMel Gorman 	if (fatal_signal_pending(current))
249950694c28SMel Gorman 		goto out;
25005515061dSMel Gorman 
25015515061dSMel Gorman 	/* Check if the pfmemalloc reserves are ok */
25025515061dSMel Gorman 	first_zones_zonelist(zonelist, high_zoneidx, NULL, &zone);
25035515061dSMel Gorman 	pgdat = zone->zone_pgdat;
25045515061dSMel Gorman 	if (pfmemalloc_watermark_ok(pgdat))
250550694c28SMel Gorman 		goto out;
25065515061dSMel Gorman 
250768243e76SMel Gorman 	/* Account for the throttling */
250868243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
250968243e76SMel Gorman 
25105515061dSMel Gorman 	/*
25115515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
25125515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
25135515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
25145515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
25155515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
25165515061dSMel Gorman 	 * second before continuing.
25175515061dSMel Gorman 	 */
25185515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
25195515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
25205515061dSMel Gorman 			pfmemalloc_watermark_ok(pgdat), HZ);
252150694c28SMel Gorman 
252250694c28SMel Gorman 		goto check_pending;
25235515061dSMel Gorman 	}
25245515061dSMel Gorman 
25255515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
25265515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
25275515061dSMel Gorman 		pfmemalloc_watermark_ok(pgdat));
252850694c28SMel Gorman 
252950694c28SMel Gorman check_pending:
253050694c28SMel Gorman 	if (fatal_signal_pending(current))
253150694c28SMel Gorman 		return true;
253250694c28SMel Gorman 
253350694c28SMel Gorman out:
253450694c28SMel Gorman 	return false;
25355515061dSMel Gorman }
25365515061dSMel Gorman 
2537dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2538327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
253966e1707bSBalbir Singh {
254033906bc5SMel Gorman 	unsigned long nr_reclaimed;
254166e1707bSBalbir Singh 	struct scan_control sc = {
254221caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
254366e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
254422fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2545a6dc60f8SJohannes Weiner 		.may_unmap = 1,
25462e2e4259SKOSAKI Motohiro 		.may_swap = 1,
254766e1707bSBalbir Singh 		.order = order,
25489e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
2549f16015fbSJohannes Weiner 		.target_mem_cgroup = NULL,
2550327c0e96SKAMEZAWA Hiroyuki 		.nodemask = nodemask,
255166e1707bSBalbir Singh 	};
2552a09ed5e0SYing Han 	struct shrink_control shrink = {
2553a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
2554a09ed5e0SYing Han 	};
255566e1707bSBalbir Singh 
25565515061dSMel Gorman 	/*
255750694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
255850694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
255950694c28SMel Gorman 	 * point.
25605515061dSMel Gorman 	 */
256150694c28SMel Gorman 	if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
25625515061dSMel Gorman 		return 1;
25635515061dSMel Gorman 
256433906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
256533906bc5SMel Gorman 				sc.may_writepage,
256633906bc5SMel Gorman 				gfp_mask);
256733906bc5SMel Gorman 
2568a09ed5e0SYing Han 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
256933906bc5SMel Gorman 
257033906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
257133906bc5SMel Gorman 
257233906bc5SMel Gorman 	return nr_reclaimed;
257366e1707bSBalbir Singh }
257466e1707bSBalbir Singh 
2575c255a458SAndrew Morton #ifdef CONFIG_MEMCG
257666e1707bSBalbir Singh 
257772835c86SJohannes Weiner unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg,
25784e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
25790ae5e89cSYing Han 						struct zone *zone,
25800ae5e89cSYing Han 						unsigned long *nr_scanned)
25814e416953SBalbir Singh {
25824e416953SBalbir Singh 	struct scan_control sc = {
25830ae5e89cSYing Han 		.nr_scanned = 0,
2584b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
25854e416953SBalbir Singh 		.may_writepage = !laptop_mode,
25864e416953SBalbir Singh 		.may_unmap = 1,
25874e416953SBalbir Singh 		.may_swap = !noswap,
25884e416953SBalbir Singh 		.order = 0,
25899e3b2f8cSKonstantin Khlebnikov 		.priority = 0,
259072835c86SJohannes Weiner 		.target_mem_cgroup = memcg,
25914e416953SBalbir Singh 	};
2592f9be23d6SKonstantin Khlebnikov 	struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
25930ae5e89cSYing Han 
25944e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
25954e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2596bdce6d9eSKOSAKI Motohiro 
25979e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
2598bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
2599bdce6d9eSKOSAKI Motohiro 						      sc.gfp_mask);
2600bdce6d9eSKOSAKI Motohiro 
26014e416953SBalbir Singh 	/*
26024e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
26034e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
26044e416953SBalbir Singh 	 * if we don't reclaim here, the shrink_zone from balance_pgdat
26054e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
26064e416953SBalbir Singh 	 * the priority and make it zero.
26074e416953SBalbir Singh 	 */
2608f9be23d6SKonstantin Khlebnikov 	shrink_lruvec(lruvec, &sc);
2609bdce6d9eSKOSAKI Motohiro 
2610bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
2611bdce6d9eSKOSAKI Motohiro 
26120ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
26134e416953SBalbir Singh 	return sc.nr_reclaimed;
26144e416953SBalbir Singh }
26154e416953SBalbir Singh 
261672835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
26178c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
2618185efc0fSJohannes Weiner 					   bool noswap)
261966e1707bSBalbir Singh {
26204e416953SBalbir Singh 	struct zonelist *zonelist;
2621bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
2622889976dbSYing Han 	int nid;
262366e1707bSBalbir Singh 	struct scan_control sc = {
262466e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
2625a6dc60f8SJohannes Weiner 		.may_unmap = 1,
26262e2e4259SKOSAKI Motohiro 		.may_swap = !noswap,
262722fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
262866e1707bSBalbir Singh 		.order = 0,
26299e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
263072835c86SJohannes Weiner 		.target_mem_cgroup = memcg,
2631327c0e96SKAMEZAWA Hiroyuki 		.nodemask = NULL, /* we don't care the placement */
2632a09ed5e0SYing Han 		.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2633a09ed5e0SYing Han 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
2634a09ed5e0SYing Han 	};
2635a09ed5e0SYing Han 	struct shrink_control shrink = {
2636a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
263766e1707bSBalbir Singh 	};
263866e1707bSBalbir Singh 
2639889976dbSYing Han 	/*
2640889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
2641889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
2642889976dbSYing Han 	 * scan does not need to be the current node.
2643889976dbSYing Han 	 */
264472835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
2645889976dbSYing Han 
2646889976dbSYing Han 	zonelist = NODE_DATA(nid)->node_zonelists;
2647bdce6d9eSKOSAKI Motohiro 
2648bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
2649bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
2650bdce6d9eSKOSAKI Motohiro 					    sc.gfp_mask);
2651bdce6d9eSKOSAKI Motohiro 
2652a09ed5e0SYing Han 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
2653bdce6d9eSKOSAKI Motohiro 
2654bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
2655bdce6d9eSKOSAKI Motohiro 
2656bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
265766e1707bSBalbir Singh }
265866e1707bSBalbir Singh #endif
265966e1707bSBalbir Singh 
26609e3b2f8cSKonstantin Khlebnikov static void age_active_anon(struct zone *zone, struct scan_control *sc)
2661f16015fbSJohannes Weiner {
2662b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
2663b95a2f2dSJohannes Weiner 
2664b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
2665b95a2f2dSJohannes Weiner 		return;
2666b95a2f2dSJohannes Weiner 
2667b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
2668b95a2f2dSJohannes Weiner 	do {
2669c56d5c7dSKonstantin Khlebnikov 		struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
2670f16015fbSJohannes Weiner 
2671c56d5c7dSKonstantin Khlebnikov 		if (inactive_anon_is_low(lruvec))
26721a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
26739e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
2674b95a2f2dSJohannes Weiner 
2675b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
2676b95a2f2dSJohannes Weiner 	} while (memcg);
2677f16015fbSJohannes Weiner }
2678f16015fbSJohannes Weiner 
267960cefed4SJohannes Weiner static bool zone_balanced(struct zone *zone, int order,
268060cefed4SJohannes Weiner 			  unsigned long balance_gap, int classzone_idx)
268160cefed4SJohannes Weiner {
268260cefed4SJohannes Weiner 	if (!zone_watermark_ok_safe(zone, order, high_wmark_pages(zone) +
268360cefed4SJohannes Weiner 				    balance_gap, classzone_idx, 0))
268460cefed4SJohannes Weiner 		return false;
268560cefed4SJohannes Weiner 
2686d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && order &&
2687d84da3f9SKirill A. Shutemov 	    !compaction_suitable(zone, order))
268860cefed4SJohannes Weiner 		return false;
268960cefed4SJohannes Weiner 
269060cefed4SJohannes Weiner 	return true;
269160cefed4SJohannes Weiner }
269260cefed4SJohannes Weiner 
26931741c877SMel Gorman /*
26944ae0a48bSZlatko Calusic  * pgdat_balanced() is used when checking if a node is balanced.
26954ae0a48bSZlatko Calusic  *
26964ae0a48bSZlatko Calusic  * For order-0, all zones must be balanced!
26974ae0a48bSZlatko Calusic  *
26984ae0a48bSZlatko Calusic  * For high-order allocations only zones that meet watermarks and are in a
26994ae0a48bSZlatko Calusic  * zone allowed by the callers classzone_idx are added to balanced_pages. The
27004ae0a48bSZlatko Calusic  * total of balanced pages must be at least 25% of the zones allowed by
27014ae0a48bSZlatko Calusic  * classzone_idx for the node to be considered balanced. Forcing all zones to
27024ae0a48bSZlatko Calusic  * be balanced for high orders can cause excessive reclaim when there are
27034ae0a48bSZlatko Calusic  * imbalanced zones.
27041741c877SMel Gorman  * The choice of 25% is due to
27051741c877SMel Gorman  *   o a 16M DMA zone that is balanced will not balance a zone on any
27061741c877SMel Gorman  *     reasonable sized machine
27071741c877SMel Gorman  *   o On all other machines, the top zone must be at least a reasonable
270825985edcSLucas De Marchi  *     percentage of the middle zones. For example, on 32-bit x86, highmem
27091741c877SMel Gorman  *     would need to be at least 256M for it to be balance a whole node.
27101741c877SMel Gorman  *     Similarly, on x86-64 the Normal zone would need to be at least 1G
27111741c877SMel Gorman  *     to balance a node on its own. These seemed like reasonable ratios.
27121741c877SMel Gorman  */
27134ae0a48bSZlatko Calusic static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
27141741c877SMel Gorman {
2715b40da049SJiang Liu 	unsigned long managed_pages = 0;
27164ae0a48bSZlatko Calusic 	unsigned long balanced_pages = 0;
27171741c877SMel Gorman 	int i;
27181741c877SMel Gorman 
27194ae0a48bSZlatko Calusic 	/* Check the watermark levels */
27204ae0a48bSZlatko Calusic 	for (i = 0; i <= classzone_idx; i++) {
27214ae0a48bSZlatko Calusic 		struct zone *zone = pgdat->node_zones + i;
27221741c877SMel Gorman 
27234ae0a48bSZlatko Calusic 		if (!populated_zone(zone))
27244ae0a48bSZlatko Calusic 			continue;
27254ae0a48bSZlatko Calusic 
2726b40da049SJiang Liu 		managed_pages += zone->managed_pages;
27274ae0a48bSZlatko Calusic 
27284ae0a48bSZlatko Calusic 		/*
27294ae0a48bSZlatko Calusic 		 * A special case here:
27304ae0a48bSZlatko Calusic 		 *
27314ae0a48bSZlatko Calusic 		 * balance_pgdat() skips over all_unreclaimable after
27324ae0a48bSZlatko Calusic 		 * DEF_PRIORITY. Effectively, it considers them balanced so
27334ae0a48bSZlatko Calusic 		 * they must be considered balanced here as well!
27344ae0a48bSZlatko Calusic 		 */
27354ae0a48bSZlatko Calusic 		if (zone->all_unreclaimable) {
2736b40da049SJiang Liu 			balanced_pages += zone->managed_pages;
27374ae0a48bSZlatko Calusic 			continue;
27384ae0a48bSZlatko Calusic 		}
27394ae0a48bSZlatko Calusic 
27404ae0a48bSZlatko Calusic 		if (zone_balanced(zone, order, 0, i))
2741b40da049SJiang Liu 			balanced_pages += zone->managed_pages;
27424ae0a48bSZlatko Calusic 		else if (!order)
27434ae0a48bSZlatko Calusic 			return false;
27444ae0a48bSZlatko Calusic 	}
27454ae0a48bSZlatko Calusic 
27464ae0a48bSZlatko Calusic 	if (order)
2747b40da049SJiang Liu 		return balanced_pages >= (managed_pages >> 2);
27484ae0a48bSZlatko Calusic 	else
27494ae0a48bSZlatko Calusic 		return true;
27501741c877SMel Gorman }
27511741c877SMel Gorman 
27525515061dSMel Gorman /*
27535515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
27545515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
27555515061dSMel Gorman  *
27565515061dSMel Gorman  * Returns true if kswapd is ready to sleep
27575515061dSMel Gorman  */
27585515061dSMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, long remaining,
2759dc83edd9SMel Gorman 					int classzone_idx)
2760f50de2d3SMel Gorman {
2761f50de2d3SMel Gorman 	/* If a direct reclaimer woke kswapd within HZ/10, it's premature */
2762f50de2d3SMel Gorman 	if (remaining)
27635515061dSMel Gorman 		return false;
27645515061dSMel Gorman 
27655515061dSMel Gorman 	/*
27665515061dSMel Gorman 	 * There is a potential race between when kswapd checks its watermarks
27675515061dSMel Gorman 	 * and a process gets throttled. There is also a potential race if
27685515061dSMel Gorman 	 * processes get throttled, kswapd wakes, a large process exits therby
27695515061dSMel Gorman 	 * balancing the zones that causes kswapd to miss a wakeup. If kswapd
27705515061dSMel Gorman 	 * is going to sleep, no process should be sleeping on pfmemalloc_wait
27715515061dSMel Gorman 	 * so wake them now if necessary. If necessary, processes will wake
27725515061dSMel Gorman 	 * kswapd and get throttled again
27735515061dSMel Gorman 	 */
27745515061dSMel Gorman 	if (waitqueue_active(&pgdat->pfmemalloc_wait)) {
27755515061dSMel Gorman 		wake_up(&pgdat->pfmemalloc_wait);
27765515061dSMel Gorman 		return false;
27775515061dSMel Gorman 	}
2778f50de2d3SMel Gorman 
27794ae0a48bSZlatko Calusic 	return pgdat_balanced(pgdat, order, classzone_idx);
2780f50de2d3SMel Gorman }
2781f50de2d3SMel Gorman 
27821da177e4SLinus Torvalds /*
278375485363SMel Gorman  * kswapd shrinks the zone by the number of pages required to reach
278475485363SMel Gorman  * the high watermark.
2785b8e83b94SMel Gorman  *
2786b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
2787283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
2788283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
278975485363SMel Gorman  */
2790b8e83b94SMel Gorman static bool kswapd_shrink_zone(struct zone *zone,
27917c954f6dSMel Gorman 			       int classzone_idx,
279275485363SMel Gorman 			       struct scan_control *sc,
27932ab44f43SMel Gorman 			       unsigned long lru_pages,
27942ab44f43SMel Gorman 			       unsigned long *nr_attempted)
279575485363SMel Gorman {
279675485363SMel Gorman 	unsigned long nr_slab;
27977c954f6dSMel Gorman 	int testorder = sc->order;
27987c954f6dSMel Gorman 	unsigned long balance_gap;
279975485363SMel Gorman 	struct reclaim_state *reclaim_state = current->reclaim_state;
280075485363SMel Gorman 	struct shrink_control shrink = {
280175485363SMel Gorman 		.gfp_mask = sc->gfp_mask,
280275485363SMel Gorman 	};
28037c954f6dSMel Gorman 	bool lowmem_pressure;
280475485363SMel Gorman 
280575485363SMel Gorman 	/* Reclaim above the high watermark. */
280675485363SMel Gorman 	sc->nr_to_reclaim = max(SWAP_CLUSTER_MAX, high_wmark_pages(zone));
28077c954f6dSMel Gorman 
28087c954f6dSMel Gorman 	/*
28097c954f6dSMel Gorman 	 * Kswapd reclaims only single pages with compaction enabled. Trying
28107c954f6dSMel Gorman 	 * too hard to reclaim until contiguous free pages have become
28117c954f6dSMel Gorman 	 * available can hurt performance by evicting too much useful data
28127c954f6dSMel Gorman 	 * from memory. Do not reclaim more than needed for compaction.
28137c954f6dSMel Gorman 	 */
28147c954f6dSMel Gorman 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
28157c954f6dSMel Gorman 			compaction_suitable(zone, sc->order) !=
28167c954f6dSMel Gorman 				COMPACT_SKIPPED)
28177c954f6dSMel Gorman 		testorder = 0;
28187c954f6dSMel Gorman 
28197c954f6dSMel Gorman 	/*
28207c954f6dSMel Gorman 	 * We put equal pressure on every zone, unless one zone has way too
28217c954f6dSMel Gorman 	 * many pages free already. The "too many pages" is defined as the
28227c954f6dSMel Gorman 	 * high wmark plus a "gap" where the gap is either the low
28237c954f6dSMel Gorman 	 * watermark or 1% of the zone, whichever is smaller.
28247c954f6dSMel Gorman 	 */
28257c954f6dSMel Gorman 	balance_gap = min(low_wmark_pages(zone),
28267c954f6dSMel Gorman 		(zone->managed_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
28277c954f6dSMel Gorman 		KSWAPD_ZONE_BALANCE_GAP_RATIO);
28287c954f6dSMel Gorman 
28297c954f6dSMel Gorman 	/*
28307c954f6dSMel Gorman 	 * If there is no low memory pressure or the zone is balanced then no
28317c954f6dSMel Gorman 	 * reclaim is necessary
28327c954f6dSMel Gorman 	 */
28337c954f6dSMel Gorman 	lowmem_pressure = (buffer_heads_over_limit && is_highmem(zone));
28347c954f6dSMel Gorman 	if (!lowmem_pressure && zone_balanced(zone, testorder,
28357c954f6dSMel Gorman 						balance_gap, classzone_idx))
28367c954f6dSMel Gorman 		return true;
28377c954f6dSMel Gorman 
283875485363SMel Gorman 	shrink_zone(zone, sc);
283975485363SMel Gorman 
284075485363SMel Gorman 	reclaim_state->reclaimed_slab = 0;
284175485363SMel Gorman 	nr_slab = shrink_slab(&shrink, sc->nr_scanned, lru_pages);
284275485363SMel Gorman 	sc->nr_reclaimed += reclaim_state->reclaimed_slab;
284375485363SMel Gorman 
28442ab44f43SMel Gorman 	/* Account for the number of pages attempted to reclaim */
28452ab44f43SMel Gorman 	*nr_attempted += sc->nr_to_reclaim;
28462ab44f43SMel Gorman 
284775485363SMel Gorman 	if (nr_slab == 0 && !zone_reclaimable(zone))
284875485363SMel Gorman 		zone->all_unreclaimable = 1;
2849b8e83b94SMel Gorman 
2850283aba9fSMel Gorman 	zone_clear_flag(zone, ZONE_WRITEBACK);
2851283aba9fSMel Gorman 
28527c954f6dSMel Gorman 	/*
28537c954f6dSMel Gorman 	 * If a zone reaches its high watermark, consider it to be no longer
28547c954f6dSMel Gorman 	 * congested. It's possible there are dirty pages backed by congested
28557c954f6dSMel Gorman 	 * BDIs but as pressure is relieved, speculatively avoid congestion
28567c954f6dSMel Gorman 	 * waits.
28577c954f6dSMel Gorman 	 */
28587c954f6dSMel Gorman 	if (!zone->all_unreclaimable &&
28597c954f6dSMel Gorman 	    zone_balanced(zone, testorder, 0, classzone_idx)) {
28607c954f6dSMel Gorman 		zone_clear_flag(zone, ZONE_CONGESTED);
28617c954f6dSMel Gorman 		zone_clear_flag(zone, ZONE_TAIL_LRU_DIRTY);
28627c954f6dSMel Gorman 	}
28637c954f6dSMel Gorman 
2864b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
286575485363SMel Gorman }
286675485363SMel Gorman 
286775485363SMel Gorman /*
28681da177e4SLinus Torvalds  * For kswapd, balance_pgdat() will work across all this node's zones until
286941858966SMel Gorman  * they are all at high_wmark_pages(zone).
28701da177e4SLinus Torvalds  *
28710abdee2bSMel Gorman  * Returns the final order kswapd was reclaiming at
28721da177e4SLinus Torvalds  *
28731da177e4SLinus Torvalds  * There is special handling here for zones which are full of pinned pages.
28741da177e4SLinus Torvalds  * This can happen if the pages are all mlocked, or if they are all used by
28751da177e4SLinus Torvalds  * device drivers (say, ZONE_DMA).  Or if they are all in use by hugetlb.
28761da177e4SLinus Torvalds  * What we do is to detect the case where all pages in the zone have been
28771da177e4SLinus Torvalds  * scanned twice and there has been zero successful reclaim.  Mark the zone as
28781da177e4SLinus Torvalds  * dead and from now on, only perform a short scan.  Basically we're polling
28791da177e4SLinus Torvalds  * the zone for when the problem goes away.
28801da177e4SLinus Torvalds  *
28811da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
288241858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
288341858966SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
288441858966SMel Gorman  * lower zones regardless of the number of free pages in the lower zones. This
288541858966SMel Gorman  * interoperates with the page allocator fallback scheme to ensure that aging
288641858966SMel Gorman  * of pages is balanced across the zones.
28871da177e4SLinus Torvalds  */
288899504748SMel Gorman static unsigned long balance_pgdat(pg_data_t *pgdat, int order,
2889dc83edd9SMel Gorman 							int *classzone_idx)
28901da177e4SLinus Torvalds {
28911da177e4SLinus Torvalds 	int i;
289299504748SMel Gorman 	int end_zone = 0;	/* Inclusive.  0 = ZONE_DMA */
28930ae5e89cSYing Han 	unsigned long nr_soft_reclaimed;
28940ae5e89cSYing Han 	unsigned long nr_soft_scanned;
2895179e9639SAndrew Morton 	struct scan_control sc = {
2896179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
2897b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
2898a6dc60f8SJohannes Weiner 		.may_unmap = 1,
28992e2e4259SKOSAKI Motohiro 		.may_swap = 1,
2900b8e83b94SMel Gorman 		.may_writepage = !laptop_mode,
29015ad333ebSAndy Whitcroft 		.order = order,
2902f16015fbSJohannes Weiner 		.target_mem_cgroup = NULL,
2903179e9639SAndrew Morton 	};
2904f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
29051da177e4SLinus Torvalds 
29069e3b2f8cSKonstantin Khlebnikov 	do {
29071da177e4SLinus Torvalds 		unsigned long lru_pages = 0;
29082ab44f43SMel Gorman 		unsigned long nr_attempted = 0;
2909b8e83b94SMel Gorman 		bool raise_priority = true;
29102ab44f43SMel Gorman 		bool pgdat_needs_compaction = (order > 0);
2911b8e83b94SMel Gorman 
2912b8e83b94SMel Gorman 		sc.nr_reclaimed = 0;
29131da177e4SLinus Torvalds 
29141da177e4SLinus Torvalds 		/*
29151da177e4SLinus Torvalds 		 * Scan in the highmem->dma direction for the highest
29161da177e4SLinus Torvalds 		 * zone which needs scanning
29171da177e4SLinus Torvalds 		 */
29181da177e4SLinus Torvalds 		for (i = pgdat->nr_zones - 1; i >= 0; i--) {
29191da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
29201da177e4SLinus Torvalds 
2921f3fe6512SCon Kolivas 			if (!populated_zone(zone))
29221da177e4SLinus Torvalds 				continue;
29231da177e4SLinus Torvalds 
29249e3b2f8cSKonstantin Khlebnikov 			if (zone->all_unreclaimable &&
29259e3b2f8cSKonstantin Khlebnikov 			    sc.priority != DEF_PRIORITY)
29261da177e4SLinus Torvalds 				continue;
29271da177e4SLinus Torvalds 
2928556adecbSRik van Riel 			/*
2929556adecbSRik van Riel 			 * Do some background aging of the anon list, to give
2930556adecbSRik van Riel 			 * pages a chance to be referenced before reclaiming.
2931556adecbSRik van Riel 			 */
29329e3b2f8cSKonstantin Khlebnikov 			age_active_anon(zone, &sc);
2933556adecbSRik van Riel 
2934cc715d99SMel Gorman 			/*
2935cc715d99SMel Gorman 			 * If the number of buffer_heads in the machine
2936cc715d99SMel Gorman 			 * exceeds the maximum allowed level and this node
2937cc715d99SMel Gorman 			 * has a highmem zone, force kswapd to reclaim from
2938cc715d99SMel Gorman 			 * it to relieve lowmem pressure.
2939cc715d99SMel Gorman 			 */
2940cc715d99SMel Gorman 			if (buffer_heads_over_limit && is_highmem_idx(i)) {
2941cc715d99SMel Gorman 				end_zone = i;
2942cc715d99SMel Gorman 				break;
2943cc715d99SMel Gorman 			}
2944cc715d99SMel Gorman 
294560cefed4SJohannes Weiner 			if (!zone_balanced(zone, order, 0, 0)) {
29461da177e4SLinus Torvalds 				end_zone = i;
2947e1dbeda6SAndrew Morton 				break;
2948439423f6SShaohua Li 			} else {
2949d43006d5SMel Gorman 				/*
2950d43006d5SMel Gorman 				 * If balanced, clear the dirty and congested
2951d43006d5SMel Gorman 				 * flags
2952d43006d5SMel Gorman 				 */
2953439423f6SShaohua Li 				zone_clear_flag(zone, ZONE_CONGESTED);
2954d43006d5SMel Gorman 				zone_clear_flag(zone, ZONE_TAIL_LRU_DIRTY);
29551da177e4SLinus Torvalds 			}
29561da177e4SLinus Torvalds 		}
2957dafcb73eSZlatko Calusic 
2958b8e83b94SMel Gorman 		if (i < 0)
29591da177e4SLinus Torvalds 			goto out;
2960e1dbeda6SAndrew Morton 
29611da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
29621da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
29631da177e4SLinus Torvalds 
29642ab44f43SMel Gorman 			if (!populated_zone(zone))
29652ab44f43SMel Gorman 				continue;
29662ab44f43SMel Gorman 
2967adea02a1SWu Fengguang 			lru_pages += zone_reclaimable_pages(zone);
29682ab44f43SMel Gorman 
29692ab44f43SMel Gorman 			/*
29702ab44f43SMel Gorman 			 * If any zone is currently balanced then kswapd will
29712ab44f43SMel Gorman 			 * not call compaction as it is expected that the
29722ab44f43SMel Gorman 			 * necessary pages are already available.
29732ab44f43SMel Gorman 			 */
29742ab44f43SMel Gorman 			if (pgdat_needs_compaction &&
29752ab44f43SMel Gorman 					zone_watermark_ok(zone, order,
29762ab44f43SMel Gorman 						low_wmark_pages(zone),
29772ab44f43SMel Gorman 						*classzone_idx, 0))
29782ab44f43SMel Gorman 				pgdat_needs_compaction = false;
29791da177e4SLinus Torvalds 		}
29801da177e4SLinus Torvalds 
29811da177e4SLinus Torvalds 		/*
2982b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
2983b7ea3c41SMel Gorman 		 * even in laptop mode.
2984b7ea3c41SMel Gorman 		 */
2985b7ea3c41SMel Gorman 		if (sc.priority < DEF_PRIORITY - 2)
2986b7ea3c41SMel Gorman 			sc.may_writepage = 1;
2987b7ea3c41SMel Gorman 
2988b7ea3c41SMel Gorman 		/*
29891da177e4SLinus Torvalds 		 * Now scan the zone in the dma->highmem direction, stopping
29901da177e4SLinus Torvalds 		 * at the last zone which needs scanning.
29911da177e4SLinus Torvalds 		 *
29921da177e4SLinus Torvalds 		 * We do this because the page allocator works in the opposite
29931da177e4SLinus Torvalds 		 * direction.  This prevents the page allocator from allocating
29941da177e4SLinus Torvalds 		 * pages behind kswapd's direction of progress, which would
29951da177e4SLinus Torvalds 		 * cause too much scanning of the lower zones.
29961da177e4SLinus Torvalds 		 */
29971da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
29981da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
29991da177e4SLinus Torvalds 
3000f3fe6512SCon Kolivas 			if (!populated_zone(zone))
30011da177e4SLinus Torvalds 				continue;
30021da177e4SLinus Torvalds 
30039e3b2f8cSKonstantin Khlebnikov 			if (zone->all_unreclaimable &&
30049e3b2f8cSKonstantin Khlebnikov 			    sc.priority != DEF_PRIORITY)
30051da177e4SLinus Torvalds 				continue;
30061da177e4SLinus Torvalds 
30071da177e4SLinus Torvalds 			sc.nr_scanned = 0;
30084e416953SBalbir Singh 
30090ae5e89cSYing Han 			nr_soft_scanned = 0;
30104e416953SBalbir Singh 			/*
30114e416953SBalbir Singh 			 * Call soft limit reclaim before calling shrink_zone.
30124e416953SBalbir Singh 			 */
30130ae5e89cSYing Han 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
30140ae5e89cSYing Han 							order, sc.gfp_mask,
30150ae5e89cSYing Han 							&nr_soft_scanned);
30160ae5e89cSYing Han 			sc.nr_reclaimed += nr_soft_reclaimed;
301700918b6aSKOSAKI Motohiro 
301832a4330dSRik van Riel 			/*
30197c954f6dSMel Gorman 			 * There should be no need to raise the scanning
30207c954f6dSMel Gorman 			 * priority if enough pages are already being scanned
30217c954f6dSMel Gorman 			 * that that high watermark would be met at 100%
30227c954f6dSMel Gorman 			 * efficiency.
302332a4330dSRik van Riel 			 */
30247c954f6dSMel Gorman 			if (kswapd_shrink_zone(zone, end_zone, &sc,
30257c954f6dSMel Gorman 					lru_pages, &nr_attempted))
3026b8e83b94SMel Gorman 				raise_priority = false;
3027b8e83b94SMel Gorman 		}
3028d7868daeSMel Gorman 
30295515061dSMel Gorman 		/*
30305515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
30315515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
30325515061dSMel Gorman 		 * able to safely make forward progress. Wake them
30335515061dSMel Gorman 		 */
30345515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
30355515061dSMel Gorman 				pfmemalloc_watermark_ok(pgdat))
30365515061dSMel Gorman 			wake_up(&pgdat->pfmemalloc_wait);
30375515061dSMel Gorman 
30381da177e4SLinus Torvalds 		/*
3039b8e83b94SMel Gorman 		 * Fragmentation may mean that the system cannot be rebalanced
3040b8e83b94SMel Gorman 		 * for high-order allocations in all zones. If twice the
3041b8e83b94SMel Gorman 		 * allocation size has been reclaimed and the zones are still
3042b8e83b94SMel Gorman 		 * not balanced then recheck the watermarks at order-0 to
3043b8e83b94SMel Gorman 		 * prevent kswapd reclaiming excessively. Assume that a
3044b8e83b94SMel Gorman 		 * process requested a high-order can direct reclaim/compact.
30451da177e4SLinus Torvalds 		 */
3046b8e83b94SMel Gorman 		if (order && sc.nr_reclaimed >= 2UL << order)
304773ce02e9SKOSAKI Motohiro 			order = sc.order = 0;
304873ce02e9SKOSAKI Motohiro 
3049b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
3050b8e83b94SMel Gorman 		if (try_to_freeze() || kthread_should_stop())
3051b8e83b94SMel Gorman 			break;
3052b8e83b94SMel Gorman 
3053b8e83b94SMel Gorman 		/*
30542ab44f43SMel Gorman 		 * Compact if necessary and kswapd is reclaiming at least the
30552ab44f43SMel Gorman 		 * high watermark number of pages as requsted
30562ab44f43SMel Gorman 		 */
30572ab44f43SMel Gorman 		if (pgdat_needs_compaction && sc.nr_reclaimed > nr_attempted)
30582ab44f43SMel Gorman 			compact_pgdat(pgdat, order);
30592ab44f43SMel Gorman 
30602ab44f43SMel Gorman 		/*
3061b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3062b8e83b94SMel Gorman 		 * progress in reclaiming pages
3063b8e83b94SMel Gorman 		 */
3064b8e83b94SMel Gorman 		if (raise_priority || !sc.nr_reclaimed)
3065b8e83b94SMel Gorman 			sc.priority--;
30669aa41348SMel Gorman 	} while (sc.priority >= 1 &&
3067b8e83b94SMel Gorman 		 !pgdat_balanced(pgdat, order, *classzone_idx));
30681da177e4SLinus Torvalds 
3069b8e83b94SMel Gorman out:
30700abdee2bSMel Gorman 	/*
30715515061dSMel Gorman 	 * Return the order we were reclaiming at so prepare_kswapd_sleep()
30720abdee2bSMel Gorman 	 * makes a decision on the order we were last reclaiming at. However,
30730abdee2bSMel Gorman 	 * if another caller entered the allocator slow path while kswapd
30740abdee2bSMel Gorman 	 * was awake, order will remain at the higher level
30750abdee2bSMel Gorman 	 */
3076dc83edd9SMel Gorman 	*classzone_idx = end_zone;
30770abdee2bSMel Gorman 	return order;
30781da177e4SLinus Torvalds }
30791da177e4SLinus Torvalds 
3080dc83edd9SMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3081f0bc0a60SKOSAKI Motohiro {
3082f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3083f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3084f0bc0a60SKOSAKI Motohiro 
3085f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3086f0bc0a60SKOSAKI Motohiro 		return;
3087f0bc0a60SKOSAKI Motohiro 
3088f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3089f0bc0a60SKOSAKI Motohiro 
3090f0bc0a60SKOSAKI Motohiro 	/* Try to sleep for a short interval */
30915515061dSMel Gorman 	if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
3092f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
3093f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3094f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3095f0bc0a60SKOSAKI Motohiro 	}
3096f0bc0a60SKOSAKI Motohiro 
3097f0bc0a60SKOSAKI Motohiro 	/*
3098f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3099f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3100f0bc0a60SKOSAKI Motohiro 	 */
31015515061dSMel Gorman 	if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
3102f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3103f0bc0a60SKOSAKI Motohiro 
3104f0bc0a60SKOSAKI Motohiro 		/*
3105f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3106f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3107f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3108f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3109f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3110f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3111f0bc0a60SKOSAKI Motohiro 		 */
3112f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
31131c7e7f6cSAaditya Kumar 
311462997027SMel Gorman 		/*
311562997027SMel Gorman 		 * Compaction records what page blocks it recently failed to
311662997027SMel Gorman 		 * isolate pages from and skips them in the future scanning.
311762997027SMel Gorman 		 * When kswapd is going to sleep, it is reasonable to assume
311862997027SMel Gorman 		 * that pages and compaction may succeed so reset the cache.
311962997027SMel Gorman 		 */
312062997027SMel Gorman 		reset_isolation_suitable(pgdat);
312162997027SMel Gorman 
31221c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3123f0bc0a60SKOSAKI Motohiro 			schedule();
31241c7e7f6cSAaditya Kumar 
3125f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3126f0bc0a60SKOSAKI Motohiro 	} else {
3127f0bc0a60SKOSAKI Motohiro 		if (remaining)
3128f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3129f0bc0a60SKOSAKI Motohiro 		else
3130f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3131f0bc0a60SKOSAKI Motohiro 	}
3132f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3133f0bc0a60SKOSAKI Motohiro }
3134f0bc0a60SKOSAKI Motohiro 
31351da177e4SLinus Torvalds /*
31361da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
31371da177e4SLinus Torvalds  * from the init process.
31381da177e4SLinus Torvalds  *
31391da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
31401da177e4SLinus Torvalds  * free memory available even if there is no other activity
31411da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
31421da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
31431da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
31441da177e4SLinus Torvalds  *
31451da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
31461da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
31471da177e4SLinus Torvalds  */
31481da177e4SLinus Torvalds static int kswapd(void *p)
31491da177e4SLinus Torvalds {
3150215ddd66SMel Gorman 	unsigned long order, new_order;
3151d2ebd0f6SAlex,Shi 	unsigned balanced_order;
3152215ddd66SMel Gorman 	int classzone_idx, new_classzone_idx;
3153d2ebd0f6SAlex,Shi 	int balanced_classzone_idx;
31541da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
31551da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3156f0bc0a60SKOSAKI Motohiro 
31571da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
31581da177e4SLinus Torvalds 		.reclaimed_slab = 0,
31591da177e4SLinus Torvalds 	};
3160a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
31611da177e4SLinus Torvalds 
3162cf40bd16SNick Piggin 	lockdep_set_current_reclaim_state(GFP_KERNEL);
3163cf40bd16SNick Piggin 
3164174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3165c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
31661da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
31671da177e4SLinus Torvalds 
31681da177e4SLinus Torvalds 	/*
31691da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
31701da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
31711da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
31721da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
31731da177e4SLinus Torvalds 	 *
31741da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
31751da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
31761da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
31771da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
31781da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
31791da177e4SLinus Torvalds 	 */
3180930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
318183144186SRafael J. Wysocki 	set_freezable();
31821da177e4SLinus Torvalds 
3183215ddd66SMel Gorman 	order = new_order = 0;
3184d2ebd0f6SAlex,Shi 	balanced_order = 0;
3185215ddd66SMel Gorman 	classzone_idx = new_classzone_idx = pgdat->nr_zones - 1;
3186d2ebd0f6SAlex,Shi 	balanced_classzone_idx = classzone_idx;
31871da177e4SLinus Torvalds 	for ( ; ; ) {
31886f6313d4SJeff Liu 		bool ret;
31893e1d1d28SChristoph Lameter 
3190215ddd66SMel Gorman 		/*
3191215ddd66SMel Gorman 		 * If the last balance_pgdat was unsuccessful it's unlikely a
3192215ddd66SMel Gorman 		 * new request of a similar or harder type will succeed soon
3193215ddd66SMel Gorman 		 * so consider going to sleep on the basis we reclaimed at
3194215ddd66SMel Gorman 		 */
3195d2ebd0f6SAlex,Shi 		if (balanced_classzone_idx >= new_classzone_idx &&
3196d2ebd0f6SAlex,Shi 					balanced_order == new_order) {
31971da177e4SLinus Torvalds 			new_order = pgdat->kswapd_max_order;
319899504748SMel Gorman 			new_classzone_idx = pgdat->classzone_idx;
31991da177e4SLinus Torvalds 			pgdat->kswapd_max_order =  0;
3200215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
3201215ddd66SMel Gorman 		}
3202215ddd66SMel Gorman 
320399504748SMel Gorman 		if (order < new_order || classzone_idx > new_classzone_idx) {
32041da177e4SLinus Torvalds 			/*
32051da177e4SLinus Torvalds 			 * Don't sleep if someone wants a larger 'order'
320699504748SMel Gorman 			 * allocation or has tigher zone constraints
32071da177e4SLinus Torvalds 			 */
32081da177e4SLinus Torvalds 			order = new_order;
320999504748SMel Gorman 			classzone_idx = new_classzone_idx;
32101da177e4SLinus Torvalds 		} else {
3211d2ebd0f6SAlex,Shi 			kswapd_try_to_sleep(pgdat, balanced_order,
3212d2ebd0f6SAlex,Shi 						balanced_classzone_idx);
32131da177e4SLinus Torvalds 			order = pgdat->kswapd_max_order;
321499504748SMel Gorman 			classzone_idx = pgdat->classzone_idx;
3215f0dfcde0SAlex,Shi 			new_order = order;
3216f0dfcde0SAlex,Shi 			new_classzone_idx = classzone_idx;
32174d40502eSMel Gorman 			pgdat->kswapd_max_order = 0;
3218215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
32191da177e4SLinus Torvalds 		}
32201da177e4SLinus Torvalds 
32218fe23e05SDavid Rientjes 		ret = try_to_freeze();
32228fe23e05SDavid Rientjes 		if (kthread_should_stop())
32238fe23e05SDavid Rientjes 			break;
32248fe23e05SDavid Rientjes 
32258fe23e05SDavid Rientjes 		/*
32268fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
32278fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3228b1296cc4SRafael J. Wysocki 		 */
322933906bc5SMel Gorman 		if (!ret) {
323033906bc5SMel Gorman 			trace_mm_vmscan_kswapd_wake(pgdat->node_id, order);
3231d2ebd0f6SAlex,Shi 			balanced_classzone_idx = classzone_idx;
3232d2ebd0f6SAlex,Shi 			balanced_order = balance_pgdat(pgdat, order,
3233d2ebd0f6SAlex,Shi 						&balanced_classzone_idx);
32341da177e4SLinus Torvalds 		}
323533906bc5SMel Gorman 	}
3236b0a8cc58STakamori Yamaguchi 
3237b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
32381da177e4SLinus Torvalds 	return 0;
32391da177e4SLinus Torvalds }
32401da177e4SLinus Torvalds 
32411da177e4SLinus Torvalds /*
32421da177e4SLinus Torvalds  * A zone is low on free memory, so wake its kswapd task to service it.
32431da177e4SLinus Torvalds  */
324499504748SMel Gorman void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
32451da177e4SLinus Torvalds {
32461da177e4SLinus Torvalds 	pg_data_t *pgdat;
32471da177e4SLinus Torvalds 
3248f3fe6512SCon Kolivas 	if (!populated_zone(zone))
32491da177e4SLinus Torvalds 		return;
32501da177e4SLinus Torvalds 
325102a0e53dSPaul Jackson 	if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
32521da177e4SLinus Torvalds 		return;
325388f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
325499504748SMel Gorman 	if (pgdat->kswapd_max_order < order) {
325588f5acf8SMel Gorman 		pgdat->kswapd_max_order = order;
325699504748SMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx);
325799504748SMel Gorman 	}
32588d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
32591da177e4SLinus Torvalds 		return;
326088f5acf8SMel Gorman 	if (zone_watermark_ok_safe(zone, order, low_wmark_pages(zone), 0, 0))
326188f5acf8SMel Gorman 		return;
326288f5acf8SMel Gorman 
326388f5acf8SMel Gorman 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
32648d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
32651da177e4SLinus Torvalds }
32661da177e4SLinus Torvalds 
3267adea02a1SWu Fengguang /*
3268adea02a1SWu Fengguang  * The reclaimable count would be mostly accurate.
3269adea02a1SWu Fengguang  * The less reclaimable pages may be
3270adea02a1SWu Fengguang  * - mlocked pages, which will be moved to unevictable list when encountered
3271adea02a1SWu Fengguang  * - mapped pages, which may require several travels to be reclaimed
3272adea02a1SWu Fengguang  * - dirty pages, which is not "instantly" reclaimable
3273adea02a1SWu Fengguang  */
3274adea02a1SWu Fengguang unsigned long global_reclaimable_pages(void)
32754f98a2feSRik van Riel {
3276adea02a1SWu Fengguang 	int nr;
3277adea02a1SWu Fengguang 
3278adea02a1SWu Fengguang 	nr = global_page_state(NR_ACTIVE_FILE) +
3279adea02a1SWu Fengguang 	     global_page_state(NR_INACTIVE_FILE);
3280adea02a1SWu Fengguang 
3281ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
3282adea02a1SWu Fengguang 		nr += global_page_state(NR_ACTIVE_ANON) +
3283adea02a1SWu Fengguang 		      global_page_state(NR_INACTIVE_ANON);
3284adea02a1SWu Fengguang 
3285adea02a1SWu Fengguang 	return nr;
3286adea02a1SWu Fengguang }
3287adea02a1SWu Fengguang 
3288adea02a1SWu Fengguang unsigned long zone_reclaimable_pages(struct zone *zone)
3289adea02a1SWu Fengguang {
3290adea02a1SWu Fengguang 	int nr;
3291adea02a1SWu Fengguang 
3292adea02a1SWu Fengguang 	nr = zone_page_state(zone, NR_ACTIVE_FILE) +
3293adea02a1SWu Fengguang 	     zone_page_state(zone, NR_INACTIVE_FILE);
3294adea02a1SWu Fengguang 
3295ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
3296adea02a1SWu Fengguang 		nr += zone_page_state(zone, NR_ACTIVE_ANON) +
3297adea02a1SWu Fengguang 		      zone_page_state(zone, NR_INACTIVE_ANON);
3298adea02a1SWu Fengguang 
3299adea02a1SWu Fengguang 	return nr;
33004f98a2feSRik van Riel }
33014f98a2feSRik van Riel 
3302c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
33031da177e4SLinus Torvalds /*
33047b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3305d6277db4SRafael J. Wysocki  * freed pages.
3306d6277db4SRafael J. Wysocki  *
3307d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3308d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3309d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
33101da177e4SLinus Torvalds  */
33117b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
33121da177e4SLinus Torvalds {
3313d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3314d6277db4SRafael J. Wysocki 	struct scan_control sc = {
33157b51755cSKOSAKI Motohiro 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
33167b51755cSKOSAKI Motohiro 		.may_swap = 1,
33177b51755cSKOSAKI Motohiro 		.may_unmap = 1,
3318d6277db4SRafael J. Wysocki 		.may_writepage = 1,
33197b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
33207b51755cSKOSAKI Motohiro 		.hibernation_mode = 1,
33217b51755cSKOSAKI Motohiro 		.order = 0,
33229e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
33231da177e4SLinus Torvalds 	};
3324a09ed5e0SYing Han 	struct shrink_control shrink = {
3325a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
3326a09ed5e0SYing Han 	};
33277b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
33287b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
33297b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
33301da177e4SLinus Torvalds 
33317b51755cSKOSAKI Motohiro 	p->flags |= PF_MEMALLOC;
33327b51755cSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(sc.gfp_mask);
3333d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
33347b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3335d6277db4SRafael J. Wysocki 
3336a09ed5e0SYing Han 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
3337d6277db4SRafael J. Wysocki 
33387b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
33397b51755cSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
33407b51755cSKOSAKI Motohiro 	p->flags &= ~PF_MEMALLOC;
3341d6277db4SRafael J. Wysocki 
33427b51755cSKOSAKI Motohiro 	return nr_reclaimed;
33431da177e4SLinus Torvalds }
3344c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
33451da177e4SLinus Torvalds 
33461da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
33471da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
33481da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
33491da177e4SLinus Torvalds    restore their cpu bindings. */
3350fcb35a9bSGreg Kroah-Hartman static int cpu_callback(struct notifier_block *nfb, unsigned long action,
3351fcb35a9bSGreg Kroah-Hartman 			void *hcpu)
33521da177e4SLinus Torvalds {
335358c0a4a7SYasunori Goto 	int nid;
33541da177e4SLinus Torvalds 
33558bb78442SRafael J. Wysocki 	if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
335648fb2e24SLai Jiangshan 		for_each_node_state(nid, N_MEMORY) {
3357c5f59f08SMike Travis 			pg_data_t *pgdat = NODE_DATA(nid);
3358a70f7302SRusty Russell 			const struct cpumask *mask;
3359a70f7302SRusty Russell 
3360a70f7302SRusty Russell 			mask = cpumask_of_node(pgdat->node_id);
3361c5f59f08SMike Travis 
33623e597945SRusty Russell 			if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
33631da177e4SLinus Torvalds 				/* One of our CPUs online: restore mask */
3364c5f59f08SMike Travis 				set_cpus_allowed_ptr(pgdat->kswapd, mask);
33651da177e4SLinus Torvalds 		}
33661da177e4SLinus Torvalds 	}
33671da177e4SLinus Torvalds 	return NOTIFY_OK;
33681da177e4SLinus Torvalds }
33691da177e4SLinus Torvalds 
33703218ae14SYasunori Goto /*
33713218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
33723218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
33733218ae14SYasunori Goto  */
33743218ae14SYasunori Goto int kswapd_run(int nid)
33753218ae14SYasunori Goto {
33763218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
33773218ae14SYasunori Goto 	int ret = 0;
33783218ae14SYasunori Goto 
33793218ae14SYasunori Goto 	if (pgdat->kswapd)
33803218ae14SYasunori Goto 		return 0;
33813218ae14SYasunori Goto 
33823218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
33833218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
33843218ae14SYasunori Goto 		/* failure at boot is fatal */
33853218ae14SYasunori Goto 		BUG_ON(system_state == SYSTEM_BOOTING);
3386d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3387d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3388d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
33893218ae14SYasunori Goto 	}
33903218ae14SYasunori Goto 	return ret;
33913218ae14SYasunori Goto }
33923218ae14SYasunori Goto 
33938fe23e05SDavid Rientjes /*
3394d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3395d8adde17SJiang Liu  * hold lock_memory_hotplug().
33968fe23e05SDavid Rientjes  */
33978fe23e05SDavid Rientjes void kswapd_stop(int nid)
33988fe23e05SDavid Rientjes {
33998fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
34008fe23e05SDavid Rientjes 
3401d8adde17SJiang Liu 	if (kswapd) {
34028fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3403d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3404d8adde17SJiang Liu 	}
34058fe23e05SDavid Rientjes }
34068fe23e05SDavid Rientjes 
34071da177e4SLinus Torvalds static int __init kswapd_init(void)
34081da177e4SLinus Torvalds {
34093218ae14SYasunori Goto 	int nid;
341069e05944SAndrew Morton 
34111da177e4SLinus Torvalds 	swap_setup();
341248fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
34133218ae14SYasunori Goto  		kswapd_run(nid);
34141da177e4SLinus Torvalds 	hotcpu_notifier(cpu_callback, 0);
34151da177e4SLinus Torvalds 	return 0;
34161da177e4SLinus Torvalds }
34171da177e4SLinus Torvalds 
34181da177e4SLinus Torvalds module_init(kswapd_init)
34199eeff239SChristoph Lameter 
34209eeff239SChristoph Lameter #ifdef CONFIG_NUMA
34219eeff239SChristoph Lameter /*
34229eeff239SChristoph Lameter  * Zone reclaim mode
34239eeff239SChristoph Lameter  *
34249eeff239SChristoph Lameter  * If non-zero call zone_reclaim when the number of free pages falls below
34259eeff239SChristoph Lameter  * the watermarks.
34269eeff239SChristoph Lameter  */
34279eeff239SChristoph Lameter int zone_reclaim_mode __read_mostly;
34289eeff239SChristoph Lameter 
34291b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
34307d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
34311b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
34321b2ffb78SChristoph Lameter #define RECLAIM_SWAP (1<<2)	/* Swap pages out during reclaim */
34331b2ffb78SChristoph Lameter 
34349eeff239SChristoph Lameter /*
3435a92f7126SChristoph Lameter  * Priority for ZONE_RECLAIM. This determines the fraction of pages
3436a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3437a92f7126SChristoph Lameter  * a zone.
3438a92f7126SChristoph Lameter  */
3439a92f7126SChristoph Lameter #define ZONE_RECLAIM_PRIORITY 4
3440a92f7126SChristoph Lameter 
34419eeff239SChristoph Lameter /*
34429614634fSChristoph Lameter  * Percentage of pages in a zone that must be unmapped for zone_reclaim to
34439614634fSChristoph Lameter  * occur.
34449614634fSChristoph Lameter  */
34459614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
34469614634fSChristoph Lameter 
34479614634fSChristoph Lameter /*
34480ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
34490ff38490SChristoph Lameter  * slab reclaim needs to occur.
34500ff38490SChristoph Lameter  */
34510ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
34520ff38490SChristoph Lameter 
345390afa5deSMel Gorman static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
345490afa5deSMel Gorman {
345590afa5deSMel Gorman 	unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
345690afa5deSMel Gorman 	unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
345790afa5deSMel Gorman 		zone_page_state(zone, NR_ACTIVE_FILE);
345890afa5deSMel Gorman 
345990afa5deSMel Gorman 	/*
346090afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
346190afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
346290afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
346390afa5deSMel Gorman 	 */
346490afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
346590afa5deSMel Gorman }
346690afa5deSMel Gorman 
346790afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
346890afa5deSMel Gorman static long zone_pagecache_reclaimable(struct zone *zone)
346990afa5deSMel Gorman {
347090afa5deSMel Gorman 	long nr_pagecache_reclaimable;
347190afa5deSMel Gorman 	long delta = 0;
347290afa5deSMel Gorman 
347390afa5deSMel Gorman 	/*
347490afa5deSMel Gorman 	 * If RECLAIM_SWAP is set, then all file pages are considered
347590afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
347690afa5deSMel Gorman 	 * pages like swapcache and zone_unmapped_file_pages() provides
347790afa5deSMel Gorman 	 * a better estimate
347890afa5deSMel Gorman 	 */
347990afa5deSMel Gorman 	if (zone_reclaim_mode & RECLAIM_SWAP)
348090afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
348190afa5deSMel Gorman 	else
348290afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
348390afa5deSMel Gorman 
348490afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
348590afa5deSMel Gorman 	if (!(zone_reclaim_mode & RECLAIM_WRITE))
348690afa5deSMel Gorman 		delta += zone_page_state(zone, NR_FILE_DIRTY);
348790afa5deSMel Gorman 
348890afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
348990afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
349090afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
349190afa5deSMel Gorman 
349290afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
349390afa5deSMel Gorman }
349490afa5deSMel Gorman 
34950ff38490SChristoph Lameter /*
34969eeff239SChristoph Lameter  * Try to free up some pages from this zone through reclaim.
34979eeff239SChristoph Lameter  */
3498179e9639SAndrew Morton static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
34999eeff239SChristoph Lameter {
35007fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
350169e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
35029eeff239SChristoph Lameter 	struct task_struct *p = current;
35039eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
3504179e9639SAndrew Morton 	struct scan_control sc = {
3505179e9639SAndrew Morton 		.may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
3506a6dc60f8SJohannes Weiner 		.may_unmap = !!(zone_reclaim_mode & RECLAIM_SWAP),
35072e2e4259SKOSAKI Motohiro 		.may_swap = 1,
350862b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
350921caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
3510bd2f6199SJohannes Weiner 		.order = order,
35119e3b2f8cSKonstantin Khlebnikov 		.priority = ZONE_RECLAIM_PRIORITY,
3512179e9639SAndrew Morton 	};
3513a09ed5e0SYing Han 	struct shrink_control shrink = {
3514a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
3515a09ed5e0SYing Han 	};
351615748048SKOSAKI Motohiro 	unsigned long nr_slab_pages0, nr_slab_pages1;
35179eeff239SChristoph Lameter 
35189eeff239SChristoph Lameter 	cond_resched();
3519d4f7796eSChristoph Lameter 	/*
3520d4f7796eSChristoph Lameter 	 * We need to be able to allocate from the reserves for RECLAIM_SWAP
3521d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
3522d4f7796eSChristoph Lameter 	 * and RECLAIM_SWAP.
3523d4f7796eSChristoph Lameter 	 */
3524d4f7796eSChristoph Lameter 	p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
352576ca542dSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(gfp_mask);
35269eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
35279eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3528c84db23cSChristoph Lameter 
352990afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
3530a92f7126SChristoph Lameter 		/*
35310ff38490SChristoph Lameter 		 * Free memory by calling shrink zone with increasing
35320ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3533a92f7126SChristoph Lameter 		 */
3534a92f7126SChristoph Lameter 		do {
35359e3b2f8cSKonstantin Khlebnikov 			shrink_zone(zone, &sc);
35369e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
35370ff38490SChristoph Lameter 	}
3538a92f7126SChristoph Lameter 
353915748048SKOSAKI Motohiro 	nr_slab_pages0 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
354015748048SKOSAKI Motohiro 	if (nr_slab_pages0 > zone->min_slab_pages) {
35412a16e3f4SChristoph Lameter 		/*
35427fb2d46dSChristoph Lameter 		 * shrink_slab() does not currently allow us to determine how
35430ff38490SChristoph Lameter 		 * many pages were freed in this zone. So we take the current
35440ff38490SChristoph Lameter 		 * number of slab pages and shake the slab until it is reduced
35450ff38490SChristoph Lameter 		 * by the same nr_pages that we used for reclaiming unmapped
35460ff38490SChristoph Lameter 		 * pages.
35472a16e3f4SChristoph Lameter 		 *
35480ff38490SChristoph Lameter 		 * Note that shrink_slab will free memory on all zones and may
35490ff38490SChristoph Lameter 		 * take a long time.
35502a16e3f4SChristoph Lameter 		 */
35514dc4b3d9SKOSAKI Motohiro 		for (;;) {
35524dc4b3d9SKOSAKI Motohiro 			unsigned long lru_pages = zone_reclaimable_pages(zone);
35534dc4b3d9SKOSAKI Motohiro 
35544dc4b3d9SKOSAKI Motohiro 			/* No reclaimable slab or very low memory pressure */
35551495f230SYing Han 			if (!shrink_slab(&shrink, sc.nr_scanned, lru_pages))
35564dc4b3d9SKOSAKI Motohiro 				break;
35574dc4b3d9SKOSAKI Motohiro 
35584dc4b3d9SKOSAKI Motohiro 			/* Freed enough memory */
35594dc4b3d9SKOSAKI Motohiro 			nr_slab_pages1 = zone_page_state(zone,
35604dc4b3d9SKOSAKI Motohiro 							NR_SLAB_RECLAIMABLE);
35614dc4b3d9SKOSAKI Motohiro 			if (nr_slab_pages1 + nr_pages <= nr_slab_pages0)
35624dc4b3d9SKOSAKI Motohiro 				break;
35634dc4b3d9SKOSAKI Motohiro 		}
356483e33a47SChristoph Lameter 
356583e33a47SChristoph Lameter 		/*
356683e33a47SChristoph Lameter 		 * Update nr_reclaimed by the number of slab pages we
356783e33a47SChristoph Lameter 		 * reclaimed from this zone.
356883e33a47SChristoph Lameter 		 */
356915748048SKOSAKI Motohiro 		nr_slab_pages1 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
357015748048SKOSAKI Motohiro 		if (nr_slab_pages1 < nr_slab_pages0)
357115748048SKOSAKI Motohiro 			sc.nr_reclaimed += nr_slab_pages0 - nr_slab_pages1;
35722a16e3f4SChristoph Lameter 	}
35732a16e3f4SChristoph Lameter 
35749eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3575d4f7796eSChristoph Lameter 	current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
357676ca542dSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
3577a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
35789eeff239SChristoph Lameter }
3579179e9639SAndrew Morton 
3580179e9639SAndrew Morton int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
3581179e9639SAndrew Morton {
3582179e9639SAndrew Morton 	int node_id;
3583d773ed6bSDavid Rientjes 	int ret;
3584179e9639SAndrew Morton 
3585179e9639SAndrew Morton 	/*
35860ff38490SChristoph Lameter 	 * Zone reclaim reclaims unmapped file backed pages and
35870ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
358834aa1330SChristoph Lameter 	 *
35899614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
35909614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
35919614634fSChristoph Lameter 	 * thrown out if the zone is overallocated. So we do not reclaim
35929614634fSChristoph Lameter 	 * if less than a specified percentage of the zone is used by
35939614634fSChristoph Lameter 	 * unmapped file backed pages.
3594179e9639SAndrew Morton 	 */
359590afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
359690afa5deSMel Gorman 	    zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
3597fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3598179e9639SAndrew Morton 
359993e4a89aSKOSAKI Motohiro 	if (zone->all_unreclaimable)
3600fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3601d773ed6bSDavid Rientjes 
3602179e9639SAndrew Morton 	/*
3603d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3604179e9639SAndrew Morton 	 */
3605d773ed6bSDavid Rientjes 	if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
3606fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3607179e9639SAndrew Morton 
3608179e9639SAndrew Morton 	/*
3609179e9639SAndrew Morton 	 * Only run zone reclaim on the local zone or on zones that do not
3610179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3611179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3612179e9639SAndrew Morton 	 * as wide as possible.
3613179e9639SAndrew Morton 	 */
361489fa3024SChristoph Lameter 	node_id = zone_to_nid(zone);
361537c0708dSChristoph Lameter 	if (node_state(node_id, N_CPU) && node_id != numa_node_id())
3616fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3617d773ed6bSDavid Rientjes 
3618d773ed6bSDavid Rientjes 	if (zone_test_and_set_flag(zone, ZONE_RECLAIM_LOCKED))
3619fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3620fa5e084eSMel Gorman 
3621d773ed6bSDavid Rientjes 	ret = __zone_reclaim(zone, gfp_mask, order);
3622d773ed6bSDavid Rientjes 	zone_clear_flag(zone, ZONE_RECLAIM_LOCKED);
3623d773ed6bSDavid Rientjes 
362424cf7251SMel Gorman 	if (!ret)
362524cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
362624cf7251SMel Gorman 
3627d773ed6bSDavid Rientjes 	return ret;
3628179e9639SAndrew Morton }
36299eeff239SChristoph Lameter #endif
3630894bc310SLee Schermerhorn 
3631894bc310SLee Schermerhorn /*
3632894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3633894bc310SLee Schermerhorn  * @page: the page to test
3634894bc310SLee Schermerhorn  *
3635894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
363639b5f29aSHugh Dickins  * lists vs unevictable list.
3637894bc310SLee Schermerhorn  *
3638894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3639ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3640b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3641ba9ddf49SLee Schermerhorn  *
3642894bc310SLee Schermerhorn  */
364339b5f29aSHugh Dickins int page_evictable(struct page *page)
3644894bc310SLee Schermerhorn {
364539b5f29aSHugh Dickins 	return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3646894bc310SLee Schermerhorn }
364789e004eaSLee Schermerhorn 
364885046579SHugh Dickins #ifdef CONFIG_SHMEM
364989e004eaSLee Schermerhorn /**
365024513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
365124513264SHugh Dickins  * @pages:	array of pages to check
365224513264SHugh Dickins  * @nr_pages:	number of pages to check
365389e004eaSLee Schermerhorn  *
365424513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
365585046579SHugh Dickins  *
365685046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
365789e004eaSLee Schermerhorn  */
365824513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
365989e004eaSLee Schermerhorn {
3660925b7673SJohannes Weiner 	struct lruvec *lruvec;
366124513264SHugh Dickins 	struct zone *zone = NULL;
366224513264SHugh Dickins 	int pgscanned = 0;
366324513264SHugh Dickins 	int pgrescued = 0;
366489e004eaSLee Schermerhorn 	int i;
366589e004eaSLee Schermerhorn 
366624513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
366724513264SHugh Dickins 		struct page *page = pages[i];
366824513264SHugh Dickins 		struct zone *pagezone;
366989e004eaSLee Schermerhorn 
367024513264SHugh Dickins 		pgscanned++;
367124513264SHugh Dickins 		pagezone = page_zone(page);
367289e004eaSLee Schermerhorn 		if (pagezone != zone) {
367389e004eaSLee Schermerhorn 			if (zone)
367489e004eaSLee Schermerhorn 				spin_unlock_irq(&zone->lru_lock);
367589e004eaSLee Schermerhorn 			zone = pagezone;
367689e004eaSLee Schermerhorn 			spin_lock_irq(&zone->lru_lock);
367789e004eaSLee Schermerhorn 		}
3678fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
367989e004eaSLee Schermerhorn 
368024513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
368124513264SHugh Dickins 			continue;
368289e004eaSLee Schermerhorn 
368339b5f29aSHugh Dickins 		if (page_evictable(page)) {
368424513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
368524513264SHugh Dickins 
368624513264SHugh Dickins 			VM_BUG_ON(PageActive(page));
368724513264SHugh Dickins 			ClearPageUnevictable(page);
3688fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3689fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
369024513264SHugh Dickins 			pgrescued++;
369189e004eaSLee Schermerhorn 		}
369289e004eaSLee Schermerhorn 	}
369324513264SHugh Dickins 
369424513264SHugh Dickins 	if (zone) {
369524513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
369624513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
369724513264SHugh Dickins 		spin_unlock_irq(&zone->lru_lock);
369824513264SHugh Dickins 	}
369985046579SHugh Dickins }
370085046579SHugh Dickins #endif /* CONFIG_SHMEM */
3701af936a16SLee Schermerhorn 
3702264e56d8SJohannes Weiner static void warn_scan_unevictable_pages(void)
3703af936a16SLee Schermerhorn {
3704264e56d8SJohannes Weiner 	printk_once(KERN_WARNING
370525bd91bdSKOSAKI Motohiro 		    "%s: The scan_unevictable_pages sysctl/node-interface has been "
3706264e56d8SJohannes Weiner 		    "disabled for lack of a legitimate use case.  If you have "
370725bd91bdSKOSAKI Motohiro 		    "one, please send an email to linux-mm@kvack.org.\n",
370825bd91bdSKOSAKI Motohiro 		    current->comm);
3709af936a16SLee Schermerhorn }
3710af936a16SLee Schermerhorn 
3711af936a16SLee Schermerhorn /*
3712af936a16SLee Schermerhorn  * scan_unevictable_pages [vm] sysctl handler.  On demand re-scan of
3713af936a16SLee Schermerhorn  * all nodes' unevictable lists for evictable pages
3714af936a16SLee Schermerhorn  */
3715af936a16SLee Schermerhorn unsigned long scan_unevictable_pages;
3716af936a16SLee Schermerhorn 
3717af936a16SLee Schermerhorn int scan_unevictable_handler(struct ctl_table *table, int write,
37188d65af78SAlexey Dobriyan 			   void __user *buffer,
3719af936a16SLee Schermerhorn 			   size_t *length, loff_t *ppos)
3720af936a16SLee Schermerhorn {
3721264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
37228d65af78SAlexey Dobriyan 	proc_doulongvec_minmax(table, write, buffer, length, ppos);
3723af936a16SLee Schermerhorn 	scan_unevictable_pages = 0;
3724af936a16SLee Schermerhorn 	return 0;
3725af936a16SLee Schermerhorn }
3726af936a16SLee Schermerhorn 
3727e4455abbSThadeu Lima de Souza Cascardo #ifdef CONFIG_NUMA
3728af936a16SLee Schermerhorn /*
3729af936a16SLee Schermerhorn  * per node 'scan_unevictable_pages' attribute.  On demand re-scan of
3730af936a16SLee Schermerhorn  * a specified node's per zone unevictable lists for evictable pages.
3731af936a16SLee Schermerhorn  */
3732af936a16SLee Schermerhorn 
373310fbcf4cSKay Sievers static ssize_t read_scan_unevictable_node(struct device *dev,
373410fbcf4cSKay Sievers 					  struct device_attribute *attr,
3735af936a16SLee Schermerhorn 					  char *buf)
3736af936a16SLee Schermerhorn {
3737264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
3738af936a16SLee Schermerhorn 	return sprintf(buf, "0\n");	/* always zero; should fit... */
3739af936a16SLee Schermerhorn }
3740af936a16SLee Schermerhorn 
374110fbcf4cSKay Sievers static ssize_t write_scan_unevictable_node(struct device *dev,
374210fbcf4cSKay Sievers 					   struct device_attribute *attr,
3743af936a16SLee Schermerhorn 					const char *buf, size_t count)
3744af936a16SLee Schermerhorn {
3745264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
3746af936a16SLee Schermerhorn 	return 1;
3747af936a16SLee Schermerhorn }
3748af936a16SLee Schermerhorn 
3749af936a16SLee Schermerhorn 
375010fbcf4cSKay Sievers static DEVICE_ATTR(scan_unevictable_pages, S_IRUGO | S_IWUSR,
3751af936a16SLee Schermerhorn 			read_scan_unevictable_node,
3752af936a16SLee Schermerhorn 			write_scan_unevictable_node);
3753af936a16SLee Schermerhorn 
3754af936a16SLee Schermerhorn int scan_unevictable_register_node(struct node *node)
3755af936a16SLee Schermerhorn {
375610fbcf4cSKay Sievers 	return device_create_file(&node->dev, &dev_attr_scan_unevictable_pages);
3757af936a16SLee Schermerhorn }
3758af936a16SLee Schermerhorn 
3759af936a16SLee Schermerhorn void scan_unevictable_unregister_node(struct node *node)
3760af936a16SLee Schermerhorn {
376110fbcf4cSKay Sievers 	device_remove_file(&node->dev, &dev_attr_scan_unevictable_pages);
3762af936a16SLee Schermerhorn }
3763e4455abbSThadeu Lima de Souza Cascardo #endif
3764