xref: /openbmc/linux/mm/vmscan.c (revision 283aba9f9e0e4882bf09bd37a2983379a6fae805)
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  */
208a09ed5e0SYing Han unsigned long shrink_slab(struct shrink_control *shrink,
2091495f230SYing Han 			  unsigned long nr_pages_scanned,
21069e05944SAndrew Morton 			  unsigned long lru_pages)
2111da177e4SLinus Torvalds {
2121da177e4SLinus Torvalds 	struct shrinker *shrinker;
21369e05944SAndrew Morton 	unsigned long ret = 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)) {
219f06590bdSMinchan Kim 		/* Assume we'll be able to shrink next time */
220f06590bdSMinchan Kim 		ret = 1;
221f06590bdSMinchan Kim 		goto out;
222f06590bdSMinchan Kim 	}
2231da177e4SLinus Torvalds 
2241da177e4SLinus Torvalds 	list_for_each_entry(shrinker, &shrinker_list, list) {
2251da177e4SLinus Torvalds 		unsigned long long delta;
226635697c6SKonstantin Khlebnikov 		long total_scan;
227635697c6SKonstantin Khlebnikov 		long max_pass;
22809576073SDave Chinner 		int shrink_ret = 0;
229acf92b48SDave Chinner 		long nr;
230acf92b48SDave Chinner 		long new_nr;
231e9299f50SDave Chinner 		long batch_size = shrinker->batch ? shrinker->batch
232e9299f50SDave Chinner 						  : SHRINK_BATCH;
2331da177e4SLinus Torvalds 
234635697c6SKonstantin Khlebnikov 		max_pass = do_shrinker_shrink(shrinker, shrink, 0);
235635697c6SKonstantin Khlebnikov 		if (max_pass <= 0)
236635697c6SKonstantin Khlebnikov 			continue;
237635697c6SKonstantin Khlebnikov 
238acf92b48SDave Chinner 		/*
239acf92b48SDave Chinner 		 * copy the current shrinker scan count into a local variable
240acf92b48SDave Chinner 		 * and zero it so that other concurrent shrinker invocations
241acf92b48SDave Chinner 		 * don't also do this scanning work.
242acf92b48SDave Chinner 		 */
24383aeeadaSKonstantin Khlebnikov 		nr = atomic_long_xchg(&shrinker->nr_in_batch, 0);
244acf92b48SDave Chinner 
245acf92b48SDave Chinner 		total_scan = nr;
2461495f230SYing Han 		delta = (4 * nr_pages_scanned) / shrinker->seeks;
247ea164d73SAndrea Arcangeli 		delta *= max_pass;
2481da177e4SLinus Torvalds 		do_div(delta, lru_pages + 1);
249acf92b48SDave Chinner 		total_scan += delta;
250acf92b48SDave Chinner 		if (total_scan < 0) {
25188c3bd70SDavid Rientjes 			printk(KERN_ERR "shrink_slab: %pF negative objects to "
25288c3bd70SDavid Rientjes 			       "delete nr=%ld\n",
253acf92b48SDave Chinner 			       shrinker->shrink, total_scan);
254acf92b48SDave Chinner 			total_scan = max_pass;
255ea164d73SAndrea Arcangeli 		}
256ea164d73SAndrea Arcangeli 
257ea164d73SAndrea Arcangeli 		/*
2583567b59aSDave Chinner 		 * We need to avoid excessive windup on filesystem shrinkers
2593567b59aSDave Chinner 		 * due to large numbers of GFP_NOFS allocations causing the
2603567b59aSDave Chinner 		 * shrinkers to return -1 all the time. This results in a large
2613567b59aSDave Chinner 		 * nr being built up so when a shrink that can do some work
2623567b59aSDave Chinner 		 * comes along it empties the entire cache due to nr >>>
2633567b59aSDave Chinner 		 * max_pass.  This is bad for sustaining a working set in
2643567b59aSDave Chinner 		 * memory.
2653567b59aSDave Chinner 		 *
2663567b59aSDave Chinner 		 * Hence only allow the shrinker to scan the entire cache when
2673567b59aSDave Chinner 		 * a large delta change is calculated directly.
2683567b59aSDave Chinner 		 */
2693567b59aSDave Chinner 		if (delta < max_pass / 4)
2703567b59aSDave Chinner 			total_scan = min(total_scan, max_pass / 2);
2713567b59aSDave Chinner 
2723567b59aSDave Chinner 		/*
273ea164d73SAndrea Arcangeli 		 * Avoid risking looping forever due to too large nr value:
274ea164d73SAndrea Arcangeli 		 * never try to free more than twice the estimate number of
275ea164d73SAndrea Arcangeli 		 * freeable entries.
276ea164d73SAndrea Arcangeli 		 */
277acf92b48SDave Chinner 		if (total_scan > max_pass * 2)
278acf92b48SDave Chinner 			total_scan = max_pass * 2;
2791da177e4SLinus Torvalds 
280acf92b48SDave Chinner 		trace_mm_shrink_slab_start(shrinker, shrink, nr,
28109576073SDave Chinner 					nr_pages_scanned, lru_pages,
28209576073SDave Chinner 					max_pass, delta, total_scan);
28309576073SDave Chinner 
284e9299f50SDave Chinner 		while (total_scan >= batch_size) {
285b15e0905Sakpm@osdl.org 			int nr_before;
2861da177e4SLinus Torvalds 
2871495f230SYing Han 			nr_before = do_shrinker_shrink(shrinker, shrink, 0);
2881495f230SYing Han 			shrink_ret = do_shrinker_shrink(shrinker, shrink,
289e9299f50SDave Chinner 							batch_size);
2901da177e4SLinus Torvalds 			if (shrink_ret == -1)
2911da177e4SLinus Torvalds 				break;
292b15e0905Sakpm@osdl.org 			if (shrink_ret < nr_before)
293b15e0905Sakpm@osdl.org 				ret += nr_before - shrink_ret;
294e9299f50SDave Chinner 			count_vm_events(SLABS_SCANNED, batch_size);
295e9299f50SDave Chinner 			total_scan -= batch_size;
2961da177e4SLinus Torvalds 
2971da177e4SLinus Torvalds 			cond_resched();
2981da177e4SLinus Torvalds 		}
2991da177e4SLinus Torvalds 
300acf92b48SDave Chinner 		/*
301acf92b48SDave Chinner 		 * move the unused scan count back into the shrinker in a
302acf92b48SDave Chinner 		 * manner that handles concurrent updates. If we exhausted the
303acf92b48SDave Chinner 		 * scan, there is no need to do an update.
304acf92b48SDave Chinner 		 */
30583aeeadaSKonstantin Khlebnikov 		if (total_scan > 0)
30683aeeadaSKonstantin Khlebnikov 			new_nr = atomic_long_add_return(total_scan,
30783aeeadaSKonstantin Khlebnikov 					&shrinker->nr_in_batch);
30883aeeadaSKonstantin Khlebnikov 		else
30983aeeadaSKonstantin Khlebnikov 			new_nr = atomic_long_read(&shrinker->nr_in_batch);
310acf92b48SDave Chinner 
311acf92b48SDave Chinner 		trace_mm_shrink_slab_end(shrinker, shrink_ret, nr, new_nr);
3121da177e4SLinus Torvalds 	}
3131da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
314f06590bdSMinchan Kim out:
315f06590bdSMinchan Kim 	cond_resched();
316b15e0905Sakpm@osdl.org 	return ret;
3171da177e4SLinus Torvalds }
3181da177e4SLinus Torvalds 
3191da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
3201da177e4SLinus Torvalds {
321ceddc3a5SJohannes Weiner 	/*
322ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
323ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
324ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
325ceddc3a5SJohannes Weiner 	 */
326edcf4748SJohannes Weiner 	return page_count(page) - page_has_private(page) == 2;
3271da177e4SLinus Torvalds }
3281da177e4SLinus Torvalds 
3297d3579e8SKOSAKI Motohiro static int may_write_to_queue(struct backing_dev_info *bdi,
3307d3579e8SKOSAKI Motohiro 			      struct scan_control *sc)
3311da177e4SLinus Torvalds {
332930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
3331da177e4SLinus Torvalds 		return 1;
3341da177e4SLinus Torvalds 	if (!bdi_write_congested(bdi))
3351da177e4SLinus Torvalds 		return 1;
3361da177e4SLinus Torvalds 	if (bdi == current->backing_dev_info)
3371da177e4SLinus Torvalds 		return 1;
3381da177e4SLinus Torvalds 	return 0;
3391da177e4SLinus Torvalds }
3401da177e4SLinus Torvalds 
3411da177e4SLinus Torvalds /*
3421da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
3431da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
3441da177e4SLinus Torvalds  * fsync(), msync() or close().
3451da177e4SLinus Torvalds  *
3461da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
3471da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
3481da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
3491da177e4SLinus Torvalds  *
3501da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
3511da177e4SLinus Torvalds  * __GFP_FS.
3521da177e4SLinus Torvalds  */
3531da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
3541da177e4SLinus Torvalds 				struct page *page, int error)
3551da177e4SLinus Torvalds {
3567eaceaccSJens Axboe 	lock_page(page);
3573e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
3583e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
3591da177e4SLinus Torvalds 	unlock_page(page);
3601da177e4SLinus Torvalds }
3611da177e4SLinus Torvalds 
36204e62a29SChristoph Lameter /* possible outcome of pageout() */
36304e62a29SChristoph Lameter typedef enum {
36404e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
36504e62a29SChristoph Lameter 	PAGE_KEEP,
36604e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
36704e62a29SChristoph Lameter 	PAGE_ACTIVATE,
36804e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
36904e62a29SChristoph Lameter 	PAGE_SUCCESS,
37004e62a29SChristoph Lameter 	/* page is clean and locked */
37104e62a29SChristoph Lameter 	PAGE_CLEAN,
37204e62a29SChristoph Lameter } pageout_t;
37304e62a29SChristoph Lameter 
3741da177e4SLinus Torvalds /*
3751742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
3761742f19fSAndrew Morton  * Calls ->writepage().
3771da177e4SLinus Torvalds  */
378c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
3797d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
3801da177e4SLinus Torvalds {
3811da177e4SLinus Torvalds 	/*
3821da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
3831da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
3841da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
3851da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
3861da177e4SLinus Torvalds 	 * PagePrivate for that.
3871da177e4SLinus Torvalds 	 *
3886aceb53bSVincent Li 	 * If this process is currently in __generic_file_aio_write() against
3891da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
3901da177e4SLinus Torvalds 	 * will block.
3911da177e4SLinus Torvalds 	 *
3921da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
3931da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
3941da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
3951da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
3961da177e4SLinus Torvalds 	 */
3971da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
3981da177e4SLinus Torvalds 		return PAGE_KEEP;
3991da177e4SLinus Torvalds 	if (!mapping) {
4001da177e4SLinus Torvalds 		/*
4011da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
4021da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
4031da177e4SLinus Torvalds 		 */
404266cf658SDavid Howells 		if (page_has_private(page)) {
4051da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
4061da177e4SLinus Torvalds 				ClearPageDirty(page);
407d40cee24SHarvey Harrison 				printk("%s: orphaned page\n", __func__);
4081da177e4SLinus Torvalds 				return PAGE_CLEAN;
4091da177e4SLinus Torvalds 			}
4101da177e4SLinus Torvalds 		}
4111da177e4SLinus Torvalds 		return PAGE_KEEP;
4121da177e4SLinus Torvalds 	}
4131da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
4141da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
4150e093d99SMel Gorman 	if (!may_write_to_queue(mapping->backing_dev_info, sc))
4161da177e4SLinus Torvalds 		return PAGE_KEEP;
4171da177e4SLinus Torvalds 
4181da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
4191da177e4SLinus Torvalds 		int res;
4201da177e4SLinus Torvalds 		struct writeback_control wbc = {
4211da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
4221da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
423111ebb6eSOGAWA Hirofumi 			.range_start = 0,
424111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
4251da177e4SLinus Torvalds 			.for_reclaim = 1,
4261da177e4SLinus Torvalds 		};
4271da177e4SLinus Torvalds 
4281da177e4SLinus Torvalds 		SetPageReclaim(page);
4291da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
4301da177e4SLinus Torvalds 		if (res < 0)
4311da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
432994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
4331da177e4SLinus Torvalds 			ClearPageReclaim(page);
4341da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
4351da177e4SLinus Torvalds 		}
436c661b078SAndy Whitcroft 
4371da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
4381da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
4391da177e4SLinus Torvalds 			ClearPageReclaim(page);
4401da177e4SLinus Torvalds 		}
44123b9da55SMel Gorman 		trace_mm_vmscan_writepage(page, trace_reclaim_flags(page));
442e129b5c2SAndrew Morton 		inc_zone_page_state(page, NR_VMSCAN_WRITE);
4431da177e4SLinus Torvalds 		return PAGE_SUCCESS;
4441da177e4SLinus Torvalds 	}
4451da177e4SLinus Torvalds 
4461da177e4SLinus Torvalds 	return PAGE_CLEAN;
4471da177e4SLinus Torvalds }
4481da177e4SLinus Torvalds 
449a649fd92SAndrew Morton /*
450e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
451e286781dSNick Piggin  * gets returned with a refcount of 0.
452a649fd92SAndrew Morton  */
453e286781dSNick Piggin static int __remove_mapping(struct address_space *mapping, struct page *page)
45449d2e9ccSChristoph Lameter {
45528e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
45628e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
45749d2e9ccSChristoph Lameter 
45819fd6231SNick Piggin 	spin_lock_irq(&mapping->tree_lock);
45949d2e9ccSChristoph Lameter 	/*
4600fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
4610fd0e6b0SNick Piggin 	 *
4620fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
4630fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
4640fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
4650fd0e6b0SNick Piggin 	 * here, then the following race may occur:
4660fd0e6b0SNick Piggin 	 *
4670fd0e6b0SNick Piggin 	 * get_user_pages(&page);
4680fd0e6b0SNick Piggin 	 * [user mapping goes away]
4690fd0e6b0SNick Piggin 	 * write_to(page);
4700fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
4710fd0e6b0SNick Piggin 	 * SetPageDirty(page);
4720fd0e6b0SNick Piggin 	 * put_page(page);
4730fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
4740fd0e6b0SNick Piggin 	 *
4750fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
4760fd0e6b0SNick Piggin 	 *
4770fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
4780fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
4790fd0e6b0SNick Piggin 	 * load is not satisfied before that of page->_count.
4800fd0e6b0SNick Piggin 	 *
4810fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
4820fd0e6b0SNick Piggin 	 * and thus under tree_lock, then this ordering is not required.
48349d2e9ccSChristoph Lameter 	 */
484e286781dSNick Piggin 	if (!page_freeze_refs(page, 2))
48549d2e9ccSChristoph Lameter 		goto cannot_free;
486e286781dSNick Piggin 	/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
487e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
488e286781dSNick Piggin 		page_unfreeze_refs(page, 2);
48949d2e9ccSChristoph Lameter 		goto cannot_free;
490e286781dSNick Piggin 	}
49149d2e9ccSChristoph Lameter 
49249d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
49349d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
49449d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
49519fd6231SNick Piggin 		spin_unlock_irq(&mapping->tree_lock);
496cb4b86baSKAMEZAWA Hiroyuki 		swapcache_free(swap, page);
497e286781dSNick Piggin 	} else {
4986072d13cSLinus Torvalds 		void (*freepage)(struct page *);
4996072d13cSLinus Torvalds 
5006072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
5016072d13cSLinus Torvalds 
502e64a782fSMinchan Kim 		__delete_from_page_cache(page);
50319fd6231SNick Piggin 		spin_unlock_irq(&mapping->tree_lock);
504e767e056SDaisuke Nishimura 		mem_cgroup_uncharge_cache_page(page);
5056072d13cSLinus Torvalds 
5066072d13cSLinus Torvalds 		if (freepage != NULL)
5076072d13cSLinus Torvalds 			freepage(page);
508e286781dSNick Piggin 	}
509e286781dSNick Piggin 
51049d2e9ccSChristoph Lameter 	return 1;
51149d2e9ccSChristoph Lameter 
51249d2e9ccSChristoph Lameter cannot_free:
51319fd6231SNick Piggin 	spin_unlock_irq(&mapping->tree_lock);
51449d2e9ccSChristoph Lameter 	return 0;
51549d2e9ccSChristoph Lameter }
51649d2e9ccSChristoph Lameter 
5171da177e4SLinus Torvalds /*
518e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
519e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
520e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
521e286781dSNick Piggin  * this page.
522e286781dSNick Piggin  */
523e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
524e286781dSNick Piggin {
525e286781dSNick Piggin 	if (__remove_mapping(mapping, page)) {
526e286781dSNick Piggin 		/*
527e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
528e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
529e286781dSNick Piggin 		 * atomic operation.
530e286781dSNick Piggin 		 */
531e286781dSNick Piggin 		page_unfreeze_refs(page, 1);
532e286781dSNick Piggin 		return 1;
533e286781dSNick Piggin 	}
534e286781dSNick Piggin 	return 0;
535e286781dSNick Piggin }
536e286781dSNick Piggin 
537894bc310SLee Schermerhorn /**
538894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
539894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
540894bc310SLee Schermerhorn  *
541894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
542894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
543894bc310SLee Schermerhorn  *
544894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
545894bc310SLee Schermerhorn  */
546894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
547894bc310SLee Schermerhorn {
548894bc310SLee Schermerhorn 	int lru;
549894bc310SLee Schermerhorn 	int active = !!TestClearPageActive(page);
550bbfd28eeSLee Schermerhorn 	int was_unevictable = PageUnevictable(page);
551894bc310SLee Schermerhorn 
552894bc310SLee Schermerhorn 	VM_BUG_ON(PageLRU(page));
553894bc310SLee Schermerhorn 
554894bc310SLee Schermerhorn redo:
555894bc310SLee Schermerhorn 	ClearPageUnevictable(page);
556894bc310SLee Schermerhorn 
55739b5f29aSHugh Dickins 	if (page_evictable(page)) {
558894bc310SLee Schermerhorn 		/*
559894bc310SLee Schermerhorn 		 * For evictable pages, we can use the cache.
560894bc310SLee Schermerhorn 		 * In event of a race, worst case is we end up with an
561894bc310SLee Schermerhorn 		 * unevictable page on [in]active list.
562894bc310SLee Schermerhorn 		 * We know how to handle that.
563894bc310SLee Schermerhorn 		 */
564401a8e1cSJohannes Weiner 		lru = active + page_lru_base_type(page);
565894bc310SLee Schermerhorn 		lru_cache_add_lru(page, lru);
566894bc310SLee Schermerhorn 	} else {
567894bc310SLee Schermerhorn 		/*
568894bc310SLee Schermerhorn 		 * Put unevictable pages directly on zone's unevictable
569894bc310SLee Schermerhorn 		 * list.
570894bc310SLee Schermerhorn 		 */
571894bc310SLee Schermerhorn 		lru = LRU_UNEVICTABLE;
572894bc310SLee Schermerhorn 		add_page_to_unevictable_list(page);
5736a7b9548SJohannes Weiner 		/*
57421ee9f39SMinchan Kim 		 * When racing with an mlock or AS_UNEVICTABLE clearing
57521ee9f39SMinchan Kim 		 * (page is unlocked) make sure that if the other thread
57621ee9f39SMinchan Kim 		 * does not observe our setting of PG_lru and fails
57724513264SHugh Dickins 		 * isolation/check_move_unevictable_pages,
57821ee9f39SMinchan Kim 		 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
5796a7b9548SJohannes Weiner 		 * the page back to the evictable list.
5806a7b9548SJohannes Weiner 		 *
58121ee9f39SMinchan Kim 		 * The other side is TestClearPageMlocked() or shmem_lock().
5826a7b9548SJohannes Weiner 		 */
5836a7b9548SJohannes Weiner 		smp_mb();
584894bc310SLee Schermerhorn 	}
585894bc310SLee Schermerhorn 
586894bc310SLee Schermerhorn 	/*
587894bc310SLee Schermerhorn 	 * page's status can change while we move it among lru. If an evictable
588894bc310SLee Schermerhorn 	 * page is on unevictable list, it never be freed. To avoid that,
589894bc310SLee Schermerhorn 	 * check after we added it to the list, again.
590894bc310SLee Schermerhorn 	 */
59139b5f29aSHugh Dickins 	if (lru == LRU_UNEVICTABLE && page_evictable(page)) {
592894bc310SLee Schermerhorn 		if (!isolate_lru_page(page)) {
593894bc310SLee Schermerhorn 			put_page(page);
594894bc310SLee Schermerhorn 			goto redo;
595894bc310SLee Schermerhorn 		}
596894bc310SLee Schermerhorn 		/* This means someone else dropped this page from LRU
597894bc310SLee Schermerhorn 		 * So, it will be freed or putback to LRU again. There is
598894bc310SLee Schermerhorn 		 * nothing to do here.
599894bc310SLee Schermerhorn 		 */
600894bc310SLee Schermerhorn 	}
601894bc310SLee Schermerhorn 
602bbfd28eeSLee Schermerhorn 	if (was_unevictable && lru != LRU_UNEVICTABLE)
603bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGRESCUED);
604bbfd28eeSLee Schermerhorn 	else if (!was_unevictable && lru == LRU_UNEVICTABLE)
605bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGCULLED);
606bbfd28eeSLee Schermerhorn 
607894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
608894bc310SLee Schermerhorn }
609894bc310SLee Schermerhorn 
610dfc8d636SJohannes Weiner enum page_references {
611dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
612dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
61364574746SJohannes Weiner 	PAGEREF_KEEP,
614dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
615dfc8d636SJohannes Weiner };
616dfc8d636SJohannes Weiner 
617dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
618dfc8d636SJohannes Weiner 						  struct scan_control *sc)
619dfc8d636SJohannes Weiner {
62064574746SJohannes Weiner 	int referenced_ptes, referenced_page;
621dfc8d636SJohannes Weiner 	unsigned long vm_flags;
622dfc8d636SJohannes Weiner 
623c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
624c3ac9a8aSJohannes Weiner 					  &vm_flags);
62564574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
626dfc8d636SJohannes Weiner 
627dfc8d636SJohannes Weiner 	/*
628dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
629dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
630dfc8d636SJohannes Weiner 	 */
631dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
632dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
633dfc8d636SJohannes Weiner 
63464574746SJohannes Weiner 	if (referenced_ptes) {
635e4898273SMichal Hocko 		if (PageSwapBacked(page))
63664574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
63764574746SJohannes Weiner 		/*
63864574746SJohannes Weiner 		 * All mapped pages start out with page table
63964574746SJohannes Weiner 		 * references from the instantiating fault, so we need
64064574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
64164574746SJohannes Weiner 		 * than once.
64264574746SJohannes Weiner 		 *
64364574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
64464574746SJohannes Weiner 		 * inactive list.  Another page table reference will
64564574746SJohannes Weiner 		 * lead to its activation.
64664574746SJohannes Weiner 		 *
64764574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
64864574746SJohannes Weiner 		 * so that recently deactivated but used pages are
64964574746SJohannes Weiner 		 * quickly recovered.
65064574746SJohannes Weiner 		 */
65164574746SJohannes Weiner 		SetPageReferenced(page);
65264574746SJohannes Weiner 
65334dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
654dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
655dfc8d636SJohannes Weiner 
656c909e993SKonstantin Khlebnikov 		/*
657c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
658c909e993SKonstantin Khlebnikov 		 */
659c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
660c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
661c909e993SKonstantin Khlebnikov 
66264574746SJohannes Weiner 		return PAGEREF_KEEP;
66364574746SJohannes Weiner 	}
66464574746SJohannes Weiner 
665dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
6662e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
667dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
66864574746SJohannes Weiner 
66964574746SJohannes Weiner 	return PAGEREF_RECLAIM;
670dfc8d636SJohannes Weiner }
671dfc8d636SJohannes Weiner 
672e286781dSNick Piggin /*
6731742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
6741da177e4SLinus Torvalds  */
6751742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
6766a18adb3SKonstantin Khlebnikov 				      struct zone *zone,
677f84f6e2bSMel Gorman 				      struct scan_control *sc,
67802c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
679d43006d5SMel Gorman 				      unsigned long *ret_nr_unqueued_dirty,
68002c6de8dSMinchan Kim 				      unsigned long *ret_nr_writeback,
68102c6de8dSMinchan Kim 				      bool force_reclaim)
6821da177e4SLinus Torvalds {
6831da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
684abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
6851da177e4SLinus Torvalds 	int pgactivate = 0;
686d43006d5SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
6870e093d99SMel Gorman 	unsigned long nr_dirty = 0;
6880e093d99SMel Gorman 	unsigned long nr_congested = 0;
68905ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
69092df3a72SMel Gorman 	unsigned long nr_writeback = 0;
6911da177e4SLinus Torvalds 
6921da177e4SLinus Torvalds 	cond_resched();
6931da177e4SLinus Torvalds 
69469980e31STim Chen 	mem_cgroup_uncharge_start();
6951da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
6961da177e4SLinus Torvalds 		struct address_space *mapping;
6971da177e4SLinus Torvalds 		struct page *page;
6981da177e4SLinus Torvalds 		int may_enter_fs;
69902c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
7001da177e4SLinus Torvalds 
7011da177e4SLinus Torvalds 		cond_resched();
7021da177e4SLinus Torvalds 
7031da177e4SLinus Torvalds 		page = lru_to_page(page_list);
7041da177e4SLinus Torvalds 		list_del(&page->lru);
7051da177e4SLinus Torvalds 
706529ae9aaSNick Piggin 		if (!trylock_page(page))
7071da177e4SLinus Torvalds 			goto keep;
7081da177e4SLinus Torvalds 
709725d704eSNick Piggin 		VM_BUG_ON(PageActive(page));
7106a18adb3SKonstantin Khlebnikov 		VM_BUG_ON(page_zone(page) != zone);
7111da177e4SLinus Torvalds 
7121da177e4SLinus Torvalds 		sc->nr_scanned++;
71380e43426SChristoph Lameter 
71439b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
715b291f000SNick Piggin 			goto cull_mlocked;
716894bc310SLee Schermerhorn 
717a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
71880e43426SChristoph Lameter 			goto keep_locked;
71980e43426SChristoph Lameter 
7201da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
7211da177e4SLinus Torvalds 		if (page_mapped(page) || PageSwapCache(page))
7221da177e4SLinus Torvalds 			sc->nr_scanned++;
7231da177e4SLinus Torvalds 
724c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
725c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
726c661b078SAndy Whitcroft 
727e62e384eSMichal Hocko 		/*
728*283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
729*283aba9fSMel Gorman 		 * are three cases to consider.
730e62e384eSMichal Hocko 		 *
731*283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
732*283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
733*283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
734*283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
735*283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
736*283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
737*283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
738*283aba9fSMel Gorman 		 *    block for HZ/10 or until some IO completes then clear the
739*283aba9fSMel Gorman 		 *    ZONE_WRITEBACK flag to recheck if the condition exists.
740c3b94f44SHugh Dickins 		 *
741*283aba9fSMel Gorman 		 * 2) Global reclaim encounters a page, memcg encounters a
742*283aba9fSMel Gorman 		 *    page that is not marked for immediate reclaim or
743*283aba9fSMel Gorman 		 *    the caller does not have __GFP_IO. In this case mark
744*283aba9fSMel Gorman 		 *    the page for immediate reclaim and continue scanning.
745*283aba9fSMel Gorman 		 *
746*283aba9fSMel Gorman 		 *    __GFP_IO is checked  because a loop driver thread might
747*283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
748*283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
749*283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
750*283aba9fSMel Gorman 		 *    would probably show more reasons.
751*283aba9fSMel Gorman 		 *
752*283aba9fSMel Gorman 		 *    Don't require __GFP_FS, since we're not going into the
753*283aba9fSMel Gorman 		 *    FS, just waiting on its writeback completion. Worryingly,
754*283aba9fSMel Gorman 		 *    ext4 gfs2 and xfs allocate pages with
755*283aba9fSMel Gorman 		 *    grab_cache_page_write_begin(,,AOP_FLAG_NOFS), so testing
756*283aba9fSMel Gorman 		 *    may_enter_fs here is liable to OOM on them.
757*283aba9fSMel Gorman 		 *
758*283aba9fSMel Gorman 		 * 3) memcg encounters a page that is not already marked
759*283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
760*283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
761*283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
762*283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
763e62e384eSMichal Hocko 		 */
764*283aba9fSMel Gorman 		if (PageWriteback(page)) {
765*283aba9fSMel Gorman 			/* Case 1 above */
766*283aba9fSMel Gorman 			if (current_is_kswapd() &&
767*283aba9fSMel Gorman 			    PageReclaim(page) &&
768*283aba9fSMel Gorman 			    zone_is_reclaim_writeback(zone)) {
769*283aba9fSMel Gorman 				unlock_page(page);
770*283aba9fSMel Gorman 				congestion_wait(BLK_RW_ASYNC, HZ/10);
771*283aba9fSMel Gorman 				zone_clear_flag(zone, ZONE_WRITEBACK);
772*283aba9fSMel Gorman 				goto keep;
773*283aba9fSMel Gorman 
774*283aba9fSMel Gorman 			/* Case 2 above */
775*283aba9fSMel Gorman 			} else if (global_reclaim(sc) ||
776c3b94f44SHugh Dickins 			    !PageReclaim(page) || !(sc->gfp_mask & __GFP_IO)) {
777c3b94f44SHugh Dickins 				/*
778c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
779c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
780c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
781c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
782c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
783c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
784c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
785c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
786c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
787c3b94f44SHugh Dickins 				 */
788c3b94f44SHugh Dickins 				SetPageReclaim(page);
78992df3a72SMel Gorman 				nr_writeback++;
790*283aba9fSMel Gorman 
791c3b94f44SHugh Dickins 				goto keep_locked;
792*283aba9fSMel Gorman 
793*283aba9fSMel Gorman 			/* Case 3 above */
794*283aba9fSMel Gorman 			} else {
795c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
796e62e384eSMichal Hocko 			}
797*283aba9fSMel Gorman 		}
7981da177e4SLinus Torvalds 
79902c6de8dSMinchan Kim 		if (!force_reclaim)
8006a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
80102c6de8dSMinchan Kim 
802dfc8d636SJohannes Weiner 		switch (references) {
803dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
8041da177e4SLinus Torvalds 			goto activate_locked;
80564574746SJohannes Weiner 		case PAGEREF_KEEP:
80664574746SJohannes Weiner 			goto keep_locked;
807dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
808dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
809dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
810dfc8d636SJohannes Weiner 		}
8111da177e4SLinus Torvalds 
8121da177e4SLinus Torvalds 		/*
8131da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
8141da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
8151da177e4SLinus Torvalds 		 */
816b291f000SNick Piggin 		if (PageAnon(page) && !PageSwapCache(page)) {
81763eb6b93SHugh Dickins 			if (!(sc->gfp_mask & __GFP_IO))
81863eb6b93SHugh Dickins 				goto keep_locked;
8195bc7b8acSShaohua Li 			if (!add_to_swap(page, page_list))
8201da177e4SLinus Torvalds 				goto activate_locked;
82163eb6b93SHugh Dickins 			may_enter_fs = 1;
822b291f000SNick Piggin 		}
8231da177e4SLinus Torvalds 
8241da177e4SLinus Torvalds 		mapping = page_mapping(page);
8251da177e4SLinus Torvalds 
8261da177e4SLinus Torvalds 		/*
8271da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
8281da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
8291da177e4SLinus Torvalds 		 */
8301da177e4SLinus Torvalds 		if (page_mapped(page) && mapping) {
83102c6de8dSMinchan Kim 			switch (try_to_unmap(page, ttu_flags)) {
8321da177e4SLinus Torvalds 			case SWAP_FAIL:
8331da177e4SLinus Torvalds 				goto activate_locked;
8341da177e4SLinus Torvalds 			case SWAP_AGAIN:
8351da177e4SLinus Torvalds 				goto keep_locked;
836b291f000SNick Piggin 			case SWAP_MLOCK:
837b291f000SNick Piggin 				goto cull_mlocked;
8381da177e4SLinus Torvalds 			case SWAP_SUCCESS:
8391da177e4SLinus Torvalds 				; /* try to free the page below */
8401da177e4SLinus Torvalds 			}
8411da177e4SLinus Torvalds 		}
8421da177e4SLinus Torvalds 
8431da177e4SLinus Torvalds 		if (PageDirty(page)) {
8440e093d99SMel Gorman 			nr_dirty++;
8450e093d99SMel Gorman 
846d43006d5SMel Gorman 			if (!PageWriteback(page))
847d43006d5SMel Gorman 				nr_unqueued_dirty++;
848d43006d5SMel Gorman 
849ee72886dSMel Gorman 			/*
850ee72886dSMel Gorman 			 * Only kswapd can writeback filesystem pages to
851d43006d5SMel Gorman 			 * avoid risk of stack overflow but only writeback
852d43006d5SMel Gorman 			 * if many dirty pages have been encountered.
853ee72886dSMel Gorman 			 */
854f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
8559e3b2f8cSKonstantin Khlebnikov 					(!current_is_kswapd() ||
856d43006d5SMel Gorman 					 !zone_is_reclaim_dirty(zone))) {
85749ea7eb6SMel Gorman 				/*
85849ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
85949ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
86049ea7eb6SMel Gorman 				 * except we already have the page isolated
86149ea7eb6SMel Gorman 				 * and know it's dirty
86249ea7eb6SMel Gorman 				 */
86349ea7eb6SMel Gorman 				inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE);
86449ea7eb6SMel Gorman 				SetPageReclaim(page);
86549ea7eb6SMel Gorman 
866ee72886dSMel Gorman 				goto keep_locked;
867ee72886dSMel Gorman 			}
868ee72886dSMel Gorman 
869dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
8701da177e4SLinus Torvalds 				goto keep_locked;
8714dd4b920SAndrew Morton 			if (!may_enter_fs)
8721da177e4SLinus Torvalds 				goto keep_locked;
87352a8363eSChristoph Lameter 			if (!sc->may_writepage)
8741da177e4SLinus Torvalds 				goto keep_locked;
8751da177e4SLinus Torvalds 
8761da177e4SLinus Torvalds 			/* Page is dirty, try to write it out here */
8777d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
8781da177e4SLinus Torvalds 			case PAGE_KEEP:
8790e093d99SMel Gorman 				nr_congested++;
8801da177e4SLinus Torvalds 				goto keep_locked;
8811da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
8821da177e4SLinus Torvalds 				goto activate_locked;
8831da177e4SLinus Torvalds 			case PAGE_SUCCESS:
8847d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
88541ac1999SMel Gorman 					goto keep;
8867d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
8871da177e4SLinus Torvalds 					goto keep;
8887d3579e8SKOSAKI Motohiro 
8891da177e4SLinus Torvalds 				/*
8901da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
8911da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
8921da177e4SLinus Torvalds 				 */
893529ae9aaSNick Piggin 				if (!trylock_page(page))
8941da177e4SLinus Torvalds 					goto keep;
8951da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
8961da177e4SLinus Torvalds 					goto keep_locked;
8971da177e4SLinus Torvalds 				mapping = page_mapping(page);
8981da177e4SLinus Torvalds 			case PAGE_CLEAN:
8991da177e4SLinus Torvalds 				; /* try to free the page below */
9001da177e4SLinus Torvalds 			}
9011da177e4SLinus Torvalds 		}
9021da177e4SLinus Torvalds 
9031da177e4SLinus Torvalds 		/*
9041da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
9051da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
9061da177e4SLinus Torvalds 		 * the page as well.
9071da177e4SLinus Torvalds 		 *
9081da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
9091da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
9101da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
9111da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
9121da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
9131da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
9141da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
9151da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
9161da177e4SLinus Torvalds 		 *
9171da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
9181da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
9191da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
9201da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
9211da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
9221da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
9231da177e4SLinus Torvalds 		 */
924266cf658SDavid Howells 		if (page_has_private(page)) {
9251da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
9261da177e4SLinus Torvalds 				goto activate_locked;
927e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
928e286781dSNick Piggin 				unlock_page(page);
929e286781dSNick Piggin 				if (put_page_testzero(page))
9301da177e4SLinus Torvalds 					goto free_it;
931e286781dSNick Piggin 				else {
932e286781dSNick Piggin 					/*
933e286781dSNick Piggin 					 * rare race with speculative reference.
934e286781dSNick Piggin 					 * the speculative reference will free
935e286781dSNick Piggin 					 * this page shortly, so we may
936e286781dSNick Piggin 					 * increment nr_reclaimed here (and
937e286781dSNick Piggin 					 * leave it off the LRU).
938e286781dSNick Piggin 					 */
939e286781dSNick Piggin 					nr_reclaimed++;
940e286781dSNick Piggin 					continue;
941e286781dSNick Piggin 				}
942e286781dSNick Piggin 			}
9431da177e4SLinus Torvalds 		}
9441da177e4SLinus Torvalds 
945e286781dSNick Piggin 		if (!mapping || !__remove_mapping(mapping, page))
94649d2e9ccSChristoph Lameter 			goto keep_locked;
9471da177e4SLinus Torvalds 
948a978d6f5SNick Piggin 		/*
949a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
950a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
951a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
952a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
953a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
954a978d6f5SNick Piggin 		 */
955a978d6f5SNick Piggin 		__clear_page_locked(page);
956e286781dSNick Piggin free_it:
95705ff5137SAndrew Morton 		nr_reclaimed++;
958abe4c3b5SMel Gorman 
959abe4c3b5SMel Gorman 		/*
960abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
961abe4c3b5SMel Gorman 		 * appear not as the counts should be low
962abe4c3b5SMel Gorman 		 */
963abe4c3b5SMel Gorman 		list_add(&page->lru, &free_pages);
9641da177e4SLinus Torvalds 		continue;
9651da177e4SLinus Torvalds 
966b291f000SNick Piggin cull_mlocked:
96763d6c5adSHugh Dickins 		if (PageSwapCache(page))
96863d6c5adSHugh Dickins 			try_to_free_swap(page);
969b291f000SNick Piggin 		unlock_page(page);
970b291f000SNick Piggin 		putback_lru_page(page);
971b291f000SNick Piggin 		continue;
972b291f000SNick Piggin 
9731da177e4SLinus Torvalds activate_locked:
97468a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
97568a22394SRik van Riel 		if (PageSwapCache(page) && vm_swap_full())
976a2c43eedSHugh Dickins 			try_to_free_swap(page);
977894bc310SLee Schermerhorn 		VM_BUG_ON(PageActive(page));
9781da177e4SLinus Torvalds 		SetPageActive(page);
9791da177e4SLinus Torvalds 		pgactivate++;
9801da177e4SLinus Torvalds keep_locked:
9811da177e4SLinus Torvalds 		unlock_page(page);
9821da177e4SLinus Torvalds keep:
9831da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
984b291f000SNick Piggin 		VM_BUG_ON(PageLRU(page) || PageUnevictable(page));
9851da177e4SLinus Torvalds 	}
986abe4c3b5SMel Gorman 
9870e093d99SMel Gorman 	/*
9880e093d99SMel Gorman 	 * Tag a zone as congested if all the dirty pages encountered were
9890e093d99SMel Gorman 	 * backed by a congested BDI. In this case, reclaimers should just
9900e093d99SMel Gorman 	 * back off and wait for congestion to clear because further reclaim
9910e093d99SMel Gorman 	 * will encounter the same problem
9920e093d99SMel Gorman 	 */
99389b5fae5SJohannes Weiner 	if (nr_dirty && nr_dirty == nr_congested && global_reclaim(sc))
9946a18adb3SKonstantin Khlebnikov 		zone_set_flag(zone, ZONE_CONGESTED);
9950e093d99SMel Gorman 
996cc59850eSKonstantin Khlebnikov 	free_hot_cold_page_list(&free_pages, 1);
997abe4c3b5SMel Gorman 
9981da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
999f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
100069980e31STim Chen 	mem_cgroup_uncharge_end();
1001d43006d5SMel Gorman 	*ret_nr_unqueued_dirty += nr_unqueued_dirty;
100292df3a72SMel Gorman 	*ret_nr_writeback += nr_writeback;
100305ff5137SAndrew Morton 	return nr_reclaimed;
10041da177e4SLinus Torvalds }
10051da177e4SLinus Torvalds 
100602c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
100702c6de8dSMinchan Kim 					    struct list_head *page_list)
100802c6de8dSMinchan Kim {
100902c6de8dSMinchan Kim 	struct scan_control sc = {
101002c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
101102c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
101202c6de8dSMinchan Kim 		.may_unmap = 1,
101302c6de8dSMinchan Kim 	};
101402c6de8dSMinchan Kim 	unsigned long ret, dummy1, dummy2;
101502c6de8dSMinchan Kim 	struct page *page, *next;
101602c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
101702c6de8dSMinchan Kim 
101802c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
101902c6de8dSMinchan Kim 		if (page_is_file_cache(page) && !PageDirty(page)) {
102002c6de8dSMinchan Kim 			ClearPageActive(page);
102102c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
102202c6de8dSMinchan Kim 		}
102302c6de8dSMinchan Kim 	}
102402c6de8dSMinchan Kim 
102502c6de8dSMinchan Kim 	ret = shrink_page_list(&clean_pages, zone, &sc,
102602c6de8dSMinchan Kim 				TTU_UNMAP|TTU_IGNORE_ACCESS,
102702c6de8dSMinchan Kim 				&dummy1, &dummy2, true);
102802c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
102902c6de8dSMinchan Kim 	__mod_zone_page_state(zone, NR_ISOLATED_FILE, -ret);
103002c6de8dSMinchan Kim 	return ret;
103102c6de8dSMinchan Kim }
103202c6de8dSMinchan Kim 
10335ad333ebSAndy Whitcroft /*
10345ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
10355ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
10365ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
10375ad333ebSAndy Whitcroft  *
10385ad333ebSAndy Whitcroft  * page:	page to consider
10395ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
10405ad333ebSAndy Whitcroft  *
10415ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
10425ad333ebSAndy Whitcroft  */
1043f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
10445ad333ebSAndy Whitcroft {
10455ad333ebSAndy Whitcroft 	int ret = -EINVAL;
10465ad333ebSAndy Whitcroft 
10475ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
10485ad333ebSAndy Whitcroft 	if (!PageLRU(page))
10495ad333ebSAndy Whitcroft 		return ret;
10505ad333ebSAndy Whitcroft 
1051e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1052e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1053894bc310SLee Schermerhorn 		return ret;
1054894bc310SLee Schermerhorn 
10555ad333ebSAndy Whitcroft 	ret = -EBUSY;
105608e552c6SKAMEZAWA Hiroyuki 
1057c8244935SMel Gorman 	/*
1058c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1059c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1060c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1061c8244935SMel Gorman 	 *
1062c8244935SMel Gorman 	 * ISOLATE_CLEAN means that only clean pages should be isolated. This
1063c8244935SMel Gorman 	 * is used by reclaim when it is cannot write to backing storage
1064c8244935SMel Gorman 	 *
1065c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1066c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1067c8244935SMel Gorman 	 */
1068c8244935SMel Gorman 	if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
1069c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1070c8244935SMel Gorman 		if (PageWriteback(page))
107139deaf85SMinchan Kim 			return ret;
107239deaf85SMinchan Kim 
1073c8244935SMel Gorman 		if (PageDirty(page)) {
1074c8244935SMel Gorman 			struct address_space *mapping;
1075c8244935SMel Gorman 
1076c8244935SMel Gorman 			/* ISOLATE_CLEAN means only clean pages */
1077c8244935SMel Gorman 			if (mode & ISOLATE_CLEAN)
1078c8244935SMel Gorman 				return ret;
1079c8244935SMel Gorman 
1080c8244935SMel Gorman 			/*
1081c8244935SMel Gorman 			 * Only pages without mappings or that have a
1082c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
1083c8244935SMel Gorman 			 * without blocking
1084c8244935SMel Gorman 			 */
1085c8244935SMel Gorman 			mapping = page_mapping(page);
1086c8244935SMel Gorman 			if (mapping && !mapping->a_ops->migratepage)
1087c8244935SMel Gorman 				return ret;
1088c8244935SMel Gorman 		}
1089c8244935SMel Gorman 	}
1090c8244935SMel Gorman 
1091f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1092f80c0673SMinchan Kim 		return ret;
1093f80c0673SMinchan Kim 
10945ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
10955ad333ebSAndy Whitcroft 		/*
10965ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
10975ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
10985ad333ebSAndy Whitcroft 		 * page release code relies on it.
10995ad333ebSAndy Whitcroft 		 */
11005ad333ebSAndy Whitcroft 		ClearPageLRU(page);
11015ad333ebSAndy Whitcroft 		ret = 0;
11025ad333ebSAndy Whitcroft 	}
11035ad333ebSAndy Whitcroft 
11045ad333ebSAndy Whitcroft 	return ret;
11055ad333ebSAndy Whitcroft }
11065ad333ebSAndy Whitcroft 
110749d2e9ccSChristoph Lameter /*
11081da177e4SLinus Torvalds  * zone->lru_lock is heavily contended.  Some of the functions that
11091da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
11101da177e4SLinus Torvalds  * and working on them outside the LRU lock.
11111da177e4SLinus Torvalds  *
11121da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
11131da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
11141da177e4SLinus Torvalds  *
11151da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
11161da177e4SLinus Torvalds  *
11171da177e4SLinus Torvalds  * @nr_to_scan:	The number of pages to look through on the list.
11185dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
11191da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1120f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1121fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
11225ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
11233cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
11241da177e4SLinus Torvalds  *
11251da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
11261da177e4SLinus Torvalds  */
112769e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
11285dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1129fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
11303cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
11311da177e4SLinus Torvalds {
113275b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
113369e05944SAndrew Morton 	unsigned long nr_taken = 0;
1134c9b02d97SWu Fengguang 	unsigned long scan;
11351da177e4SLinus Torvalds 
1136c9b02d97SWu Fengguang 	for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
11375ad333ebSAndy Whitcroft 		struct page *page;
1138fa9add64SHugh Dickins 		int nr_pages;
11395ad333ebSAndy Whitcroft 
11401da177e4SLinus Torvalds 		page = lru_to_page(src);
11411da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
11421da177e4SLinus Torvalds 
1143725d704eSNick Piggin 		VM_BUG_ON(!PageLRU(page));
11448d438f96SNick Piggin 
1145f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
11465ad333ebSAndy Whitcroft 		case 0:
1147fa9add64SHugh Dickins 			nr_pages = hpage_nr_pages(page);
1148fa9add64SHugh Dickins 			mem_cgroup_update_lru_size(lruvec, lru, -nr_pages);
11495ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
1150fa9add64SHugh Dickins 			nr_taken += nr_pages;
11515ad333ebSAndy Whitcroft 			break;
11527c8ee9a8SNick Piggin 
11535ad333ebSAndy Whitcroft 		case -EBUSY:
11545ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
11555ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
11565ad333ebSAndy Whitcroft 			continue;
11575ad333ebSAndy Whitcroft 
11585ad333ebSAndy Whitcroft 		default:
11595ad333ebSAndy Whitcroft 			BUG();
11605ad333ebSAndy Whitcroft 		}
11615ad333ebSAndy Whitcroft 	}
11621da177e4SLinus Torvalds 
1163f626012dSHugh Dickins 	*nr_scanned = scan;
116475b00af7SHugh Dickins 	trace_mm_vmscan_lru_isolate(sc->order, nr_to_scan, scan,
116575b00af7SHugh Dickins 				    nr_taken, mode, is_file_lru(lru));
11661da177e4SLinus Torvalds 	return nr_taken;
11671da177e4SLinus Torvalds }
11681da177e4SLinus Torvalds 
116962695a84SNick Piggin /**
117062695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
117162695a84SNick Piggin  * @page: page to isolate from its LRU list
117262695a84SNick Piggin  *
117362695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
117462695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
117562695a84SNick Piggin  *
117662695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
117762695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
117862695a84SNick Piggin  *
117962695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1180894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1181894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1182894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
118362695a84SNick Piggin  *
118462695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
118562695a84SNick Piggin  * found will be decremented.
118662695a84SNick Piggin  *
118762695a84SNick Piggin  * Restrictions:
118862695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
118962695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
119062695a84SNick Piggin  *     without a stable reference).
119162695a84SNick Piggin  * (2) the lru_lock must not be held.
119262695a84SNick Piggin  * (3) interrupts must be enabled.
119362695a84SNick Piggin  */
119462695a84SNick Piggin int isolate_lru_page(struct page *page)
119562695a84SNick Piggin {
119662695a84SNick Piggin 	int ret = -EBUSY;
119762695a84SNick Piggin 
11980c917313SKonstantin Khlebnikov 	VM_BUG_ON(!page_count(page));
11990c917313SKonstantin Khlebnikov 
120062695a84SNick Piggin 	if (PageLRU(page)) {
120162695a84SNick Piggin 		struct zone *zone = page_zone(page);
1202fa9add64SHugh Dickins 		struct lruvec *lruvec;
120362695a84SNick Piggin 
120462695a84SNick Piggin 		spin_lock_irq(&zone->lru_lock);
1205fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
12060c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1207894bc310SLee Schermerhorn 			int lru = page_lru(page);
12080c917313SKonstantin Khlebnikov 			get_page(page);
120962695a84SNick Piggin 			ClearPageLRU(page);
1210fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1211fa9add64SHugh Dickins 			ret = 0;
121262695a84SNick Piggin 		}
121362695a84SNick Piggin 		spin_unlock_irq(&zone->lru_lock);
121462695a84SNick Piggin 	}
121562695a84SNick Piggin 	return ret;
121662695a84SNick Piggin }
121762695a84SNick Piggin 
12185ad333ebSAndy Whitcroft /*
1219d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1220d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1221d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1222d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1223d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
122435cd7815SRik van Riel  */
122535cd7815SRik van Riel static int too_many_isolated(struct zone *zone, int file,
122635cd7815SRik van Riel 		struct scan_control *sc)
122735cd7815SRik van Riel {
122835cd7815SRik van Riel 	unsigned long inactive, isolated;
122935cd7815SRik van Riel 
123035cd7815SRik van Riel 	if (current_is_kswapd())
123135cd7815SRik van Riel 		return 0;
123235cd7815SRik van Riel 
123389b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
123435cd7815SRik van Riel 		return 0;
123535cd7815SRik van Riel 
123635cd7815SRik van Riel 	if (file) {
123735cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_FILE);
123835cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_FILE);
123935cd7815SRik van Riel 	} else {
124035cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_ANON);
124135cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_ANON);
124235cd7815SRik van Riel 	}
124335cd7815SRik van Riel 
12443cf23841SFengguang Wu 	/*
12453cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
12463cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
12473cf23841SFengguang Wu 	 * deadlock.
12483cf23841SFengguang Wu 	 */
12493cf23841SFengguang Wu 	if ((sc->gfp_mask & GFP_IOFS) == GFP_IOFS)
12503cf23841SFengguang Wu 		inactive >>= 3;
12513cf23841SFengguang Wu 
125235cd7815SRik van Riel 	return isolated > inactive;
125335cd7815SRik van Riel }
125435cd7815SRik van Riel 
125566635629SMel Gorman static noinline_for_stack void
125675b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
125766635629SMel Gorman {
125827ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
125927ac81d8SKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
12603f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
126166635629SMel Gorman 
126266635629SMel Gorman 	/*
126366635629SMel Gorman 	 * Put back any unfreeable pages.
126466635629SMel Gorman 	 */
126566635629SMel Gorman 	while (!list_empty(page_list)) {
12663f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
126766635629SMel Gorman 		int lru;
12683f79768fSHugh Dickins 
126966635629SMel Gorman 		VM_BUG_ON(PageLRU(page));
127066635629SMel Gorman 		list_del(&page->lru);
127139b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
127266635629SMel Gorman 			spin_unlock_irq(&zone->lru_lock);
127366635629SMel Gorman 			putback_lru_page(page);
127466635629SMel Gorman 			spin_lock_irq(&zone->lru_lock);
127566635629SMel Gorman 			continue;
127666635629SMel Gorman 		}
1277fa9add64SHugh Dickins 
1278fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
1279fa9add64SHugh Dickins 
12807a608572SLinus Torvalds 		SetPageLRU(page);
128166635629SMel Gorman 		lru = page_lru(page);
1282fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1283fa9add64SHugh Dickins 
128466635629SMel Gorman 		if (is_active_lru(lru)) {
128566635629SMel Gorman 			int file = is_file_lru(lru);
12869992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
12879992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
128866635629SMel Gorman 		}
12892bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
12902bcf8879SHugh Dickins 			__ClearPageLRU(page);
12912bcf8879SHugh Dickins 			__ClearPageActive(page);
1292fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
12932bcf8879SHugh Dickins 
12942bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
129566635629SMel Gorman 				spin_unlock_irq(&zone->lru_lock);
12962bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
129766635629SMel Gorman 				spin_lock_irq(&zone->lru_lock);
12982bcf8879SHugh Dickins 			} else
12992bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
130066635629SMel Gorman 		}
130166635629SMel Gorman 	}
130266635629SMel Gorman 
13033f79768fSHugh Dickins 	/*
13043f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
13053f79768fSHugh Dickins 	 */
13063f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
130766635629SMel Gorman }
130866635629SMel Gorman 
130966635629SMel Gorman /*
13101742f19fSAndrew Morton  * shrink_inactive_list() is a helper for shrink_zone().  It returns the number
13111742f19fSAndrew Morton  * of reclaimed pages
13121da177e4SLinus Torvalds  */
131366635629SMel Gorman static noinline_for_stack unsigned long
13141a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
13159e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
13161da177e4SLinus Torvalds {
13171da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1318e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
131905ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1320e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
132192df3a72SMel Gorman 	unsigned long nr_dirty = 0;
132292df3a72SMel Gorman 	unsigned long nr_writeback = 0;
1323f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
13243cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
13251a93be0eSKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
13261a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
132778dc583dSKOSAKI Motohiro 
132835cd7815SRik van Riel 	while (unlikely(too_many_isolated(zone, file, sc))) {
132958355c78SKOSAKI Motohiro 		congestion_wait(BLK_RW_ASYNC, HZ/10);
133035cd7815SRik van Riel 
133135cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
133235cd7815SRik van Riel 		if (fatal_signal_pending(current))
133335cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
133435cd7815SRik van Riel 	}
133535cd7815SRik van Riel 
13361da177e4SLinus Torvalds 	lru_add_drain();
1337f80c0673SMinchan Kim 
1338f80c0673SMinchan Kim 	if (!sc->may_unmap)
133961317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1340f80c0673SMinchan Kim 	if (!sc->may_writepage)
134161317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1342f80c0673SMinchan Kim 
13431da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
13441da177e4SLinus Torvalds 
13455dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
13465dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
134795d918fcSKonstantin Khlebnikov 
134895d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
134995d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
135095d918fcSKonstantin Khlebnikov 
135189b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
1352e247dbceSKOSAKI Motohiro 		zone->pages_scanned += nr_scanned;
1353b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
135475b00af7SHugh Dickins 			__count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scanned);
1355b35ea17bSKOSAKI Motohiro 		else
135675b00af7SHugh Dickins 			__count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scanned);
1357b35ea17bSKOSAKI Motohiro 	}
135866635629SMel Gorman 	spin_unlock_irq(&zone->lru_lock);
1359d563c050SHillf Danton 
1360d563c050SHillf Danton 	if (nr_taken == 0)
136166635629SMel Gorman 		return 0;
1362b35ea17bSKOSAKI Motohiro 
136302c6de8dSMinchan Kim 	nr_reclaimed = shrink_page_list(&page_list, zone, sc, TTU_UNMAP,
136402c6de8dSMinchan Kim 					&nr_dirty, &nr_writeback, false);
1365c661b078SAndy Whitcroft 
13663f79768fSHugh Dickins 	spin_lock_irq(&zone->lru_lock);
13673f79768fSHugh Dickins 
136895d918fcSKonstantin Khlebnikov 	reclaim_stat->recent_scanned[file] += nr_taken;
1369d563c050SHillf Danton 
1370904249aaSYing Han 	if (global_reclaim(sc)) {
1371b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1372904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_KSWAPD, zone,
1373904249aaSYing Han 					       nr_reclaimed);
1374904249aaSYing Han 		else
1375904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_DIRECT, zone,
1376904249aaSYing Han 					       nr_reclaimed);
1377904249aaSYing Han 	}
1378a74609faSNick Piggin 
137927ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
13803f79768fSHugh Dickins 
138195d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
13823f79768fSHugh Dickins 
13833f79768fSHugh Dickins 	spin_unlock_irq(&zone->lru_lock);
13843f79768fSHugh Dickins 
13853f79768fSHugh Dickins 	free_hot_cold_page_list(&page_list, 1);
1386e11da5b4SMel Gorman 
138792df3a72SMel Gorman 	/*
138892df3a72SMel Gorman 	 * If reclaim is isolating dirty pages under writeback, it implies
138992df3a72SMel Gorman 	 * that the long-lived page allocation rate is exceeding the page
139092df3a72SMel Gorman 	 * laundering rate. Either the global limits are not being effective
139192df3a72SMel Gorman 	 * at throttling processes due to the page distribution throughout
139292df3a72SMel Gorman 	 * zones or there is heavy usage of a slow backing device. The
139392df3a72SMel Gorman 	 * only option is to throttle from reclaim context which is not ideal
139492df3a72SMel Gorman 	 * as there is no guarantee the dirtying process is throttled in the
139592df3a72SMel Gorman 	 * same way balance_dirty_pages() manages.
139692df3a72SMel Gorman 	 *
139792df3a72SMel Gorman 	 * This scales the number of dirty pages that must be under writeback
139892df3a72SMel Gorman 	 * before throttling depending on priority. It is a simple backoff
139992df3a72SMel Gorman 	 * function that has the most effect in the range DEF_PRIORITY to
140092df3a72SMel Gorman 	 * DEF_PRIORITY-2 which is the priority reclaim is considered to be
140192df3a72SMel Gorman 	 * in trouble and reclaim is considered to be in trouble.
140292df3a72SMel Gorman 	 *
140392df3a72SMel Gorman 	 * DEF_PRIORITY   100% isolated pages must be PageWriteback to throttle
140492df3a72SMel Gorman 	 * DEF_PRIORITY-1  50% must be PageWriteback
140592df3a72SMel Gorman 	 * DEF_PRIORITY-2  25% must be PageWriteback, kswapd in trouble
140692df3a72SMel Gorman 	 * ...
140792df3a72SMel Gorman 	 * DEF_PRIORITY-6 For SWAP_CLUSTER_MAX isolated pages, throttle if any
140892df3a72SMel Gorman 	 *                     isolated page is PageWriteback
140992df3a72SMel Gorman 	 */
14109e3b2f8cSKonstantin Khlebnikov 	if (nr_writeback && nr_writeback >=
1411*283aba9fSMel Gorman 			(nr_taken >> (DEF_PRIORITY - sc->priority))) {
141292df3a72SMel Gorman 		wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10);
1413*283aba9fSMel Gorman 		zone_set_flag(zone, ZONE_WRITEBACK);
1414*283aba9fSMel Gorman 	}
141592df3a72SMel Gorman 
1416d43006d5SMel Gorman 	/*
1417d43006d5SMel Gorman 	 * Similarly, if many dirty pages are encountered that are not
1418d43006d5SMel Gorman 	 * currently being written then flag that kswapd should start
1419d43006d5SMel Gorman 	 * writing back pages.
1420d43006d5SMel Gorman 	 */
1421d43006d5SMel Gorman 	if (global_reclaim(sc) && nr_dirty &&
1422d43006d5SMel Gorman 			nr_dirty >= (nr_taken >> (DEF_PRIORITY - sc->priority)))
1423d43006d5SMel Gorman 		zone_set_flag(zone, ZONE_TAIL_LRU_DIRTY);
1424d43006d5SMel Gorman 
1425e11da5b4SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(zone->zone_pgdat->node_id,
1426e11da5b4SMel Gorman 		zone_idx(zone),
1427e11da5b4SMel Gorman 		nr_scanned, nr_reclaimed,
14289e3b2f8cSKonstantin Khlebnikov 		sc->priority,
142923b9da55SMel Gorman 		trace_shrink_flags(file));
143005ff5137SAndrew Morton 	return nr_reclaimed;
14311da177e4SLinus Torvalds }
14321da177e4SLinus Torvalds 
14333bb1a852SMartin Bligh /*
14341cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
14351cfb419bSKAMEZAWA Hiroyuki  *
14361cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
14371cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
14381cfb419bSKAMEZAWA Hiroyuki  *
14391cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
14401cfb419bSKAMEZAWA Hiroyuki  * appropriate to hold zone->lru_lock across the whole operation.  But if
14411cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
14421cfb419bSKAMEZAWA Hiroyuki  * should drop zone->lru_lock around each page.  It's impossible to balance
14431cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
14441cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
14451cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
14461cfb419bSKAMEZAWA Hiroyuki  *
14471cfb419bSKAMEZAWA Hiroyuki  * The downside is that we have to touch page->_count against each page.
14481cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
14491cfb419bSKAMEZAWA Hiroyuki  */
14501cfb419bSKAMEZAWA Hiroyuki 
1451fa9add64SHugh Dickins static void move_active_pages_to_lru(struct lruvec *lruvec,
14523eb4140fSWu Fengguang 				     struct list_head *list,
14532bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
14543eb4140fSWu Fengguang 				     enum lru_list lru)
14553eb4140fSWu Fengguang {
1456fa9add64SHugh Dickins 	struct zone *zone = lruvec_zone(lruvec);
14573eb4140fSWu Fengguang 	unsigned long pgmoved = 0;
14583eb4140fSWu Fengguang 	struct page *page;
1459fa9add64SHugh Dickins 	int nr_pages;
14603eb4140fSWu Fengguang 
14613eb4140fSWu Fengguang 	while (!list_empty(list)) {
14623eb4140fSWu Fengguang 		page = lru_to_page(list);
1463fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
14643eb4140fSWu Fengguang 
14653eb4140fSWu Fengguang 		VM_BUG_ON(PageLRU(page));
14663eb4140fSWu Fengguang 		SetPageLRU(page);
14673eb4140fSWu Fengguang 
1468fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
1469fa9add64SHugh Dickins 		mem_cgroup_update_lru_size(lruvec, lru, nr_pages);
1470925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
1471fa9add64SHugh Dickins 		pgmoved += nr_pages;
14723eb4140fSWu Fengguang 
14732bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
14742bcf8879SHugh Dickins 			__ClearPageLRU(page);
14752bcf8879SHugh Dickins 			__ClearPageActive(page);
1476fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
14772bcf8879SHugh Dickins 
14782bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
14793eb4140fSWu Fengguang 				spin_unlock_irq(&zone->lru_lock);
14802bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
14813eb4140fSWu Fengguang 				spin_lock_irq(&zone->lru_lock);
14822bcf8879SHugh Dickins 			} else
14832bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
14843eb4140fSWu Fengguang 		}
14853eb4140fSWu Fengguang 	}
14863eb4140fSWu Fengguang 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved);
14873eb4140fSWu Fengguang 	if (!is_active_lru(lru))
14883eb4140fSWu Fengguang 		__count_vm_events(PGDEACTIVATE, pgmoved);
14893eb4140fSWu Fengguang }
14901cfb419bSKAMEZAWA Hiroyuki 
1491f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
14921a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1493f16015fbSJohannes Weiner 			       struct scan_control *sc,
14949e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
14951cfb419bSKAMEZAWA Hiroyuki {
149644c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1497f626012dSHugh Dickins 	unsigned long nr_scanned;
14986fe6b7e3SWu Fengguang 	unsigned long vm_flags;
14991cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
15008cab4754SWu Fengguang 	LIST_HEAD(l_active);
1501b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
15021cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
15031a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
150444c241f1SKOSAKI Motohiro 	unsigned long nr_rotated = 0;
1505f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
15063cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
15071a93be0eSKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
15081cfb419bSKAMEZAWA Hiroyuki 
15091da177e4SLinus Torvalds 	lru_add_drain();
1510f80c0673SMinchan Kim 
1511f80c0673SMinchan Kim 	if (!sc->may_unmap)
151261317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1513f80c0673SMinchan Kim 	if (!sc->may_writepage)
151461317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1515f80c0673SMinchan Kim 
15161da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
1517925b7673SJohannes Weiner 
15185dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
15195dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
152089b5fae5SJohannes Weiner 	if (global_reclaim(sc))
1521f626012dSHugh Dickins 		zone->pages_scanned += nr_scanned;
152289b5fae5SJohannes Weiner 
1523b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
15241cfb419bSKAMEZAWA Hiroyuki 
1525f626012dSHugh Dickins 	__count_zone_vm_events(PGREFILL, zone, nr_scanned);
15263cb99451SKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
1527a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
15281da177e4SLinus Torvalds 	spin_unlock_irq(&zone->lru_lock);
15291da177e4SLinus Torvalds 
15301da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
15311da177e4SLinus Torvalds 		cond_resched();
15321da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
15331da177e4SLinus Torvalds 		list_del(&page->lru);
15347e9cd484SRik van Riel 
153539b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1536894bc310SLee Schermerhorn 			putback_lru_page(page);
1537894bc310SLee Schermerhorn 			continue;
1538894bc310SLee Schermerhorn 		}
1539894bc310SLee Schermerhorn 
1540cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
1541cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
1542cc715d99SMel Gorman 				if (page_has_private(page))
1543cc715d99SMel Gorman 					try_to_release_page(page, 0);
1544cc715d99SMel Gorman 				unlock_page(page);
1545cc715d99SMel Gorman 			}
1546cc715d99SMel Gorman 		}
1547cc715d99SMel Gorman 
1548c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
1549c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
15509992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
15518cab4754SWu Fengguang 			/*
15528cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
15538cab4754SWu Fengguang 			 * give them one more trip around the active list. So
15548cab4754SWu Fengguang 			 * that executable code get better chances to stay in
15558cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
15568cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
15578cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
15588cab4754SWu Fengguang 			 * so we ignore them here.
15598cab4754SWu Fengguang 			 */
156041e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
15618cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
15628cab4754SWu Fengguang 				continue;
15638cab4754SWu Fengguang 			}
15648cab4754SWu Fengguang 		}
15657e9cd484SRik van Riel 
15665205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
15671da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
15681da177e4SLinus Torvalds 	}
15691da177e4SLinus Torvalds 
1570b555749aSAndrew Morton 	/*
15718cab4754SWu Fengguang 	 * Move pages back to the lru list.
1572b555749aSAndrew Morton 	 */
15732a1dc509SJohannes Weiner 	spin_lock_irq(&zone->lru_lock);
15744f98a2feSRik van Riel 	/*
15758cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
15768cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
15778cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
15788cab4754SWu Fengguang 	 * get_scan_ratio.
1579556adecbSRik van Riel 	 */
1580b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
1581556adecbSRik van Riel 
1582fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
1583fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1584a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1585f8891e5eSChristoph Lameter 	spin_unlock_irq(&zone->lru_lock);
15862bcf8879SHugh Dickins 
15872bcf8879SHugh Dickins 	free_hot_cold_page_list(&l_hold, 1);
15881da177e4SLinus Torvalds }
15891da177e4SLinus Torvalds 
159074e3f3c3SMinchan Kim #ifdef CONFIG_SWAP
159114797e23SKOSAKI Motohiro static int inactive_anon_is_low_global(struct zone *zone)
1592f89eb90eSKOSAKI Motohiro {
1593f89eb90eSKOSAKI Motohiro 	unsigned long active, inactive;
1594f89eb90eSKOSAKI Motohiro 
1595f89eb90eSKOSAKI Motohiro 	active = zone_page_state(zone, NR_ACTIVE_ANON);
1596f89eb90eSKOSAKI Motohiro 	inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1597f89eb90eSKOSAKI Motohiro 
1598f89eb90eSKOSAKI Motohiro 	if (inactive * zone->inactive_ratio < active)
1599f89eb90eSKOSAKI Motohiro 		return 1;
1600f89eb90eSKOSAKI Motohiro 
1601f89eb90eSKOSAKI Motohiro 	return 0;
1602f89eb90eSKOSAKI Motohiro }
1603f89eb90eSKOSAKI Motohiro 
160414797e23SKOSAKI Motohiro /**
160514797e23SKOSAKI Motohiro  * inactive_anon_is_low - check if anonymous pages need to be deactivated
1606c56d5c7dSKonstantin Khlebnikov  * @lruvec: LRU vector to check
160714797e23SKOSAKI Motohiro  *
160814797e23SKOSAKI Motohiro  * Returns true if the zone does not have enough inactive anon pages,
160914797e23SKOSAKI Motohiro  * meaning some active anon pages need to be deactivated.
161014797e23SKOSAKI Motohiro  */
1611c56d5c7dSKonstantin Khlebnikov static int inactive_anon_is_low(struct lruvec *lruvec)
161214797e23SKOSAKI Motohiro {
161374e3f3c3SMinchan Kim 	/*
161474e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
161574e3f3c3SMinchan Kim 	 * is pointless.
161674e3f3c3SMinchan Kim 	 */
161774e3f3c3SMinchan Kim 	if (!total_swap_pages)
161874e3f3c3SMinchan Kim 		return 0;
161974e3f3c3SMinchan Kim 
1620c3c787e8SHugh Dickins 	if (!mem_cgroup_disabled())
1621c56d5c7dSKonstantin Khlebnikov 		return mem_cgroup_inactive_anon_is_low(lruvec);
1622f16015fbSJohannes Weiner 
1623c56d5c7dSKonstantin Khlebnikov 	return inactive_anon_is_low_global(lruvec_zone(lruvec));
162414797e23SKOSAKI Motohiro }
162574e3f3c3SMinchan Kim #else
1626c56d5c7dSKonstantin Khlebnikov static inline int inactive_anon_is_low(struct lruvec *lruvec)
162774e3f3c3SMinchan Kim {
162874e3f3c3SMinchan Kim 	return 0;
162974e3f3c3SMinchan Kim }
163074e3f3c3SMinchan Kim #endif
163114797e23SKOSAKI Motohiro 
163256e49d21SRik van Riel /**
163356e49d21SRik van Riel  * inactive_file_is_low - check if file pages need to be deactivated
1634c56d5c7dSKonstantin Khlebnikov  * @lruvec: LRU vector to check
163556e49d21SRik van Riel  *
163656e49d21SRik van Riel  * When the system is doing streaming IO, memory pressure here
163756e49d21SRik van Riel  * ensures that active file pages get deactivated, until more
163856e49d21SRik van Riel  * than half of the file pages are on the inactive list.
163956e49d21SRik van Riel  *
164056e49d21SRik van Riel  * Once we get to that situation, protect the system's working
164156e49d21SRik van Riel  * set from being evicted by disabling active file page aging.
164256e49d21SRik van Riel  *
164356e49d21SRik van Riel  * This uses a different ratio than the anonymous pages, because
164456e49d21SRik van Riel  * the page cache uses a use-once replacement algorithm.
164556e49d21SRik van Riel  */
1646c56d5c7dSKonstantin Khlebnikov static int inactive_file_is_low(struct lruvec *lruvec)
164756e49d21SRik van Riel {
1648e3790144SJohannes Weiner 	unsigned long inactive;
1649e3790144SJohannes Weiner 	unsigned long active;
165056e49d21SRik van Riel 
1651e3790144SJohannes Weiner 	inactive = get_lru_size(lruvec, LRU_INACTIVE_FILE);
1652e3790144SJohannes Weiner 	active = get_lru_size(lruvec, LRU_ACTIVE_FILE);
1653e3790144SJohannes Weiner 
1654e3790144SJohannes Weiner 	return active > inactive;
165556e49d21SRik van Riel }
165656e49d21SRik van Riel 
165775b00af7SHugh Dickins static int inactive_list_is_low(struct lruvec *lruvec, enum lru_list lru)
1658b39415b2SRik van Riel {
165975b00af7SHugh Dickins 	if (is_file_lru(lru))
1660c56d5c7dSKonstantin Khlebnikov 		return inactive_file_is_low(lruvec);
1661b39415b2SRik van Riel 	else
1662c56d5c7dSKonstantin Khlebnikov 		return inactive_anon_is_low(lruvec);
1663b39415b2SRik van Riel }
1664b39415b2SRik van Riel 
16654f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
16661a93be0eSKonstantin Khlebnikov 				 struct lruvec *lruvec, struct scan_control *sc)
1667b69408e8SChristoph Lameter {
1668b39415b2SRik van Riel 	if (is_active_lru(lru)) {
166975b00af7SHugh Dickins 		if (inactive_list_is_low(lruvec, lru))
16701a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
1671556adecbSRik van Riel 		return 0;
1672556adecbSRik van Riel 	}
1673556adecbSRik van Riel 
16741a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
1675b69408e8SChristoph Lameter }
1676b69408e8SChristoph Lameter 
16773d58ab5cSKonstantin Khlebnikov static int vmscan_swappiness(struct scan_control *sc)
16781f4c025bSKAMEZAWA Hiroyuki {
167989b5fae5SJohannes Weiner 	if (global_reclaim(sc))
16801f4c025bSKAMEZAWA Hiroyuki 		return vm_swappiness;
16813d58ab5cSKonstantin Khlebnikov 	return mem_cgroup_swappiness(sc->target_mem_cgroup);
16821f4c025bSKAMEZAWA Hiroyuki }
16831f4c025bSKAMEZAWA Hiroyuki 
16849a265114SJohannes Weiner enum scan_balance {
16859a265114SJohannes Weiner 	SCAN_EQUAL,
16869a265114SJohannes Weiner 	SCAN_FRACT,
16879a265114SJohannes Weiner 	SCAN_ANON,
16889a265114SJohannes Weiner 	SCAN_FILE,
16899a265114SJohannes Weiner };
16909a265114SJohannes Weiner 
16911da177e4SLinus Torvalds /*
16924f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
16934f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
16944f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
16954f98a2feSRik van Riel  * onto the active list instead of evict.
16964f98a2feSRik van Riel  *
1697be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
1698be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
16994f98a2feSRik van Riel  */
170090126375SKonstantin Khlebnikov static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
17019e3b2f8cSKonstantin Khlebnikov 			   unsigned long *nr)
17024f98a2feSRik van Riel {
170390126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
17049a265114SJohannes Weiner 	u64 fraction[2];
17059a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
170690126375SKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
17079a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
17089a265114SJohannes Weiner 	enum scan_balance scan_balance;
17099a265114SJohannes Weiner 	unsigned long anon, file, free;
17109a265114SJohannes Weiner 	bool force_scan = false;
17119a265114SJohannes Weiner 	unsigned long ap, fp;
17129a265114SJohannes Weiner 	enum lru_list lru;
1713246e87a9SKAMEZAWA Hiroyuki 
1714f11c0ca5SJohannes Weiner 	/*
1715f11c0ca5SJohannes Weiner 	 * If the zone or memcg is small, nr[l] can be 0.  This
1716f11c0ca5SJohannes Weiner 	 * results in no scanning on this priority and a potential
1717f11c0ca5SJohannes Weiner 	 * priority drop.  Global direct reclaim can go to the next
1718f11c0ca5SJohannes Weiner 	 * zone and tends to have no problems. Global kswapd is for
1719f11c0ca5SJohannes Weiner 	 * zone balancing and it needs to scan a minimum amount. When
1720f11c0ca5SJohannes Weiner 	 * reclaiming for a memcg, a priority drop can cause high
1721f11c0ca5SJohannes Weiner 	 * latencies, so it's better to scan a minimum amount there as
1722f11c0ca5SJohannes Weiner 	 * well.
1723f11c0ca5SJohannes Weiner 	 */
172490126375SKonstantin Khlebnikov 	if (current_is_kswapd() && zone->all_unreclaimable)
1725a4d3e9e7SJohannes Weiner 		force_scan = true;
172689b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
1727a4d3e9e7SJohannes Weiner 		force_scan = true;
172876a33fc3SShaohua Li 
172976a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
1730ec8acf20SShaohua Li 	if (!sc->may_swap || (get_nr_swap_pages() <= 0)) {
17319a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
173276a33fc3SShaohua Li 		goto out;
173376a33fc3SShaohua Li 	}
17344f98a2feSRik van Riel 
173510316b31SJohannes Weiner 	/*
173610316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
173710316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
173810316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
173910316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
174010316b31SJohannes Weiner 	 * too expensive.
174110316b31SJohannes Weiner 	 */
174210316b31SJohannes Weiner 	if (!global_reclaim(sc) && !vmscan_swappiness(sc)) {
17439a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
174410316b31SJohannes Weiner 		goto out;
174510316b31SJohannes Weiner 	}
174610316b31SJohannes Weiner 
174710316b31SJohannes Weiner 	/*
174810316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
174910316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
175010316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
175110316b31SJohannes Weiner 	 */
175210316b31SJohannes Weiner 	if (!sc->priority && vmscan_swappiness(sc)) {
17539a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
175410316b31SJohannes Weiner 		goto out;
175510316b31SJohannes Weiner 	}
175610316b31SJohannes Weiner 
17574d7dcca2SHugh Dickins 	anon  = get_lru_size(lruvec, LRU_ACTIVE_ANON) +
17584d7dcca2SHugh Dickins 		get_lru_size(lruvec, LRU_INACTIVE_ANON);
17594d7dcca2SHugh Dickins 	file  = get_lru_size(lruvec, LRU_ACTIVE_FILE) +
17604d7dcca2SHugh Dickins 		get_lru_size(lruvec, LRU_INACTIVE_FILE);
1761a4d3e9e7SJohannes Weiner 
176211d16c25SJohannes Weiner 	/*
176311d16c25SJohannes Weiner 	 * If it's foreseeable that reclaiming the file cache won't be
176411d16c25SJohannes Weiner 	 * enough to get the zone back into a desirable shape, we have
176511d16c25SJohannes Weiner 	 * to swap.  Better start now and leave the - probably heavily
176611d16c25SJohannes Weiner 	 * thrashing - remaining file pages alone.
176711d16c25SJohannes Weiner 	 */
176889b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
176990126375SKonstantin Khlebnikov 		free = zone_page_state(zone, NR_FREE_PAGES);
177090126375SKonstantin Khlebnikov 		if (unlikely(file + free <= high_wmark_pages(zone))) {
17719a265114SJohannes Weiner 			scan_balance = SCAN_ANON;
177276a33fc3SShaohua Li 			goto out;
17737c5bd705SJohannes Weiner 		}
17747c5bd705SJohannes Weiner 	}
17757c5bd705SJohannes Weiner 
1776e9868505SRik van Riel 	/*
17777c5bd705SJohannes Weiner 	 * There is enough inactive page cache, do not reclaim
17787c5bd705SJohannes Weiner 	 * anything from the anonymous working set right now.
1779e9868505SRik van Riel 	 */
17807c5bd705SJohannes Weiner 	if (!inactive_file_is_low(lruvec)) {
17819a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
1782e9868505SRik van Riel 		goto out;
17834f98a2feSRik van Riel 	}
17844f98a2feSRik van Riel 
17859a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
17869a265114SJohannes Weiner 
17874f98a2feSRik van Riel 	/*
178858c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
178958c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
179058c37f6eSKOSAKI Motohiro 	 */
17913d58ab5cSKonstantin Khlebnikov 	anon_prio = vmscan_swappiness(sc);
179275b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
179358c37f6eSKOSAKI Motohiro 
179458c37f6eSKOSAKI Motohiro 	/*
17954f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
17964f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
17974f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
17984f98a2feSRik van Riel 	 *
17994f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
18004f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
18014f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
18024f98a2feSRik van Riel 	 *
18034f98a2feSRik van Riel 	 * anon in [0], file in [1]
18044f98a2feSRik van Riel 	 */
180590126375SKonstantin Khlebnikov 	spin_lock_irq(&zone->lru_lock);
180658c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
18076e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
18086e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
18094f98a2feSRik van Riel 	}
18104f98a2feSRik van Riel 
18116e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
18126e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
18136e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
18144f98a2feSRik van Riel 	}
18154f98a2feSRik van Riel 
18164f98a2feSRik van Riel 	/*
181700d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
181800d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
181900d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
18204f98a2feSRik van Riel 	 */
1821fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
18226e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
18234f98a2feSRik van Riel 
1824fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
18256e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
182690126375SKonstantin Khlebnikov 	spin_unlock_irq(&zone->lru_lock);
18274f98a2feSRik van Riel 
182876a33fc3SShaohua Li 	fraction[0] = ap;
182976a33fc3SShaohua Li 	fraction[1] = fp;
183076a33fc3SShaohua Li 	denominator = ap + fp + 1;
183176a33fc3SShaohua Li out:
18324111304dSHugh Dickins 	for_each_evictable_lru(lru) {
18334111304dSHugh Dickins 		int file = is_file_lru(lru);
1834d778df51SJohannes Weiner 		unsigned long size;
183576a33fc3SShaohua Li 		unsigned long scan;
183676a33fc3SShaohua Li 
1837d778df51SJohannes Weiner 		size = get_lru_size(lruvec, lru);
1838d778df51SJohannes Weiner 		scan = size >> sc->priority;
18399a265114SJohannes Weiner 
1840f11c0ca5SJohannes Weiner 		if (!scan && force_scan)
1841d778df51SJohannes Weiner 			scan = min(size, SWAP_CLUSTER_MAX);
18429a265114SJohannes Weiner 
18439a265114SJohannes Weiner 		switch (scan_balance) {
18449a265114SJohannes Weiner 		case SCAN_EQUAL:
18459a265114SJohannes Weiner 			/* Scan lists relative to size */
18469a265114SJohannes Weiner 			break;
18479a265114SJohannes Weiner 		case SCAN_FRACT:
18489a265114SJohannes Weiner 			/*
18499a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
18509a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
18519a265114SJohannes Weiner 			 */
185276a33fc3SShaohua Li 			scan = div64_u64(scan * fraction[file], denominator);
18539a265114SJohannes Weiner 			break;
18549a265114SJohannes Weiner 		case SCAN_FILE:
18559a265114SJohannes Weiner 		case SCAN_ANON:
18569a265114SJohannes Weiner 			/* Scan one type exclusively */
18579a265114SJohannes Weiner 			if ((scan_balance == SCAN_FILE) != file)
18589a265114SJohannes Weiner 				scan = 0;
18599a265114SJohannes Weiner 			break;
18609a265114SJohannes Weiner 		default:
18619a265114SJohannes Weiner 			/* Look ma, no brain */
18629a265114SJohannes Weiner 			BUG();
18639a265114SJohannes Weiner 		}
18644111304dSHugh Dickins 		nr[lru] = scan;
186576a33fc3SShaohua Li 	}
18666e08a369SWu Fengguang }
18674f98a2feSRik van Riel 
18689b4f98cdSJohannes Weiner /*
18699b4f98cdSJohannes Weiner  * This is a basic per-zone page freer.  Used by both kswapd and direct reclaim.
18709b4f98cdSJohannes Weiner  */
18719b4f98cdSJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
18729b4f98cdSJohannes Weiner {
18739b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
1874e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
18759b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
18769b4f98cdSJohannes Weiner 	enum lru_list lru;
18779b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
18789b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
18799b4f98cdSJohannes Weiner 	struct blk_plug plug;
1880e82e0561SMel Gorman 	bool scan_adjusted = false;
18819b4f98cdSJohannes Weiner 
18829b4f98cdSJohannes Weiner 	get_scan_count(lruvec, sc, nr);
18839b4f98cdSJohannes Weiner 
1884e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
1885e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
1886e82e0561SMel Gorman 
18879b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
18889b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
18899b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
1890e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
1891e82e0561SMel Gorman 		unsigned long nr_scanned;
1892e82e0561SMel Gorman 
18939b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
18949b4f98cdSJohannes Weiner 			if (nr[lru]) {
18959b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
18969b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
18979b4f98cdSJohannes Weiner 
18989b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
18999b4f98cdSJohannes Weiner 							    lruvec, sc);
19009b4f98cdSJohannes Weiner 			}
19019b4f98cdSJohannes Weiner 		}
1902e82e0561SMel Gorman 
1903e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
1904e82e0561SMel Gorman 			continue;
1905e82e0561SMel Gorman 
19069b4f98cdSJohannes Weiner 		/*
1907e82e0561SMel Gorman 		 * For global direct reclaim, reclaim only the number of pages
1908e82e0561SMel Gorman 		 * requested. Less care is taken to scan proportionally as it
1909e82e0561SMel Gorman 		 * is more important to minimise direct reclaim stall latency
1910e82e0561SMel Gorman 		 * than it is to properly age the LRU lists.
19119b4f98cdSJohannes Weiner 		 */
1912e82e0561SMel Gorman 		if (global_reclaim(sc) && !current_is_kswapd())
19139b4f98cdSJohannes Weiner 			break;
1914e82e0561SMel Gorman 
1915e82e0561SMel Gorman 		/*
1916e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
1917e82e0561SMel Gorman 		 * requested. Ensure that the anon and file LRUs shrink
1918e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
1919e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
1920e82e0561SMel Gorman 		 * proportional to the original scan target.
1921e82e0561SMel Gorman 		 */
1922e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
1923e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
1924e82e0561SMel Gorman 
1925e82e0561SMel Gorman 		if (nr_file > nr_anon) {
1926e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
1927e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
1928e82e0561SMel Gorman 			lru = LRU_BASE;
1929e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
1930e82e0561SMel Gorman 		} else {
1931e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
1932e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
1933e82e0561SMel Gorman 			lru = LRU_FILE;
1934e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
1935e82e0561SMel Gorman 		}
1936e82e0561SMel Gorman 
1937e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
1938e82e0561SMel Gorman 		nr[lru] = 0;
1939e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
1940e82e0561SMel Gorman 
1941e82e0561SMel Gorman 		/*
1942e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
1943e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
1944e82e0561SMel Gorman 		 */
1945e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
1946e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
1947e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
1948e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
1949e82e0561SMel Gorman 
1950e82e0561SMel Gorman 		lru += LRU_ACTIVE;
1951e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
1952e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
1953e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
1954e82e0561SMel Gorman 
1955e82e0561SMel Gorman 		scan_adjusted = true;
19569b4f98cdSJohannes Weiner 	}
19579b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
19589b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
19599b4f98cdSJohannes Weiner 
19609b4f98cdSJohannes Weiner 	/*
19619b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
19629b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
19639b4f98cdSJohannes Weiner 	 */
19649b4f98cdSJohannes Weiner 	if (inactive_anon_is_low(lruvec))
19659b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
19669b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
19679b4f98cdSJohannes Weiner 
19689b4f98cdSJohannes Weiner 	throttle_vm_writeout(sc->gfp_mask);
19699b4f98cdSJohannes Weiner }
19709b4f98cdSJohannes Weiner 
197123b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
19729e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
197323b9da55SMel Gorman {
1974d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
197523b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
19769e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
197723b9da55SMel Gorman 		return true;
197823b9da55SMel Gorman 
197923b9da55SMel Gorman 	return false;
198023b9da55SMel Gorman }
198123b9da55SMel Gorman 
19824f98a2feSRik van Riel /*
198323b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
198423b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
198523b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
198623b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
198723b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
19883e7d3449SMel Gorman  */
19899b4f98cdSJohannes Weiner static inline bool should_continue_reclaim(struct zone *zone,
19903e7d3449SMel Gorman 					unsigned long nr_reclaimed,
19913e7d3449SMel Gorman 					unsigned long nr_scanned,
19923e7d3449SMel Gorman 					struct scan_control *sc)
19933e7d3449SMel Gorman {
19943e7d3449SMel Gorman 	unsigned long pages_for_compaction;
19953e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
19963e7d3449SMel Gorman 
19973e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
19989e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
19993e7d3449SMel Gorman 		return false;
20003e7d3449SMel Gorman 
20012876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
20022876592fSMel Gorman 	if (sc->gfp_mask & __GFP_REPEAT) {
20033e7d3449SMel Gorman 		/*
20042876592fSMel Gorman 		 * For __GFP_REPEAT allocations, stop reclaiming if the
20052876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
20062876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
20072876592fSMel Gorman 		 * expensive but a __GFP_REPEAT caller really wants to succeed
20083e7d3449SMel Gorman 		 */
20093e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
20103e7d3449SMel Gorman 			return false;
20112876592fSMel Gorman 	} else {
20122876592fSMel Gorman 		/*
20132876592fSMel Gorman 		 * For non-__GFP_REPEAT allocations which can presumably
20142876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
20152876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
20162876592fSMel Gorman 		 * pages that were scanned. This will return to the
20172876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
20182876592fSMel Gorman 		 * the resulting allocation attempt fails
20192876592fSMel Gorman 		 */
20202876592fSMel Gorman 		if (!nr_reclaimed)
20212876592fSMel Gorman 			return false;
20222876592fSMel Gorman 	}
20233e7d3449SMel Gorman 
20243e7d3449SMel Gorman 	/*
20253e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
20263e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
20273e7d3449SMel Gorman 	 */
20283e7d3449SMel Gorman 	pages_for_compaction = (2UL << sc->order);
20299b4f98cdSJohannes Weiner 	inactive_lru_pages = zone_page_state(zone, NR_INACTIVE_FILE);
2030ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
20319b4f98cdSJohannes Weiner 		inactive_lru_pages += zone_page_state(zone, NR_INACTIVE_ANON);
20323e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
20333e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
20343e7d3449SMel Gorman 		return true;
20353e7d3449SMel Gorman 
20363e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
20379b4f98cdSJohannes Weiner 	switch (compaction_suitable(zone, sc->order)) {
20383e7d3449SMel Gorman 	case COMPACT_PARTIAL:
20393e7d3449SMel Gorman 	case COMPACT_CONTINUE:
20403e7d3449SMel Gorman 		return false;
20413e7d3449SMel Gorman 	default:
20423e7d3449SMel Gorman 		return true;
20433e7d3449SMel Gorman 	}
20443e7d3449SMel Gorman }
20453e7d3449SMel Gorman 
20469e3b2f8cSKonstantin Khlebnikov static void shrink_zone(struct zone *zone, struct scan_control *sc)
2047f16015fbSJohannes Weiner {
20489b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
20499b4f98cdSJohannes Weiner 
20509b4f98cdSJohannes Weiner 	do {
20515660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
20525660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
20535660048cSJohannes Weiner 			.zone = zone,
20549e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
20555660048cSJohannes Weiner 		};
20565660048cSJohannes Weiner 		struct mem_cgroup *memcg;
20575660048cSJohannes Weiner 
20589b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
20599b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
20609b4f98cdSJohannes Weiner 
20615660048cSJohannes Weiner 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
20625660048cSJohannes Weiner 		do {
20639b4f98cdSJohannes Weiner 			struct lruvec *lruvec;
20649b4f98cdSJohannes Weiner 
20659b4f98cdSJohannes Weiner 			lruvec = mem_cgroup_zone_lruvec(zone, memcg);
20665660048cSJohannes Weiner 
2067f9be23d6SKonstantin Khlebnikov 			shrink_lruvec(lruvec, sc);
2068f9be23d6SKonstantin Khlebnikov 
20695660048cSJohannes Weiner 			/*
2070a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2071a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
20729b4f98cdSJohannes Weiner 			 * zone.
2073a394cb8eSMichal Hocko 			 *
2074a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2075a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2076a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2077a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
20785660048cSJohannes Weiner 			 */
2079a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2080a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
20815660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
20825660048cSJohannes Weiner 				break;
20835660048cSJohannes Weiner 			}
20845660048cSJohannes Weiner 			memcg = mem_cgroup_iter(root, memcg, &reclaim);
20855660048cSJohannes Weiner 		} while (memcg);
208670ddf637SAnton Vorontsov 
208770ddf637SAnton Vorontsov 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup,
208870ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
208970ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
209070ddf637SAnton Vorontsov 
20919b4f98cdSJohannes Weiner 	} while (should_continue_reclaim(zone, sc->nr_reclaimed - nr_reclaimed,
20929b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
2093f16015fbSJohannes Weiner }
2094f16015fbSJohannes Weiner 
2095fe4b1b24SMel Gorman /* Returns true if compaction should go ahead for a high-order request */
2096fe4b1b24SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2097fe4b1b24SMel Gorman {
2098fe4b1b24SMel Gorman 	unsigned long balance_gap, watermark;
2099fe4b1b24SMel Gorman 	bool watermark_ok;
2100fe4b1b24SMel Gorman 
2101fe4b1b24SMel Gorman 	/* Do not consider compaction for orders reclaim is meant to satisfy */
2102fe4b1b24SMel Gorman 	if (sc->order <= PAGE_ALLOC_COSTLY_ORDER)
2103fe4b1b24SMel Gorman 		return false;
2104fe4b1b24SMel Gorman 
2105fe4b1b24SMel Gorman 	/*
2106fe4b1b24SMel Gorman 	 * Compaction takes time to run and there are potentially other
2107fe4b1b24SMel Gorman 	 * callers using the pages just freed. Continue reclaiming until
2108fe4b1b24SMel Gorman 	 * there is a buffer of free pages available to give compaction
2109fe4b1b24SMel Gorman 	 * a reasonable chance of completing and allocating the page
2110fe4b1b24SMel Gorman 	 */
2111fe4b1b24SMel Gorman 	balance_gap = min(low_wmark_pages(zone),
2112b40da049SJiang Liu 		(zone->managed_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
2113fe4b1b24SMel Gorman 			KSWAPD_ZONE_BALANCE_GAP_RATIO);
2114fe4b1b24SMel Gorman 	watermark = high_wmark_pages(zone) + balance_gap + (2UL << sc->order);
2115fe4b1b24SMel Gorman 	watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, 0, 0);
2116fe4b1b24SMel Gorman 
2117fe4b1b24SMel Gorman 	/*
2118fe4b1b24SMel Gorman 	 * If compaction is deferred, reclaim up to a point where
2119fe4b1b24SMel Gorman 	 * compaction will have a chance of success when re-enabled
2120fe4b1b24SMel Gorman 	 */
2121aff62249SRik van Riel 	if (compaction_deferred(zone, sc->order))
2122fe4b1b24SMel Gorman 		return watermark_ok;
2123fe4b1b24SMel Gorman 
2124fe4b1b24SMel Gorman 	/* If compaction is not ready to start, keep reclaiming */
2125fe4b1b24SMel Gorman 	if (!compaction_suitable(zone, sc->order))
2126fe4b1b24SMel Gorman 		return false;
2127fe4b1b24SMel Gorman 
2128fe4b1b24SMel Gorman 	return watermark_ok;
2129fe4b1b24SMel Gorman }
2130fe4b1b24SMel Gorman 
21311da177e4SLinus Torvalds /*
21321da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
21331da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
21341da177e4SLinus Torvalds  * request.
21351da177e4SLinus Torvalds  *
213641858966SMel Gorman  * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
213741858966SMel Gorman  * Because:
21381da177e4SLinus Torvalds  * a) The caller may be trying to free *extra* pages to satisfy a higher-order
21391da177e4SLinus Torvalds  *    allocation or
214041858966SMel Gorman  * b) The target zone may be at high_wmark_pages(zone) but the lower zones
214141858966SMel Gorman  *    must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
214241858966SMel Gorman  *    zone defense algorithm.
21431da177e4SLinus Torvalds  *
21441da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
21451da177e4SLinus Torvalds  * scan then give up on it.
2146e0c23279SMel Gorman  *
2147e0c23279SMel Gorman  * This function returns true if a zone is being reclaimed for a costly
2148fe4b1b24SMel Gorman  * high-order allocation and compaction is ready to begin. This indicates to
21490cee34fdSMel Gorman  * the caller that it should consider retrying the allocation instead of
21500cee34fdSMel Gorman  * further reclaim.
21511da177e4SLinus Torvalds  */
21529e3b2f8cSKonstantin Khlebnikov static bool shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
21531da177e4SLinus Torvalds {
2154dd1a239fSMel Gorman 	struct zoneref *z;
215554a6eb5cSMel Gorman 	struct zone *zone;
2156d149e3b2SYing Han 	unsigned long nr_soft_reclaimed;
2157d149e3b2SYing Han 	unsigned long nr_soft_scanned;
21580cee34fdSMel Gorman 	bool aborted_reclaim = false;
21591cfb419bSKAMEZAWA Hiroyuki 
2160cc715d99SMel Gorman 	/*
2161cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2162cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2163cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2164cc715d99SMel Gorman 	 */
2165cc715d99SMel Gorman 	if (buffer_heads_over_limit)
2166cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
2167cc715d99SMel Gorman 
2168d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2169d4debc66SMel Gorman 					gfp_zone(sc->gfp_mask), sc->nodemask) {
2170f3fe6512SCon Kolivas 		if (!populated_zone(zone))
21711da177e4SLinus Torvalds 			continue;
21721cfb419bSKAMEZAWA Hiroyuki 		/*
21731cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
21741cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
21751cfb419bSKAMEZAWA Hiroyuki 		 */
217689b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
217702a0e53dSPaul Jackson 			if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
21781da177e4SLinus Torvalds 				continue;
21799e3b2f8cSKonstantin Khlebnikov 			if (zone->all_unreclaimable &&
21809e3b2f8cSKonstantin Khlebnikov 					sc->priority != DEF_PRIORITY)
21811da177e4SLinus Torvalds 				continue;	/* Let kswapd poll it */
2182d84da3f9SKirill A. Shutemov 			if (IS_ENABLED(CONFIG_COMPACTION)) {
2183e0887c19SRik van Riel 				/*
2184e0c23279SMel Gorman 				 * If we already have plenty of memory free for
2185e0c23279SMel Gorman 				 * compaction in this zone, don't free any more.
2186e0c23279SMel Gorman 				 * Even though compaction is invoked for any
2187e0c23279SMel Gorman 				 * non-zero order, only frequent costly order
2188e0c23279SMel Gorman 				 * reclamation is disruptive enough to become a
2189c7cfa37bSCopot Alexandru 				 * noticeable problem, like transparent huge
2190c7cfa37bSCopot Alexandru 				 * page allocations.
2191e0887c19SRik van Riel 				 */
2192fe4b1b24SMel Gorman 				if (compaction_ready(zone, sc)) {
21930cee34fdSMel Gorman 					aborted_reclaim = true;
2194e0887c19SRik van Riel 					continue;
2195e0887c19SRik van Riel 				}
2196e0c23279SMel Gorman 			}
2197ac34a1a3SKAMEZAWA Hiroyuki 			/*
2198ac34a1a3SKAMEZAWA Hiroyuki 			 * This steals pages from memory cgroups over softlimit
2199ac34a1a3SKAMEZAWA Hiroyuki 			 * and returns the number of reclaimed pages and
2200ac34a1a3SKAMEZAWA Hiroyuki 			 * scanned pages. This works for global memory pressure
2201ac34a1a3SKAMEZAWA Hiroyuki 			 * and balancing, not for a memcg's limit.
2202ac34a1a3SKAMEZAWA Hiroyuki 			 */
2203d149e3b2SYing Han 			nr_soft_scanned = 0;
2204d149e3b2SYing Han 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
2205d149e3b2SYing Han 						sc->order, sc->gfp_mask,
2206d149e3b2SYing Han 						&nr_soft_scanned);
2207d149e3b2SYing Han 			sc->nr_reclaimed += nr_soft_reclaimed;
2208ac34a1a3SKAMEZAWA Hiroyuki 			sc->nr_scanned += nr_soft_scanned;
2209ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2210ac34a1a3SKAMEZAWA Hiroyuki 		}
2211d149e3b2SYing Han 
22129e3b2f8cSKonstantin Khlebnikov 		shrink_zone(zone, sc);
22131da177e4SLinus Torvalds 	}
2214e0c23279SMel Gorman 
22150cee34fdSMel Gorman 	return aborted_reclaim;
2216d1908362SMinchan Kim }
2217d1908362SMinchan Kim 
2218d1908362SMinchan Kim static bool zone_reclaimable(struct zone *zone)
2219d1908362SMinchan Kim {
2220d1908362SMinchan Kim 	return zone->pages_scanned < zone_reclaimable_pages(zone) * 6;
2221d1908362SMinchan Kim }
2222d1908362SMinchan Kim 
2223929bea7cSKOSAKI Motohiro /* All zones in zonelist are unreclaimable? */
2224d1908362SMinchan Kim static bool all_unreclaimable(struct zonelist *zonelist,
2225d1908362SMinchan Kim 		struct scan_control *sc)
2226d1908362SMinchan Kim {
2227d1908362SMinchan Kim 	struct zoneref *z;
2228d1908362SMinchan Kim 	struct zone *zone;
2229d1908362SMinchan Kim 
2230d1908362SMinchan Kim 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2231d1908362SMinchan Kim 			gfp_zone(sc->gfp_mask), sc->nodemask) {
2232d1908362SMinchan Kim 		if (!populated_zone(zone))
2233d1908362SMinchan Kim 			continue;
2234d1908362SMinchan Kim 		if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2235d1908362SMinchan Kim 			continue;
2236929bea7cSKOSAKI Motohiro 		if (!zone->all_unreclaimable)
2237929bea7cSKOSAKI Motohiro 			return false;
2238d1908362SMinchan Kim 	}
2239d1908362SMinchan Kim 
2240929bea7cSKOSAKI Motohiro 	return true;
22411da177e4SLinus Torvalds }
22421da177e4SLinus Torvalds 
22431da177e4SLinus Torvalds /*
22441da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
22451da177e4SLinus Torvalds  *
22461da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
22471da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
22481da177e4SLinus Torvalds  *
22491da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
22501da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
22515b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
22525b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
22535b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
22545b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2255a41f24eaSNishanth Aravamudan  *
2256a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2257a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
22581da177e4SLinus Torvalds  */
2259dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
2260a09ed5e0SYing Han 					struct scan_control *sc,
2261a09ed5e0SYing Han 					struct shrink_control *shrink)
22621da177e4SLinus Torvalds {
226369e05944SAndrew Morton 	unsigned long total_scanned = 0;
22641da177e4SLinus Torvalds 	struct reclaim_state *reclaim_state = current->reclaim_state;
2265dd1a239fSMel Gorman 	struct zoneref *z;
226654a6eb5cSMel Gorman 	struct zone *zone;
226722fba335SKOSAKI Motohiro 	unsigned long writeback_threshold;
22680cee34fdSMel Gorman 	bool aborted_reclaim;
22691da177e4SLinus Torvalds 
2270873b4771SKeika Kobayashi 	delayacct_freepages_start();
2271873b4771SKeika Kobayashi 
227289b5fae5SJohannes Weiner 	if (global_reclaim(sc))
2273f8891e5eSChristoph Lameter 		count_vm_event(ALLOCSTALL);
22741da177e4SLinus Torvalds 
22759e3b2f8cSKonstantin Khlebnikov 	do {
227670ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
227770ddf637SAnton Vorontsov 				sc->priority);
227866e1707bSBalbir Singh 		sc->nr_scanned = 0;
22799e3b2f8cSKonstantin Khlebnikov 		aborted_reclaim = shrink_zones(zonelist, sc);
2280e0c23279SMel Gorman 
228166e1707bSBalbir Singh 		/*
228266e1707bSBalbir Singh 		 * Don't shrink slabs when reclaiming memory from
228366e1707bSBalbir Singh 		 * over limit cgroups
228466e1707bSBalbir Singh 		 */
228589b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2286c6a8a8c5SKOSAKI Motohiro 			unsigned long lru_pages = 0;
2287d4debc66SMel Gorman 			for_each_zone_zonelist(zone, z, zonelist,
2288d4debc66SMel Gorman 					gfp_zone(sc->gfp_mask)) {
2289c6a8a8c5SKOSAKI Motohiro 				if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2290c6a8a8c5SKOSAKI Motohiro 					continue;
2291c6a8a8c5SKOSAKI Motohiro 
2292c6a8a8c5SKOSAKI Motohiro 				lru_pages += zone_reclaimable_pages(zone);
2293c6a8a8c5SKOSAKI Motohiro 			}
2294c6a8a8c5SKOSAKI Motohiro 
22951495f230SYing Han 			shrink_slab(shrink, sc->nr_scanned, lru_pages);
22961da177e4SLinus Torvalds 			if (reclaim_state) {
2297a79311c1SRik van Riel 				sc->nr_reclaimed += reclaim_state->reclaimed_slab;
22981da177e4SLinus Torvalds 				reclaim_state->reclaimed_slab = 0;
22991da177e4SLinus Torvalds 			}
230091a45470SKAMEZAWA Hiroyuki 		}
230166e1707bSBalbir Singh 		total_scanned += sc->nr_scanned;
2302bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
23031da177e4SLinus Torvalds 			goto out;
23041da177e4SLinus Torvalds 
23051da177e4SLinus Torvalds 		/*
23060e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
23070e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
23080e50ce3bSMinchan Kim 		 */
23090e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
23100e50ce3bSMinchan Kim 			sc->may_writepage = 1;
23110e50ce3bSMinchan Kim 
23120e50ce3bSMinchan Kim 		/*
23131da177e4SLinus Torvalds 		 * Try to write back as many pages as we just scanned.  This
23141da177e4SLinus Torvalds 		 * tends to cause slow streaming writers to write data to the
23151da177e4SLinus Torvalds 		 * disk smoothly, at the dirtying rate, which is nice.   But
23161da177e4SLinus Torvalds 		 * that's undesirable in laptop mode, where we *want* lumpy
23171da177e4SLinus Torvalds 		 * writeout.  So in laptop mode, write out the whole world.
23181da177e4SLinus Torvalds 		 */
231922fba335SKOSAKI Motohiro 		writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
232022fba335SKOSAKI Motohiro 		if (total_scanned > writeback_threshold) {
23210e175a18SCurt Wohlgemuth 			wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
23220e175a18SCurt Wohlgemuth 						WB_REASON_TRY_TO_FREE_PAGES);
232366e1707bSBalbir Singh 			sc->may_writepage = 1;
23241da177e4SLinus Torvalds 		}
23251da177e4SLinus Torvalds 
23261da177e4SLinus Torvalds 		/* Take a nap, wait for some writeback to complete */
23277b51755cSKOSAKI Motohiro 		if (!sc->hibernation_mode && sc->nr_scanned &&
23289e3b2f8cSKonstantin Khlebnikov 		    sc->priority < DEF_PRIORITY - 2) {
23290e093d99SMel Gorman 			struct zone *preferred_zone;
23300e093d99SMel Gorman 
23310e093d99SMel Gorman 			first_zones_zonelist(zonelist, gfp_zone(sc->gfp_mask),
2332f33261d7SDavid Rientjes 						&cpuset_current_mems_allowed,
2333f33261d7SDavid Rientjes 						&preferred_zone);
23340e093d99SMel Gorman 			wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/10);
23350e093d99SMel Gorman 		}
23369e3b2f8cSKonstantin Khlebnikov 	} while (--sc->priority >= 0);
2337bb21c7ceSKOSAKI Motohiro 
23381da177e4SLinus Torvalds out:
2339873b4771SKeika Kobayashi 	delayacct_freepages_end();
2340873b4771SKeika Kobayashi 
2341bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2342bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2343bb21c7ceSKOSAKI Motohiro 
2344929bea7cSKOSAKI Motohiro 	/*
2345929bea7cSKOSAKI Motohiro 	 * As hibernation is going on, kswapd is freezed so that it can't mark
2346929bea7cSKOSAKI Motohiro 	 * the zone into all_unreclaimable. Thus bypassing all_unreclaimable
2347929bea7cSKOSAKI Motohiro 	 * check.
2348929bea7cSKOSAKI Motohiro 	 */
2349929bea7cSKOSAKI Motohiro 	if (oom_killer_disabled)
2350929bea7cSKOSAKI Motohiro 		return 0;
2351929bea7cSKOSAKI Motohiro 
23520cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
23530cee34fdSMel Gorman 	if (aborted_reclaim)
23547335084dSMel Gorman 		return 1;
23557335084dSMel Gorman 
2356bb21c7ceSKOSAKI Motohiro 	/* top priority shrink_zones still had more to do? don't OOM, then */
235789b5fae5SJohannes Weiner 	if (global_reclaim(sc) && !all_unreclaimable(zonelist, sc))
2358bb21c7ceSKOSAKI Motohiro 		return 1;
2359bb21c7ceSKOSAKI Motohiro 
2360bb21c7ceSKOSAKI Motohiro 	return 0;
23611da177e4SLinus Torvalds }
23621da177e4SLinus Torvalds 
23635515061dSMel Gorman static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
23645515061dSMel Gorman {
23655515061dSMel Gorman 	struct zone *zone;
23665515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
23675515061dSMel Gorman 	unsigned long free_pages = 0;
23685515061dSMel Gorman 	int i;
23695515061dSMel Gorman 	bool wmark_ok;
23705515061dSMel Gorman 
23715515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
23725515061dSMel Gorman 		zone = &pgdat->node_zones[i];
23735515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
23745515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
23755515061dSMel Gorman 	}
23765515061dSMel Gorman 
23775515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
23785515061dSMel Gorman 
23795515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
23805515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
23815515061dSMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx,
23825515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
23835515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
23845515061dSMel Gorman 	}
23855515061dSMel Gorman 
23865515061dSMel Gorman 	return wmark_ok;
23875515061dSMel Gorman }
23885515061dSMel Gorman 
23895515061dSMel Gorman /*
23905515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
23915515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
23925515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
239350694c28SMel Gorman  * when the low watermark is reached.
239450694c28SMel Gorman  *
239550694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
239650694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
23975515061dSMel Gorman  */
239850694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
23995515061dSMel Gorman 					nodemask_t *nodemask)
24005515061dSMel Gorman {
24015515061dSMel Gorman 	struct zone *zone;
24025515061dSMel Gorman 	int high_zoneidx = gfp_zone(gfp_mask);
24035515061dSMel Gorman 	pg_data_t *pgdat;
24045515061dSMel Gorman 
24055515061dSMel Gorman 	/*
24065515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
24075515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
24085515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
24095515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
24105515061dSMel Gorman 	 * processes to block on log_wait_commit().
24115515061dSMel Gorman 	 */
24125515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
241350694c28SMel Gorman 		goto out;
241450694c28SMel Gorman 
241550694c28SMel Gorman 	/*
241650694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
241750694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
241850694c28SMel Gorman 	 */
241950694c28SMel Gorman 	if (fatal_signal_pending(current))
242050694c28SMel Gorman 		goto out;
24215515061dSMel Gorman 
24225515061dSMel Gorman 	/* Check if the pfmemalloc reserves are ok */
24235515061dSMel Gorman 	first_zones_zonelist(zonelist, high_zoneidx, NULL, &zone);
24245515061dSMel Gorman 	pgdat = zone->zone_pgdat;
24255515061dSMel Gorman 	if (pfmemalloc_watermark_ok(pgdat))
242650694c28SMel Gorman 		goto out;
24275515061dSMel Gorman 
242868243e76SMel Gorman 	/* Account for the throttling */
242968243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
243068243e76SMel Gorman 
24315515061dSMel Gorman 	/*
24325515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
24335515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
24345515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
24355515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
24365515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
24375515061dSMel Gorman 	 * second before continuing.
24385515061dSMel Gorman 	 */
24395515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
24405515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
24415515061dSMel Gorman 			pfmemalloc_watermark_ok(pgdat), HZ);
244250694c28SMel Gorman 
244350694c28SMel Gorman 		goto check_pending;
24445515061dSMel Gorman 	}
24455515061dSMel Gorman 
24465515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
24475515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
24485515061dSMel Gorman 		pfmemalloc_watermark_ok(pgdat));
244950694c28SMel Gorman 
245050694c28SMel Gorman check_pending:
245150694c28SMel Gorman 	if (fatal_signal_pending(current))
245250694c28SMel Gorman 		return true;
245350694c28SMel Gorman 
245450694c28SMel Gorman out:
245550694c28SMel Gorman 	return false;
24565515061dSMel Gorman }
24575515061dSMel Gorman 
2458dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2459327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
246066e1707bSBalbir Singh {
246133906bc5SMel Gorman 	unsigned long nr_reclaimed;
246266e1707bSBalbir Singh 	struct scan_control sc = {
246321caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
246466e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
246522fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2466a6dc60f8SJohannes Weiner 		.may_unmap = 1,
24672e2e4259SKOSAKI Motohiro 		.may_swap = 1,
246866e1707bSBalbir Singh 		.order = order,
24699e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
2470f16015fbSJohannes Weiner 		.target_mem_cgroup = NULL,
2471327c0e96SKAMEZAWA Hiroyuki 		.nodemask = nodemask,
247266e1707bSBalbir Singh 	};
2473a09ed5e0SYing Han 	struct shrink_control shrink = {
2474a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
2475a09ed5e0SYing Han 	};
247666e1707bSBalbir Singh 
24775515061dSMel Gorman 	/*
247850694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
247950694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
248050694c28SMel Gorman 	 * point.
24815515061dSMel Gorman 	 */
248250694c28SMel Gorman 	if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
24835515061dSMel Gorman 		return 1;
24845515061dSMel Gorman 
248533906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
248633906bc5SMel Gorman 				sc.may_writepage,
248733906bc5SMel Gorman 				gfp_mask);
248833906bc5SMel Gorman 
2489a09ed5e0SYing Han 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
249033906bc5SMel Gorman 
249133906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
249233906bc5SMel Gorman 
249333906bc5SMel Gorman 	return nr_reclaimed;
249466e1707bSBalbir Singh }
249566e1707bSBalbir Singh 
2496c255a458SAndrew Morton #ifdef CONFIG_MEMCG
249766e1707bSBalbir Singh 
249872835c86SJohannes Weiner unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg,
24994e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
25000ae5e89cSYing Han 						struct zone *zone,
25010ae5e89cSYing Han 						unsigned long *nr_scanned)
25024e416953SBalbir Singh {
25034e416953SBalbir Singh 	struct scan_control sc = {
25040ae5e89cSYing Han 		.nr_scanned = 0,
2505b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
25064e416953SBalbir Singh 		.may_writepage = !laptop_mode,
25074e416953SBalbir Singh 		.may_unmap = 1,
25084e416953SBalbir Singh 		.may_swap = !noswap,
25094e416953SBalbir Singh 		.order = 0,
25109e3b2f8cSKonstantin Khlebnikov 		.priority = 0,
251172835c86SJohannes Weiner 		.target_mem_cgroup = memcg,
25124e416953SBalbir Singh 	};
2513f9be23d6SKonstantin Khlebnikov 	struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
25140ae5e89cSYing Han 
25154e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
25164e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2517bdce6d9eSKOSAKI Motohiro 
25189e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
2519bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
2520bdce6d9eSKOSAKI Motohiro 						      sc.gfp_mask);
2521bdce6d9eSKOSAKI Motohiro 
25224e416953SBalbir Singh 	/*
25234e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
25244e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
25254e416953SBalbir Singh 	 * if we don't reclaim here, the shrink_zone from balance_pgdat
25264e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
25274e416953SBalbir Singh 	 * the priority and make it zero.
25284e416953SBalbir Singh 	 */
2529f9be23d6SKonstantin Khlebnikov 	shrink_lruvec(lruvec, &sc);
2530bdce6d9eSKOSAKI Motohiro 
2531bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
2532bdce6d9eSKOSAKI Motohiro 
25330ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
25344e416953SBalbir Singh 	return sc.nr_reclaimed;
25354e416953SBalbir Singh }
25364e416953SBalbir Singh 
253772835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
25388c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
2539185efc0fSJohannes Weiner 					   bool noswap)
254066e1707bSBalbir Singh {
25414e416953SBalbir Singh 	struct zonelist *zonelist;
2542bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
2543889976dbSYing Han 	int nid;
254466e1707bSBalbir Singh 	struct scan_control sc = {
254566e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
2546a6dc60f8SJohannes Weiner 		.may_unmap = 1,
25472e2e4259SKOSAKI Motohiro 		.may_swap = !noswap,
254822fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
254966e1707bSBalbir Singh 		.order = 0,
25509e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
255172835c86SJohannes Weiner 		.target_mem_cgroup = memcg,
2552327c0e96SKAMEZAWA Hiroyuki 		.nodemask = NULL, /* we don't care the placement */
2553a09ed5e0SYing Han 		.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2554a09ed5e0SYing Han 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
2555a09ed5e0SYing Han 	};
2556a09ed5e0SYing Han 	struct shrink_control shrink = {
2557a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
255866e1707bSBalbir Singh 	};
255966e1707bSBalbir Singh 
2560889976dbSYing Han 	/*
2561889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
2562889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
2563889976dbSYing Han 	 * scan does not need to be the current node.
2564889976dbSYing Han 	 */
256572835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
2566889976dbSYing Han 
2567889976dbSYing Han 	zonelist = NODE_DATA(nid)->node_zonelists;
2568bdce6d9eSKOSAKI Motohiro 
2569bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
2570bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
2571bdce6d9eSKOSAKI Motohiro 					    sc.gfp_mask);
2572bdce6d9eSKOSAKI Motohiro 
2573a09ed5e0SYing Han 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
2574bdce6d9eSKOSAKI Motohiro 
2575bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
2576bdce6d9eSKOSAKI Motohiro 
2577bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
257866e1707bSBalbir Singh }
257966e1707bSBalbir Singh #endif
258066e1707bSBalbir Singh 
25819e3b2f8cSKonstantin Khlebnikov static void age_active_anon(struct zone *zone, struct scan_control *sc)
2582f16015fbSJohannes Weiner {
2583b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
2584b95a2f2dSJohannes Weiner 
2585b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
2586b95a2f2dSJohannes Weiner 		return;
2587b95a2f2dSJohannes Weiner 
2588b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
2589b95a2f2dSJohannes Weiner 	do {
2590c56d5c7dSKonstantin Khlebnikov 		struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
2591f16015fbSJohannes Weiner 
2592c56d5c7dSKonstantin Khlebnikov 		if (inactive_anon_is_low(lruvec))
25931a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
25949e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
2595b95a2f2dSJohannes Weiner 
2596b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
2597b95a2f2dSJohannes Weiner 	} while (memcg);
2598f16015fbSJohannes Weiner }
2599f16015fbSJohannes Weiner 
260060cefed4SJohannes Weiner static bool zone_balanced(struct zone *zone, int order,
260160cefed4SJohannes Weiner 			  unsigned long balance_gap, int classzone_idx)
260260cefed4SJohannes Weiner {
260360cefed4SJohannes Weiner 	if (!zone_watermark_ok_safe(zone, order, high_wmark_pages(zone) +
260460cefed4SJohannes Weiner 				    balance_gap, classzone_idx, 0))
260560cefed4SJohannes Weiner 		return false;
260660cefed4SJohannes Weiner 
2607d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && order &&
2608d84da3f9SKirill A. Shutemov 	    !compaction_suitable(zone, order))
260960cefed4SJohannes Weiner 		return false;
261060cefed4SJohannes Weiner 
261160cefed4SJohannes Weiner 	return true;
261260cefed4SJohannes Weiner }
261360cefed4SJohannes Weiner 
26141741c877SMel Gorman /*
26154ae0a48bSZlatko Calusic  * pgdat_balanced() is used when checking if a node is balanced.
26164ae0a48bSZlatko Calusic  *
26174ae0a48bSZlatko Calusic  * For order-0, all zones must be balanced!
26184ae0a48bSZlatko Calusic  *
26194ae0a48bSZlatko Calusic  * For high-order allocations only zones that meet watermarks and are in a
26204ae0a48bSZlatko Calusic  * zone allowed by the callers classzone_idx are added to balanced_pages. The
26214ae0a48bSZlatko Calusic  * total of balanced pages must be at least 25% of the zones allowed by
26224ae0a48bSZlatko Calusic  * classzone_idx for the node to be considered balanced. Forcing all zones to
26234ae0a48bSZlatko Calusic  * be balanced for high orders can cause excessive reclaim when there are
26244ae0a48bSZlatko Calusic  * imbalanced zones.
26251741c877SMel Gorman  * The choice of 25% is due to
26261741c877SMel Gorman  *   o a 16M DMA zone that is balanced will not balance a zone on any
26271741c877SMel Gorman  *     reasonable sized machine
26281741c877SMel Gorman  *   o On all other machines, the top zone must be at least a reasonable
262925985edcSLucas De Marchi  *     percentage of the middle zones. For example, on 32-bit x86, highmem
26301741c877SMel Gorman  *     would need to be at least 256M for it to be balance a whole node.
26311741c877SMel Gorman  *     Similarly, on x86-64 the Normal zone would need to be at least 1G
26321741c877SMel Gorman  *     to balance a node on its own. These seemed like reasonable ratios.
26331741c877SMel Gorman  */
26344ae0a48bSZlatko Calusic static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
26351741c877SMel Gorman {
2636b40da049SJiang Liu 	unsigned long managed_pages = 0;
26374ae0a48bSZlatko Calusic 	unsigned long balanced_pages = 0;
26381741c877SMel Gorman 	int i;
26391741c877SMel Gorman 
26404ae0a48bSZlatko Calusic 	/* Check the watermark levels */
26414ae0a48bSZlatko Calusic 	for (i = 0; i <= classzone_idx; i++) {
26424ae0a48bSZlatko Calusic 		struct zone *zone = pgdat->node_zones + i;
26431741c877SMel Gorman 
26444ae0a48bSZlatko Calusic 		if (!populated_zone(zone))
26454ae0a48bSZlatko Calusic 			continue;
26464ae0a48bSZlatko Calusic 
2647b40da049SJiang Liu 		managed_pages += zone->managed_pages;
26484ae0a48bSZlatko Calusic 
26494ae0a48bSZlatko Calusic 		/*
26504ae0a48bSZlatko Calusic 		 * A special case here:
26514ae0a48bSZlatko Calusic 		 *
26524ae0a48bSZlatko Calusic 		 * balance_pgdat() skips over all_unreclaimable after
26534ae0a48bSZlatko Calusic 		 * DEF_PRIORITY. Effectively, it considers them balanced so
26544ae0a48bSZlatko Calusic 		 * they must be considered balanced here as well!
26554ae0a48bSZlatko Calusic 		 */
26564ae0a48bSZlatko Calusic 		if (zone->all_unreclaimable) {
2657b40da049SJiang Liu 			balanced_pages += zone->managed_pages;
26584ae0a48bSZlatko Calusic 			continue;
26594ae0a48bSZlatko Calusic 		}
26604ae0a48bSZlatko Calusic 
26614ae0a48bSZlatko Calusic 		if (zone_balanced(zone, order, 0, i))
2662b40da049SJiang Liu 			balanced_pages += zone->managed_pages;
26634ae0a48bSZlatko Calusic 		else if (!order)
26644ae0a48bSZlatko Calusic 			return false;
26654ae0a48bSZlatko Calusic 	}
26664ae0a48bSZlatko Calusic 
26674ae0a48bSZlatko Calusic 	if (order)
2668b40da049SJiang Liu 		return balanced_pages >= (managed_pages >> 2);
26694ae0a48bSZlatko Calusic 	else
26704ae0a48bSZlatko Calusic 		return true;
26711741c877SMel Gorman }
26721741c877SMel Gorman 
26735515061dSMel Gorman /*
26745515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
26755515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
26765515061dSMel Gorman  *
26775515061dSMel Gorman  * Returns true if kswapd is ready to sleep
26785515061dSMel Gorman  */
26795515061dSMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, long remaining,
2680dc83edd9SMel Gorman 					int classzone_idx)
2681f50de2d3SMel Gorman {
2682f50de2d3SMel Gorman 	/* If a direct reclaimer woke kswapd within HZ/10, it's premature */
2683f50de2d3SMel Gorman 	if (remaining)
26845515061dSMel Gorman 		return false;
26855515061dSMel Gorman 
26865515061dSMel Gorman 	/*
26875515061dSMel Gorman 	 * There is a potential race between when kswapd checks its watermarks
26885515061dSMel Gorman 	 * and a process gets throttled. There is also a potential race if
26895515061dSMel Gorman 	 * processes get throttled, kswapd wakes, a large process exits therby
26905515061dSMel Gorman 	 * balancing the zones that causes kswapd to miss a wakeup. If kswapd
26915515061dSMel Gorman 	 * is going to sleep, no process should be sleeping on pfmemalloc_wait
26925515061dSMel Gorman 	 * so wake them now if necessary. If necessary, processes will wake
26935515061dSMel Gorman 	 * kswapd and get throttled again
26945515061dSMel Gorman 	 */
26955515061dSMel Gorman 	if (waitqueue_active(&pgdat->pfmemalloc_wait)) {
26965515061dSMel Gorman 		wake_up(&pgdat->pfmemalloc_wait);
26975515061dSMel Gorman 		return false;
26985515061dSMel Gorman 	}
2699f50de2d3SMel Gorman 
27004ae0a48bSZlatko Calusic 	return pgdat_balanced(pgdat, order, classzone_idx);
2701f50de2d3SMel Gorman }
2702f50de2d3SMel Gorman 
27031da177e4SLinus Torvalds /*
270475485363SMel Gorman  * kswapd shrinks the zone by the number of pages required to reach
270575485363SMel Gorman  * the high watermark.
2706b8e83b94SMel Gorman  *
2707b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
2708*283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
2709*283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
271075485363SMel Gorman  */
2711b8e83b94SMel Gorman static bool kswapd_shrink_zone(struct zone *zone,
271275485363SMel Gorman 			       struct scan_control *sc,
27132ab44f43SMel Gorman 			       unsigned long lru_pages,
27142ab44f43SMel Gorman 			       unsigned long *nr_attempted)
271575485363SMel Gorman {
271675485363SMel Gorman 	unsigned long nr_slab;
271775485363SMel Gorman 	struct reclaim_state *reclaim_state = current->reclaim_state;
271875485363SMel Gorman 	struct shrink_control shrink = {
271975485363SMel Gorman 		.gfp_mask = sc->gfp_mask,
272075485363SMel Gorman 	};
272175485363SMel Gorman 
272275485363SMel Gorman 	/* Reclaim above the high watermark. */
272375485363SMel Gorman 	sc->nr_to_reclaim = max(SWAP_CLUSTER_MAX, high_wmark_pages(zone));
272475485363SMel Gorman 	shrink_zone(zone, sc);
272575485363SMel Gorman 
272675485363SMel Gorman 	reclaim_state->reclaimed_slab = 0;
272775485363SMel Gorman 	nr_slab = shrink_slab(&shrink, sc->nr_scanned, lru_pages);
272875485363SMel Gorman 	sc->nr_reclaimed += reclaim_state->reclaimed_slab;
272975485363SMel Gorman 
27302ab44f43SMel Gorman 	/* Account for the number of pages attempted to reclaim */
27312ab44f43SMel Gorman 	*nr_attempted += sc->nr_to_reclaim;
27322ab44f43SMel Gorman 
273375485363SMel Gorman 	if (nr_slab == 0 && !zone_reclaimable(zone))
273475485363SMel Gorman 		zone->all_unreclaimable = 1;
2735b8e83b94SMel Gorman 
2736*283aba9fSMel Gorman 	zone_clear_flag(zone, ZONE_WRITEBACK);
2737*283aba9fSMel Gorman 
2738b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
273975485363SMel Gorman }
274075485363SMel Gorman 
274175485363SMel Gorman /*
27421da177e4SLinus Torvalds  * For kswapd, balance_pgdat() will work across all this node's zones until
274341858966SMel Gorman  * they are all at high_wmark_pages(zone).
27441da177e4SLinus Torvalds  *
27450abdee2bSMel Gorman  * Returns the final order kswapd was reclaiming at
27461da177e4SLinus Torvalds  *
27471da177e4SLinus Torvalds  * There is special handling here for zones which are full of pinned pages.
27481da177e4SLinus Torvalds  * This can happen if the pages are all mlocked, or if they are all used by
27491da177e4SLinus Torvalds  * device drivers (say, ZONE_DMA).  Or if they are all in use by hugetlb.
27501da177e4SLinus Torvalds  * What we do is to detect the case where all pages in the zone have been
27511da177e4SLinus Torvalds  * scanned twice and there has been zero successful reclaim.  Mark the zone as
27521da177e4SLinus Torvalds  * dead and from now on, only perform a short scan.  Basically we're polling
27531da177e4SLinus Torvalds  * the zone for when the problem goes away.
27541da177e4SLinus Torvalds  *
27551da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
275641858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
275741858966SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
275841858966SMel Gorman  * lower zones regardless of the number of free pages in the lower zones. This
275941858966SMel Gorman  * interoperates with the page allocator fallback scheme to ensure that aging
276041858966SMel Gorman  * of pages is balanced across the zones.
27611da177e4SLinus Torvalds  */
276299504748SMel Gorman static unsigned long balance_pgdat(pg_data_t *pgdat, int order,
2763dc83edd9SMel Gorman 							int *classzone_idx)
27641da177e4SLinus Torvalds {
27651da177e4SLinus Torvalds 	int i;
276699504748SMel Gorman 	int end_zone = 0;	/* Inclusive.  0 = ZONE_DMA */
27670ae5e89cSYing Han 	unsigned long nr_soft_reclaimed;
27680ae5e89cSYing Han 	unsigned long nr_soft_scanned;
2769179e9639SAndrew Morton 	struct scan_control sc = {
2770179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
2771b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
2772a6dc60f8SJohannes Weiner 		.may_unmap = 1,
27732e2e4259SKOSAKI Motohiro 		.may_swap = 1,
2774b8e83b94SMel Gorman 		.may_writepage = !laptop_mode,
27755ad333ebSAndy Whitcroft 		.order = order,
2776f16015fbSJohannes Weiner 		.target_mem_cgroup = NULL,
2777179e9639SAndrew Morton 	};
2778f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
27791da177e4SLinus Torvalds 
27809e3b2f8cSKonstantin Khlebnikov 	do {
27811da177e4SLinus Torvalds 		unsigned long lru_pages = 0;
27822ab44f43SMel Gorman 		unsigned long nr_attempted = 0;
2783b8e83b94SMel Gorman 		bool raise_priority = true;
27842ab44f43SMel Gorman 		bool pgdat_needs_compaction = (order > 0);
2785b8e83b94SMel Gorman 
2786b8e83b94SMel Gorman 		sc.nr_reclaimed = 0;
27871da177e4SLinus Torvalds 
27881da177e4SLinus Torvalds 		/*
27891da177e4SLinus Torvalds 		 * Scan in the highmem->dma direction for the highest
27901da177e4SLinus Torvalds 		 * zone which needs scanning
27911da177e4SLinus Torvalds 		 */
27921da177e4SLinus Torvalds 		for (i = pgdat->nr_zones - 1; i >= 0; i--) {
27931da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
27941da177e4SLinus Torvalds 
2795f3fe6512SCon Kolivas 			if (!populated_zone(zone))
27961da177e4SLinus Torvalds 				continue;
27971da177e4SLinus Torvalds 
27989e3b2f8cSKonstantin Khlebnikov 			if (zone->all_unreclaimable &&
27999e3b2f8cSKonstantin Khlebnikov 			    sc.priority != DEF_PRIORITY)
28001da177e4SLinus Torvalds 				continue;
28011da177e4SLinus Torvalds 
2802556adecbSRik van Riel 			/*
2803556adecbSRik van Riel 			 * Do some background aging of the anon list, to give
2804556adecbSRik van Riel 			 * pages a chance to be referenced before reclaiming.
2805556adecbSRik van Riel 			 */
28069e3b2f8cSKonstantin Khlebnikov 			age_active_anon(zone, &sc);
2807556adecbSRik van Riel 
2808cc715d99SMel Gorman 			/*
2809cc715d99SMel Gorman 			 * If the number of buffer_heads in the machine
2810cc715d99SMel Gorman 			 * exceeds the maximum allowed level and this node
2811cc715d99SMel Gorman 			 * has a highmem zone, force kswapd to reclaim from
2812cc715d99SMel Gorman 			 * it to relieve lowmem pressure.
2813cc715d99SMel Gorman 			 */
2814cc715d99SMel Gorman 			if (buffer_heads_over_limit && is_highmem_idx(i)) {
2815cc715d99SMel Gorman 				end_zone = i;
2816cc715d99SMel Gorman 				break;
2817cc715d99SMel Gorman 			}
2818cc715d99SMel Gorman 
281960cefed4SJohannes Weiner 			if (!zone_balanced(zone, order, 0, 0)) {
28201da177e4SLinus Torvalds 				end_zone = i;
2821e1dbeda6SAndrew Morton 				break;
2822439423f6SShaohua Li 			} else {
2823d43006d5SMel Gorman 				/*
2824d43006d5SMel Gorman 				 * If balanced, clear the dirty and congested
2825d43006d5SMel Gorman 				 * flags
2826d43006d5SMel Gorman 				 */
2827439423f6SShaohua Li 				zone_clear_flag(zone, ZONE_CONGESTED);
2828d43006d5SMel Gorman 				zone_clear_flag(zone, ZONE_TAIL_LRU_DIRTY);
28291da177e4SLinus Torvalds 			}
28301da177e4SLinus Torvalds 		}
2831dafcb73eSZlatko Calusic 
2832b8e83b94SMel Gorman 		if (i < 0)
28331da177e4SLinus Torvalds 			goto out;
2834e1dbeda6SAndrew Morton 
28351da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
28361da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
28371da177e4SLinus Torvalds 
28382ab44f43SMel Gorman 			if (!populated_zone(zone))
28392ab44f43SMel Gorman 				continue;
28402ab44f43SMel Gorman 
2841adea02a1SWu Fengguang 			lru_pages += zone_reclaimable_pages(zone);
28422ab44f43SMel Gorman 
28432ab44f43SMel Gorman 			/*
28442ab44f43SMel Gorman 			 * If any zone is currently balanced then kswapd will
28452ab44f43SMel Gorman 			 * not call compaction as it is expected that the
28462ab44f43SMel Gorman 			 * necessary pages are already available.
28472ab44f43SMel Gorman 			 */
28482ab44f43SMel Gorman 			if (pgdat_needs_compaction &&
28492ab44f43SMel Gorman 					zone_watermark_ok(zone, order,
28502ab44f43SMel Gorman 						low_wmark_pages(zone),
28512ab44f43SMel Gorman 						*classzone_idx, 0))
28522ab44f43SMel Gorman 				pgdat_needs_compaction = false;
28531da177e4SLinus Torvalds 		}
28541da177e4SLinus Torvalds 
28551da177e4SLinus Torvalds 		/*
28561da177e4SLinus Torvalds 		 * Now scan the zone in the dma->highmem direction, stopping
28571da177e4SLinus Torvalds 		 * at the last zone which needs scanning.
28581da177e4SLinus Torvalds 		 *
28591da177e4SLinus Torvalds 		 * We do this because the page allocator works in the opposite
28601da177e4SLinus Torvalds 		 * direction.  This prevents the page allocator from allocating
28611da177e4SLinus Torvalds 		 * pages behind kswapd's direction of progress, which would
28621da177e4SLinus Torvalds 		 * cause too much scanning of the lower zones.
28631da177e4SLinus Torvalds 		 */
28641da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
28651da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
286675485363SMel Gorman 			int testorder;
28678afdceceSMel Gorman 			unsigned long balance_gap;
28681da177e4SLinus Torvalds 
2869f3fe6512SCon Kolivas 			if (!populated_zone(zone))
28701da177e4SLinus Torvalds 				continue;
28711da177e4SLinus Torvalds 
28729e3b2f8cSKonstantin Khlebnikov 			if (zone->all_unreclaimable &&
28739e3b2f8cSKonstantin Khlebnikov 			    sc.priority != DEF_PRIORITY)
28741da177e4SLinus Torvalds 				continue;
28751da177e4SLinus Torvalds 
28761da177e4SLinus Torvalds 			sc.nr_scanned = 0;
28774e416953SBalbir Singh 
28780ae5e89cSYing Han 			nr_soft_scanned = 0;
28794e416953SBalbir Singh 			/*
28804e416953SBalbir Singh 			 * Call soft limit reclaim before calling shrink_zone.
28814e416953SBalbir Singh 			 */
28820ae5e89cSYing Han 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
28830ae5e89cSYing Han 							order, sc.gfp_mask,
28840ae5e89cSYing Han 							&nr_soft_scanned);
28850ae5e89cSYing Han 			sc.nr_reclaimed += nr_soft_reclaimed;
288600918b6aSKOSAKI Motohiro 
288732a4330dSRik van Riel 			/*
28888afdceceSMel Gorman 			 * We put equal pressure on every zone, unless
28898afdceceSMel Gorman 			 * one zone has way too many pages free
28908afdceceSMel Gorman 			 * already. The "too many pages" is defined
28918afdceceSMel Gorman 			 * as the high wmark plus a "gap" where the
28928afdceceSMel Gorman 			 * gap is either the low watermark or 1%
28938afdceceSMel Gorman 			 * of the zone, whichever is smaller.
289432a4330dSRik van Riel 			 */
28958afdceceSMel Gorman 			balance_gap = min(low_wmark_pages(zone),
2896b40da049SJiang Liu 				(zone->managed_pages +
28978afdceceSMel Gorman 					KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
28988afdceceSMel Gorman 				KSWAPD_ZONE_BALANCE_GAP_RATIO);
2899fe2c2a10SRik van Riel 			/*
2900fe2c2a10SRik van Riel 			 * Kswapd reclaims only single pages with compaction
2901fe2c2a10SRik van Riel 			 * enabled. Trying too hard to reclaim until contiguous
2902fe2c2a10SRik van Riel 			 * free pages have become available can hurt performance
2903fe2c2a10SRik van Riel 			 * by evicting too much useful data from memory.
2904fe2c2a10SRik van Riel 			 * Do not reclaim more than needed for compaction.
2905fe2c2a10SRik van Riel 			 */
2906fe2c2a10SRik van Riel 			testorder = order;
2907d84da3f9SKirill A. Shutemov 			if (IS_ENABLED(CONFIG_COMPACTION) && order &&
2908fe2c2a10SRik van Riel 					compaction_suitable(zone, order) !=
2909fe2c2a10SRik van Riel 						COMPACT_SKIPPED)
2910fe2c2a10SRik van Riel 				testorder = 0;
2911fe2c2a10SRik van Riel 
2912cc715d99SMel Gorman 			if ((buffer_heads_over_limit && is_highmem_idx(i)) ||
291360cefed4SJohannes Weiner 			    !zone_balanced(zone, testorder,
2914b8e83b94SMel Gorman 					   balance_gap, end_zone)) {
2915b8e83b94SMel Gorman 				/*
2916b8e83b94SMel Gorman 				 * There should be no need to raise the
2917b8e83b94SMel Gorman 				 * scanning priority if enough pages are
2918b8e83b94SMel Gorman 				 * already being scanned that high
2919b8e83b94SMel Gorman 				 * watermark would be met at 100% efficiency.
2920b8e83b94SMel Gorman 				 */
29212ab44f43SMel Gorman 				if (kswapd_shrink_zone(zone, &sc, lru_pages,
29222ab44f43SMel Gorman 						       &nr_attempted))
2923b8e83b94SMel Gorman 					raise_priority = false;
2924b8e83b94SMel Gorman 			}
2925d7868daeSMel Gorman 
29261da177e4SLinus Torvalds 			/*
29270e50ce3bSMinchan Kim 			 * If we're getting trouble reclaiming, start doing
29280e50ce3bSMinchan Kim 			 * writepage even in laptop mode.
29291da177e4SLinus Torvalds 			 */
29300e50ce3bSMinchan Kim 			if (sc.priority < DEF_PRIORITY - 2)
29311da177e4SLinus Torvalds 				sc.may_writepage = 1;
2932bb3ab596SKOSAKI Motohiro 
2933215ddd66SMel Gorman 			if (zone->all_unreclaimable) {
2934215ddd66SMel Gorman 				if (end_zone && end_zone == i)
2935215ddd66SMel Gorman 					end_zone--;
2936d7868daeSMel Gorman 				continue;
2937215ddd66SMel Gorman 			}
2938d7868daeSMel Gorman 
2939258401a6SZlatko Calusic 			if (zone_balanced(zone, testorder, 0, end_zone))
29400e093d99SMel Gorman 				/*
29410e093d99SMel Gorman 				 * If a zone reaches its high watermark,
29420e093d99SMel Gorman 				 * consider it to be no longer congested. It's
29430e093d99SMel Gorman 				 * possible there are dirty pages backed by
29440e093d99SMel Gorman 				 * congested BDIs but as pressure is relieved,
2945ab8704b8SWanpeng Li 				 * speculatively avoid congestion waits
2946d43006d5SMel Gorman 				 * or writing pages from kswapd context.
29470e093d99SMel Gorman 				 */
29480e093d99SMel Gorman 				zone_clear_flag(zone, ZONE_CONGESTED);
2949d43006d5SMel Gorman 				zone_clear_flag(zone, ZONE_TAIL_LRU_DIRTY);
295045973d74SMinchan Kim 		}
2951bb3ab596SKOSAKI Motohiro 
29525515061dSMel Gorman 		/*
29535515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
29545515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
29555515061dSMel Gorman 		 * able to safely make forward progress. Wake them
29565515061dSMel Gorman 		 */
29575515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
29585515061dSMel Gorman 				pfmemalloc_watermark_ok(pgdat))
29595515061dSMel Gorman 			wake_up(&pgdat->pfmemalloc_wait);
29605515061dSMel Gorman 
29611da177e4SLinus Torvalds 		/*
2962b8e83b94SMel Gorman 		 * Fragmentation may mean that the system cannot be rebalanced
2963b8e83b94SMel Gorman 		 * for high-order allocations in all zones. If twice the
2964b8e83b94SMel Gorman 		 * allocation size has been reclaimed and the zones are still
2965b8e83b94SMel Gorman 		 * not balanced then recheck the watermarks at order-0 to
2966b8e83b94SMel Gorman 		 * prevent kswapd reclaiming excessively. Assume that a
2967b8e83b94SMel Gorman 		 * process requested a high-order can direct reclaim/compact.
29681da177e4SLinus Torvalds 		 */
2969b8e83b94SMel Gorman 		if (order && sc.nr_reclaimed >= 2UL << order)
297073ce02e9SKOSAKI Motohiro 			order = sc.order = 0;
297173ce02e9SKOSAKI Motohiro 
2972b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
2973b8e83b94SMel Gorman 		if (try_to_freeze() || kthread_should_stop())
2974b8e83b94SMel Gorman 			break;
2975b8e83b94SMel Gorman 
2976b8e83b94SMel Gorman 		/*
29772ab44f43SMel Gorman 		 * Compact if necessary and kswapd is reclaiming at least the
29782ab44f43SMel Gorman 		 * high watermark number of pages as requsted
29792ab44f43SMel Gorman 		 */
29802ab44f43SMel Gorman 		if (pgdat_needs_compaction && sc.nr_reclaimed > nr_attempted)
29812ab44f43SMel Gorman 			compact_pgdat(pgdat, order);
29822ab44f43SMel Gorman 
29832ab44f43SMel Gorman 		/*
2984b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
2985b8e83b94SMel Gorman 		 * progress in reclaiming pages
2986b8e83b94SMel Gorman 		 */
2987b8e83b94SMel Gorman 		if (raise_priority || !sc.nr_reclaimed)
2988b8e83b94SMel Gorman 			sc.priority--;
29899aa41348SMel Gorman 	} while (sc.priority >= 1 &&
2990b8e83b94SMel Gorman 		 !pgdat_balanced(pgdat, order, *classzone_idx));
29911da177e4SLinus Torvalds 
2992b8e83b94SMel Gorman out:
29930abdee2bSMel Gorman 	/*
29945515061dSMel Gorman 	 * Return the order we were reclaiming at so prepare_kswapd_sleep()
29950abdee2bSMel Gorman 	 * makes a decision on the order we were last reclaiming at. However,
29960abdee2bSMel Gorman 	 * if another caller entered the allocator slow path while kswapd
29970abdee2bSMel Gorman 	 * was awake, order will remain at the higher level
29980abdee2bSMel Gorman 	 */
2999dc83edd9SMel Gorman 	*classzone_idx = end_zone;
30000abdee2bSMel Gorman 	return order;
30011da177e4SLinus Torvalds }
30021da177e4SLinus Torvalds 
3003dc83edd9SMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3004f0bc0a60SKOSAKI Motohiro {
3005f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3006f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3007f0bc0a60SKOSAKI Motohiro 
3008f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3009f0bc0a60SKOSAKI Motohiro 		return;
3010f0bc0a60SKOSAKI Motohiro 
3011f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3012f0bc0a60SKOSAKI Motohiro 
3013f0bc0a60SKOSAKI Motohiro 	/* Try to sleep for a short interval */
30145515061dSMel Gorman 	if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
3015f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
3016f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3017f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3018f0bc0a60SKOSAKI Motohiro 	}
3019f0bc0a60SKOSAKI Motohiro 
3020f0bc0a60SKOSAKI Motohiro 	/*
3021f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3022f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3023f0bc0a60SKOSAKI Motohiro 	 */
30245515061dSMel Gorman 	if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
3025f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3026f0bc0a60SKOSAKI Motohiro 
3027f0bc0a60SKOSAKI Motohiro 		/*
3028f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3029f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3030f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3031f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3032f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3033f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3034f0bc0a60SKOSAKI Motohiro 		 */
3035f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
30361c7e7f6cSAaditya Kumar 
303762997027SMel Gorman 		/*
303862997027SMel Gorman 		 * Compaction records what page blocks it recently failed to
303962997027SMel Gorman 		 * isolate pages from and skips them in the future scanning.
304062997027SMel Gorman 		 * When kswapd is going to sleep, it is reasonable to assume
304162997027SMel Gorman 		 * that pages and compaction may succeed so reset the cache.
304262997027SMel Gorman 		 */
304362997027SMel Gorman 		reset_isolation_suitable(pgdat);
304462997027SMel Gorman 
30451c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3046f0bc0a60SKOSAKI Motohiro 			schedule();
30471c7e7f6cSAaditya Kumar 
3048f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3049f0bc0a60SKOSAKI Motohiro 	} else {
3050f0bc0a60SKOSAKI Motohiro 		if (remaining)
3051f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3052f0bc0a60SKOSAKI Motohiro 		else
3053f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3054f0bc0a60SKOSAKI Motohiro 	}
3055f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3056f0bc0a60SKOSAKI Motohiro }
3057f0bc0a60SKOSAKI Motohiro 
30581da177e4SLinus Torvalds /*
30591da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
30601da177e4SLinus Torvalds  * from the init process.
30611da177e4SLinus Torvalds  *
30621da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
30631da177e4SLinus Torvalds  * free memory available even if there is no other activity
30641da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
30651da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
30661da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
30671da177e4SLinus Torvalds  *
30681da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
30691da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
30701da177e4SLinus Torvalds  */
30711da177e4SLinus Torvalds static int kswapd(void *p)
30721da177e4SLinus Torvalds {
3073215ddd66SMel Gorman 	unsigned long order, new_order;
3074d2ebd0f6SAlex,Shi 	unsigned balanced_order;
3075215ddd66SMel Gorman 	int classzone_idx, new_classzone_idx;
3076d2ebd0f6SAlex,Shi 	int balanced_classzone_idx;
30771da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
30781da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3079f0bc0a60SKOSAKI Motohiro 
30801da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
30811da177e4SLinus Torvalds 		.reclaimed_slab = 0,
30821da177e4SLinus Torvalds 	};
3083a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
30841da177e4SLinus Torvalds 
3085cf40bd16SNick Piggin 	lockdep_set_current_reclaim_state(GFP_KERNEL);
3086cf40bd16SNick Piggin 
3087174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3088c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
30891da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
30901da177e4SLinus Torvalds 
30911da177e4SLinus Torvalds 	/*
30921da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
30931da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
30941da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
30951da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
30961da177e4SLinus Torvalds 	 *
30971da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
30981da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
30991da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
31001da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
31011da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
31021da177e4SLinus Torvalds 	 */
3103930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
310483144186SRafael J. Wysocki 	set_freezable();
31051da177e4SLinus Torvalds 
3106215ddd66SMel Gorman 	order = new_order = 0;
3107d2ebd0f6SAlex,Shi 	balanced_order = 0;
3108215ddd66SMel Gorman 	classzone_idx = new_classzone_idx = pgdat->nr_zones - 1;
3109d2ebd0f6SAlex,Shi 	balanced_classzone_idx = classzone_idx;
31101da177e4SLinus Torvalds 	for ( ; ; ) {
31116f6313d4SJeff Liu 		bool ret;
31123e1d1d28SChristoph Lameter 
3113215ddd66SMel Gorman 		/*
3114215ddd66SMel Gorman 		 * If the last balance_pgdat was unsuccessful it's unlikely a
3115215ddd66SMel Gorman 		 * new request of a similar or harder type will succeed soon
3116215ddd66SMel Gorman 		 * so consider going to sleep on the basis we reclaimed at
3117215ddd66SMel Gorman 		 */
3118d2ebd0f6SAlex,Shi 		if (balanced_classzone_idx >= new_classzone_idx &&
3119d2ebd0f6SAlex,Shi 					balanced_order == new_order) {
31201da177e4SLinus Torvalds 			new_order = pgdat->kswapd_max_order;
312199504748SMel Gorman 			new_classzone_idx = pgdat->classzone_idx;
31221da177e4SLinus Torvalds 			pgdat->kswapd_max_order =  0;
3123215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
3124215ddd66SMel Gorman 		}
3125215ddd66SMel Gorman 
312699504748SMel Gorman 		if (order < new_order || classzone_idx > new_classzone_idx) {
31271da177e4SLinus Torvalds 			/*
31281da177e4SLinus Torvalds 			 * Don't sleep if someone wants a larger 'order'
312999504748SMel Gorman 			 * allocation or has tigher zone constraints
31301da177e4SLinus Torvalds 			 */
31311da177e4SLinus Torvalds 			order = new_order;
313299504748SMel Gorman 			classzone_idx = new_classzone_idx;
31331da177e4SLinus Torvalds 		} else {
3134d2ebd0f6SAlex,Shi 			kswapd_try_to_sleep(pgdat, balanced_order,
3135d2ebd0f6SAlex,Shi 						balanced_classzone_idx);
31361da177e4SLinus Torvalds 			order = pgdat->kswapd_max_order;
313799504748SMel Gorman 			classzone_idx = pgdat->classzone_idx;
3138f0dfcde0SAlex,Shi 			new_order = order;
3139f0dfcde0SAlex,Shi 			new_classzone_idx = classzone_idx;
31404d40502eSMel Gorman 			pgdat->kswapd_max_order = 0;
3141215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
31421da177e4SLinus Torvalds 		}
31431da177e4SLinus Torvalds 
31448fe23e05SDavid Rientjes 		ret = try_to_freeze();
31458fe23e05SDavid Rientjes 		if (kthread_should_stop())
31468fe23e05SDavid Rientjes 			break;
31478fe23e05SDavid Rientjes 
31488fe23e05SDavid Rientjes 		/*
31498fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
31508fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3151b1296cc4SRafael J. Wysocki 		 */
315233906bc5SMel Gorman 		if (!ret) {
315333906bc5SMel Gorman 			trace_mm_vmscan_kswapd_wake(pgdat->node_id, order);
3154d2ebd0f6SAlex,Shi 			balanced_classzone_idx = classzone_idx;
3155d2ebd0f6SAlex,Shi 			balanced_order = balance_pgdat(pgdat, order,
3156d2ebd0f6SAlex,Shi 						&balanced_classzone_idx);
31571da177e4SLinus Torvalds 		}
315833906bc5SMel Gorman 	}
3159b0a8cc58STakamori Yamaguchi 
3160b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
31611da177e4SLinus Torvalds 	return 0;
31621da177e4SLinus Torvalds }
31631da177e4SLinus Torvalds 
31641da177e4SLinus Torvalds /*
31651da177e4SLinus Torvalds  * A zone is low on free memory, so wake its kswapd task to service it.
31661da177e4SLinus Torvalds  */
316799504748SMel Gorman void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
31681da177e4SLinus Torvalds {
31691da177e4SLinus Torvalds 	pg_data_t *pgdat;
31701da177e4SLinus Torvalds 
3171f3fe6512SCon Kolivas 	if (!populated_zone(zone))
31721da177e4SLinus Torvalds 		return;
31731da177e4SLinus Torvalds 
317402a0e53dSPaul Jackson 	if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
31751da177e4SLinus Torvalds 		return;
317688f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
317799504748SMel Gorman 	if (pgdat->kswapd_max_order < order) {
317888f5acf8SMel Gorman 		pgdat->kswapd_max_order = order;
317999504748SMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx);
318099504748SMel Gorman 	}
31818d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
31821da177e4SLinus Torvalds 		return;
318388f5acf8SMel Gorman 	if (zone_watermark_ok_safe(zone, order, low_wmark_pages(zone), 0, 0))
318488f5acf8SMel Gorman 		return;
318588f5acf8SMel Gorman 
318688f5acf8SMel Gorman 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
31878d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
31881da177e4SLinus Torvalds }
31891da177e4SLinus Torvalds 
3190adea02a1SWu Fengguang /*
3191adea02a1SWu Fengguang  * The reclaimable count would be mostly accurate.
3192adea02a1SWu Fengguang  * The less reclaimable pages may be
3193adea02a1SWu Fengguang  * - mlocked pages, which will be moved to unevictable list when encountered
3194adea02a1SWu Fengguang  * - mapped pages, which may require several travels to be reclaimed
3195adea02a1SWu Fengguang  * - dirty pages, which is not "instantly" reclaimable
3196adea02a1SWu Fengguang  */
3197adea02a1SWu Fengguang unsigned long global_reclaimable_pages(void)
31984f98a2feSRik van Riel {
3199adea02a1SWu Fengguang 	int nr;
3200adea02a1SWu Fengguang 
3201adea02a1SWu Fengguang 	nr = global_page_state(NR_ACTIVE_FILE) +
3202adea02a1SWu Fengguang 	     global_page_state(NR_INACTIVE_FILE);
3203adea02a1SWu Fengguang 
3204ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
3205adea02a1SWu Fengguang 		nr += global_page_state(NR_ACTIVE_ANON) +
3206adea02a1SWu Fengguang 		      global_page_state(NR_INACTIVE_ANON);
3207adea02a1SWu Fengguang 
3208adea02a1SWu Fengguang 	return nr;
3209adea02a1SWu Fengguang }
3210adea02a1SWu Fengguang 
3211adea02a1SWu Fengguang unsigned long zone_reclaimable_pages(struct zone *zone)
3212adea02a1SWu Fengguang {
3213adea02a1SWu Fengguang 	int nr;
3214adea02a1SWu Fengguang 
3215adea02a1SWu Fengguang 	nr = zone_page_state(zone, NR_ACTIVE_FILE) +
3216adea02a1SWu Fengguang 	     zone_page_state(zone, NR_INACTIVE_FILE);
3217adea02a1SWu Fengguang 
3218ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
3219adea02a1SWu Fengguang 		nr += zone_page_state(zone, NR_ACTIVE_ANON) +
3220adea02a1SWu Fengguang 		      zone_page_state(zone, NR_INACTIVE_ANON);
3221adea02a1SWu Fengguang 
3222adea02a1SWu Fengguang 	return nr;
32234f98a2feSRik van Riel }
32244f98a2feSRik van Riel 
3225c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
32261da177e4SLinus Torvalds /*
32277b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3228d6277db4SRafael J. Wysocki  * freed pages.
3229d6277db4SRafael J. Wysocki  *
3230d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3231d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3232d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
32331da177e4SLinus Torvalds  */
32347b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
32351da177e4SLinus Torvalds {
3236d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3237d6277db4SRafael J. Wysocki 	struct scan_control sc = {
32387b51755cSKOSAKI Motohiro 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
32397b51755cSKOSAKI Motohiro 		.may_swap = 1,
32407b51755cSKOSAKI Motohiro 		.may_unmap = 1,
3241d6277db4SRafael J. Wysocki 		.may_writepage = 1,
32427b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
32437b51755cSKOSAKI Motohiro 		.hibernation_mode = 1,
32447b51755cSKOSAKI Motohiro 		.order = 0,
32459e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
32461da177e4SLinus Torvalds 	};
3247a09ed5e0SYing Han 	struct shrink_control shrink = {
3248a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
3249a09ed5e0SYing Han 	};
32507b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
32517b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
32527b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
32531da177e4SLinus Torvalds 
32547b51755cSKOSAKI Motohiro 	p->flags |= PF_MEMALLOC;
32557b51755cSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(sc.gfp_mask);
3256d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
32577b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3258d6277db4SRafael J. Wysocki 
3259a09ed5e0SYing Han 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
3260d6277db4SRafael J. Wysocki 
32617b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
32627b51755cSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
32637b51755cSKOSAKI Motohiro 	p->flags &= ~PF_MEMALLOC;
3264d6277db4SRafael J. Wysocki 
32657b51755cSKOSAKI Motohiro 	return nr_reclaimed;
32661da177e4SLinus Torvalds }
3267c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
32681da177e4SLinus Torvalds 
32691da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
32701da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
32711da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
32721da177e4SLinus Torvalds    restore their cpu bindings. */
3273fcb35a9bSGreg Kroah-Hartman static int cpu_callback(struct notifier_block *nfb, unsigned long action,
3274fcb35a9bSGreg Kroah-Hartman 			void *hcpu)
32751da177e4SLinus Torvalds {
327658c0a4a7SYasunori Goto 	int nid;
32771da177e4SLinus Torvalds 
32788bb78442SRafael J. Wysocki 	if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
327948fb2e24SLai Jiangshan 		for_each_node_state(nid, N_MEMORY) {
3280c5f59f08SMike Travis 			pg_data_t *pgdat = NODE_DATA(nid);
3281a70f7302SRusty Russell 			const struct cpumask *mask;
3282a70f7302SRusty Russell 
3283a70f7302SRusty Russell 			mask = cpumask_of_node(pgdat->node_id);
3284c5f59f08SMike Travis 
32853e597945SRusty Russell 			if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
32861da177e4SLinus Torvalds 				/* One of our CPUs online: restore mask */
3287c5f59f08SMike Travis 				set_cpus_allowed_ptr(pgdat->kswapd, mask);
32881da177e4SLinus Torvalds 		}
32891da177e4SLinus Torvalds 	}
32901da177e4SLinus Torvalds 	return NOTIFY_OK;
32911da177e4SLinus Torvalds }
32921da177e4SLinus Torvalds 
32933218ae14SYasunori Goto /*
32943218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
32953218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
32963218ae14SYasunori Goto  */
32973218ae14SYasunori Goto int kswapd_run(int nid)
32983218ae14SYasunori Goto {
32993218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
33003218ae14SYasunori Goto 	int ret = 0;
33013218ae14SYasunori Goto 
33023218ae14SYasunori Goto 	if (pgdat->kswapd)
33033218ae14SYasunori Goto 		return 0;
33043218ae14SYasunori Goto 
33053218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
33063218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
33073218ae14SYasunori Goto 		/* failure at boot is fatal */
33083218ae14SYasunori Goto 		BUG_ON(system_state == SYSTEM_BOOTING);
3309d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3310d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3311d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
33123218ae14SYasunori Goto 	}
33133218ae14SYasunori Goto 	return ret;
33143218ae14SYasunori Goto }
33153218ae14SYasunori Goto 
33168fe23e05SDavid Rientjes /*
3317d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3318d8adde17SJiang Liu  * hold lock_memory_hotplug().
33198fe23e05SDavid Rientjes  */
33208fe23e05SDavid Rientjes void kswapd_stop(int nid)
33218fe23e05SDavid Rientjes {
33228fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
33238fe23e05SDavid Rientjes 
3324d8adde17SJiang Liu 	if (kswapd) {
33258fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3326d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3327d8adde17SJiang Liu 	}
33288fe23e05SDavid Rientjes }
33298fe23e05SDavid Rientjes 
33301da177e4SLinus Torvalds static int __init kswapd_init(void)
33311da177e4SLinus Torvalds {
33323218ae14SYasunori Goto 	int nid;
333369e05944SAndrew Morton 
33341da177e4SLinus Torvalds 	swap_setup();
333548fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
33363218ae14SYasunori Goto  		kswapd_run(nid);
33371da177e4SLinus Torvalds 	hotcpu_notifier(cpu_callback, 0);
33381da177e4SLinus Torvalds 	return 0;
33391da177e4SLinus Torvalds }
33401da177e4SLinus Torvalds 
33411da177e4SLinus Torvalds module_init(kswapd_init)
33429eeff239SChristoph Lameter 
33439eeff239SChristoph Lameter #ifdef CONFIG_NUMA
33449eeff239SChristoph Lameter /*
33459eeff239SChristoph Lameter  * Zone reclaim mode
33469eeff239SChristoph Lameter  *
33479eeff239SChristoph Lameter  * If non-zero call zone_reclaim when the number of free pages falls below
33489eeff239SChristoph Lameter  * the watermarks.
33499eeff239SChristoph Lameter  */
33509eeff239SChristoph Lameter int zone_reclaim_mode __read_mostly;
33519eeff239SChristoph Lameter 
33521b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
33537d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
33541b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
33551b2ffb78SChristoph Lameter #define RECLAIM_SWAP (1<<2)	/* Swap pages out during reclaim */
33561b2ffb78SChristoph Lameter 
33579eeff239SChristoph Lameter /*
3358a92f7126SChristoph Lameter  * Priority for ZONE_RECLAIM. This determines the fraction of pages
3359a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3360a92f7126SChristoph Lameter  * a zone.
3361a92f7126SChristoph Lameter  */
3362a92f7126SChristoph Lameter #define ZONE_RECLAIM_PRIORITY 4
3363a92f7126SChristoph Lameter 
33649eeff239SChristoph Lameter /*
33659614634fSChristoph Lameter  * Percentage of pages in a zone that must be unmapped for zone_reclaim to
33669614634fSChristoph Lameter  * occur.
33679614634fSChristoph Lameter  */
33689614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
33699614634fSChristoph Lameter 
33709614634fSChristoph Lameter /*
33710ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
33720ff38490SChristoph Lameter  * slab reclaim needs to occur.
33730ff38490SChristoph Lameter  */
33740ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
33750ff38490SChristoph Lameter 
337690afa5deSMel Gorman static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
337790afa5deSMel Gorman {
337890afa5deSMel Gorman 	unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
337990afa5deSMel Gorman 	unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
338090afa5deSMel Gorman 		zone_page_state(zone, NR_ACTIVE_FILE);
338190afa5deSMel Gorman 
338290afa5deSMel Gorman 	/*
338390afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
338490afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
338590afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
338690afa5deSMel Gorman 	 */
338790afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
338890afa5deSMel Gorman }
338990afa5deSMel Gorman 
339090afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
339190afa5deSMel Gorman static long zone_pagecache_reclaimable(struct zone *zone)
339290afa5deSMel Gorman {
339390afa5deSMel Gorman 	long nr_pagecache_reclaimable;
339490afa5deSMel Gorman 	long delta = 0;
339590afa5deSMel Gorman 
339690afa5deSMel Gorman 	/*
339790afa5deSMel Gorman 	 * If RECLAIM_SWAP is set, then all file pages are considered
339890afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
339990afa5deSMel Gorman 	 * pages like swapcache and zone_unmapped_file_pages() provides
340090afa5deSMel Gorman 	 * a better estimate
340190afa5deSMel Gorman 	 */
340290afa5deSMel Gorman 	if (zone_reclaim_mode & RECLAIM_SWAP)
340390afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
340490afa5deSMel Gorman 	else
340590afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
340690afa5deSMel Gorman 
340790afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
340890afa5deSMel Gorman 	if (!(zone_reclaim_mode & RECLAIM_WRITE))
340990afa5deSMel Gorman 		delta += zone_page_state(zone, NR_FILE_DIRTY);
341090afa5deSMel Gorman 
341190afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
341290afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
341390afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
341490afa5deSMel Gorman 
341590afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
341690afa5deSMel Gorman }
341790afa5deSMel Gorman 
34180ff38490SChristoph Lameter /*
34199eeff239SChristoph Lameter  * Try to free up some pages from this zone through reclaim.
34209eeff239SChristoph Lameter  */
3421179e9639SAndrew Morton static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
34229eeff239SChristoph Lameter {
34237fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
342469e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
34259eeff239SChristoph Lameter 	struct task_struct *p = current;
34269eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
3427179e9639SAndrew Morton 	struct scan_control sc = {
3428179e9639SAndrew Morton 		.may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
3429a6dc60f8SJohannes Weiner 		.may_unmap = !!(zone_reclaim_mode & RECLAIM_SWAP),
34302e2e4259SKOSAKI Motohiro 		.may_swap = 1,
343162b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
343221caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
3433bd2f6199SJohannes Weiner 		.order = order,
34349e3b2f8cSKonstantin Khlebnikov 		.priority = ZONE_RECLAIM_PRIORITY,
3435179e9639SAndrew Morton 	};
3436a09ed5e0SYing Han 	struct shrink_control shrink = {
3437a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
3438a09ed5e0SYing Han 	};
343915748048SKOSAKI Motohiro 	unsigned long nr_slab_pages0, nr_slab_pages1;
34409eeff239SChristoph Lameter 
34419eeff239SChristoph Lameter 	cond_resched();
3442d4f7796eSChristoph Lameter 	/*
3443d4f7796eSChristoph Lameter 	 * We need to be able to allocate from the reserves for RECLAIM_SWAP
3444d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
3445d4f7796eSChristoph Lameter 	 * and RECLAIM_SWAP.
3446d4f7796eSChristoph Lameter 	 */
3447d4f7796eSChristoph Lameter 	p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
344876ca542dSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(gfp_mask);
34499eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
34509eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3451c84db23cSChristoph Lameter 
345290afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
3453a92f7126SChristoph Lameter 		/*
34540ff38490SChristoph Lameter 		 * Free memory by calling shrink zone with increasing
34550ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3456a92f7126SChristoph Lameter 		 */
3457a92f7126SChristoph Lameter 		do {
34589e3b2f8cSKonstantin Khlebnikov 			shrink_zone(zone, &sc);
34599e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
34600ff38490SChristoph Lameter 	}
3461a92f7126SChristoph Lameter 
346215748048SKOSAKI Motohiro 	nr_slab_pages0 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
346315748048SKOSAKI Motohiro 	if (nr_slab_pages0 > zone->min_slab_pages) {
34642a16e3f4SChristoph Lameter 		/*
34657fb2d46dSChristoph Lameter 		 * shrink_slab() does not currently allow us to determine how
34660ff38490SChristoph Lameter 		 * many pages were freed in this zone. So we take the current
34670ff38490SChristoph Lameter 		 * number of slab pages and shake the slab until it is reduced
34680ff38490SChristoph Lameter 		 * by the same nr_pages that we used for reclaiming unmapped
34690ff38490SChristoph Lameter 		 * pages.
34702a16e3f4SChristoph Lameter 		 *
34710ff38490SChristoph Lameter 		 * Note that shrink_slab will free memory on all zones and may
34720ff38490SChristoph Lameter 		 * take a long time.
34732a16e3f4SChristoph Lameter 		 */
34744dc4b3d9SKOSAKI Motohiro 		for (;;) {
34754dc4b3d9SKOSAKI Motohiro 			unsigned long lru_pages = zone_reclaimable_pages(zone);
34764dc4b3d9SKOSAKI Motohiro 
34774dc4b3d9SKOSAKI Motohiro 			/* No reclaimable slab or very low memory pressure */
34781495f230SYing Han 			if (!shrink_slab(&shrink, sc.nr_scanned, lru_pages))
34794dc4b3d9SKOSAKI Motohiro 				break;
34804dc4b3d9SKOSAKI Motohiro 
34814dc4b3d9SKOSAKI Motohiro 			/* Freed enough memory */
34824dc4b3d9SKOSAKI Motohiro 			nr_slab_pages1 = zone_page_state(zone,
34834dc4b3d9SKOSAKI Motohiro 							NR_SLAB_RECLAIMABLE);
34844dc4b3d9SKOSAKI Motohiro 			if (nr_slab_pages1 + nr_pages <= nr_slab_pages0)
34854dc4b3d9SKOSAKI Motohiro 				break;
34864dc4b3d9SKOSAKI Motohiro 		}
348783e33a47SChristoph Lameter 
348883e33a47SChristoph Lameter 		/*
348983e33a47SChristoph Lameter 		 * Update nr_reclaimed by the number of slab pages we
349083e33a47SChristoph Lameter 		 * reclaimed from this zone.
349183e33a47SChristoph Lameter 		 */
349215748048SKOSAKI Motohiro 		nr_slab_pages1 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
349315748048SKOSAKI Motohiro 		if (nr_slab_pages1 < nr_slab_pages0)
349415748048SKOSAKI Motohiro 			sc.nr_reclaimed += nr_slab_pages0 - nr_slab_pages1;
34952a16e3f4SChristoph Lameter 	}
34962a16e3f4SChristoph Lameter 
34979eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3498d4f7796eSChristoph Lameter 	current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
349976ca542dSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
3500a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
35019eeff239SChristoph Lameter }
3502179e9639SAndrew Morton 
3503179e9639SAndrew Morton int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
3504179e9639SAndrew Morton {
3505179e9639SAndrew Morton 	int node_id;
3506d773ed6bSDavid Rientjes 	int ret;
3507179e9639SAndrew Morton 
3508179e9639SAndrew Morton 	/*
35090ff38490SChristoph Lameter 	 * Zone reclaim reclaims unmapped file backed pages and
35100ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
351134aa1330SChristoph Lameter 	 *
35129614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
35139614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
35149614634fSChristoph Lameter 	 * thrown out if the zone is overallocated. So we do not reclaim
35159614634fSChristoph Lameter 	 * if less than a specified percentage of the zone is used by
35169614634fSChristoph Lameter 	 * unmapped file backed pages.
3517179e9639SAndrew Morton 	 */
351890afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
351990afa5deSMel Gorman 	    zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
3520fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3521179e9639SAndrew Morton 
352293e4a89aSKOSAKI Motohiro 	if (zone->all_unreclaimable)
3523fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3524d773ed6bSDavid Rientjes 
3525179e9639SAndrew Morton 	/*
3526d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3527179e9639SAndrew Morton 	 */
3528d773ed6bSDavid Rientjes 	if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
3529fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3530179e9639SAndrew Morton 
3531179e9639SAndrew Morton 	/*
3532179e9639SAndrew Morton 	 * Only run zone reclaim on the local zone or on zones that do not
3533179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3534179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3535179e9639SAndrew Morton 	 * as wide as possible.
3536179e9639SAndrew Morton 	 */
353789fa3024SChristoph Lameter 	node_id = zone_to_nid(zone);
353837c0708dSChristoph Lameter 	if (node_state(node_id, N_CPU) && node_id != numa_node_id())
3539fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3540d773ed6bSDavid Rientjes 
3541d773ed6bSDavid Rientjes 	if (zone_test_and_set_flag(zone, ZONE_RECLAIM_LOCKED))
3542fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3543fa5e084eSMel Gorman 
3544d773ed6bSDavid Rientjes 	ret = __zone_reclaim(zone, gfp_mask, order);
3545d773ed6bSDavid Rientjes 	zone_clear_flag(zone, ZONE_RECLAIM_LOCKED);
3546d773ed6bSDavid Rientjes 
354724cf7251SMel Gorman 	if (!ret)
354824cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
354924cf7251SMel Gorman 
3550d773ed6bSDavid Rientjes 	return ret;
3551179e9639SAndrew Morton }
35529eeff239SChristoph Lameter #endif
3553894bc310SLee Schermerhorn 
3554894bc310SLee Schermerhorn /*
3555894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3556894bc310SLee Schermerhorn  * @page: the page to test
3557894bc310SLee Schermerhorn  *
3558894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
355939b5f29aSHugh Dickins  * lists vs unevictable list.
3560894bc310SLee Schermerhorn  *
3561894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3562ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3563b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3564ba9ddf49SLee Schermerhorn  *
3565894bc310SLee Schermerhorn  */
356639b5f29aSHugh Dickins int page_evictable(struct page *page)
3567894bc310SLee Schermerhorn {
356839b5f29aSHugh Dickins 	return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3569894bc310SLee Schermerhorn }
357089e004eaSLee Schermerhorn 
357185046579SHugh Dickins #ifdef CONFIG_SHMEM
357289e004eaSLee Schermerhorn /**
357324513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
357424513264SHugh Dickins  * @pages:	array of pages to check
357524513264SHugh Dickins  * @nr_pages:	number of pages to check
357689e004eaSLee Schermerhorn  *
357724513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
357885046579SHugh Dickins  *
357985046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
358089e004eaSLee Schermerhorn  */
358124513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
358289e004eaSLee Schermerhorn {
3583925b7673SJohannes Weiner 	struct lruvec *lruvec;
358424513264SHugh Dickins 	struct zone *zone = NULL;
358524513264SHugh Dickins 	int pgscanned = 0;
358624513264SHugh Dickins 	int pgrescued = 0;
358789e004eaSLee Schermerhorn 	int i;
358889e004eaSLee Schermerhorn 
358924513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
359024513264SHugh Dickins 		struct page *page = pages[i];
359124513264SHugh Dickins 		struct zone *pagezone;
359289e004eaSLee Schermerhorn 
359324513264SHugh Dickins 		pgscanned++;
359424513264SHugh Dickins 		pagezone = page_zone(page);
359589e004eaSLee Schermerhorn 		if (pagezone != zone) {
359689e004eaSLee Schermerhorn 			if (zone)
359789e004eaSLee Schermerhorn 				spin_unlock_irq(&zone->lru_lock);
359889e004eaSLee Schermerhorn 			zone = pagezone;
359989e004eaSLee Schermerhorn 			spin_lock_irq(&zone->lru_lock);
360089e004eaSLee Schermerhorn 		}
3601fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
360289e004eaSLee Schermerhorn 
360324513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
360424513264SHugh Dickins 			continue;
360589e004eaSLee Schermerhorn 
360639b5f29aSHugh Dickins 		if (page_evictable(page)) {
360724513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
360824513264SHugh Dickins 
360924513264SHugh Dickins 			VM_BUG_ON(PageActive(page));
361024513264SHugh Dickins 			ClearPageUnevictable(page);
3611fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3612fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
361324513264SHugh Dickins 			pgrescued++;
361489e004eaSLee Schermerhorn 		}
361589e004eaSLee Schermerhorn 	}
361624513264SHugh Dickins 
361724513264SHugh Dickins 	if (zone) {
361824513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
361924513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
362024513264SHugh Dickins 		spin_unlock_irq(&zone->lru_lock);
362124513264SHugh Dickins 	}
362285046579SHugh Dickins }
362385046579SHugh Dickins #endif /* CONFIG_SHMEM */
3624af936a16SLee Schermerhorn 
3625264e56d8SJohannes Weiner static void warn_scan_unevictable_pages(void)
3626af936a16SLee Schermerhorn {
3627264e56d8SJohannes Weiner 	printk_once(KERN_WARNING
362825bd91bdSKOSAKI Motohiro 		    "%s: The scan_unevictable_pages sysctl/node-interface has been "
3629264e56d8SJohannes Weiner 		    "disabled for lack of a legitimate use case.  If you have "
363025bd91bdSKOSAKI Motohiro 		    "one, please send an email to linux-mm@kvack.org.\n",
363125bd91bdSKOSAKI Motohiro 		    current->comm);
3632af936a16SLee Schermerhorn }
3633af936a16SLee Schermerhorn 
3634af936a16SLee Schermerhorn /*
3635af936a16SLee Schermerhorn  * scan_unevictable_pages [vm] sysctl handler.  On demand re-scan of
3636af936a16SLee Schermerhorn  * all nodes' unevictable lists for evictable pages
3637af936a16SLee Schermerhorn  */
3638af936a16SLee Schermerhorn unsigned long scan_unevictable_pages;
3639af936a16SLee Schermerhorn 
3640af936a16SLee Schermerhorn int scan_unevictable_handler(struct ctl_table *table, int write,
36418d65af78SAlexey Dobriyan 			   void __user *buffer,
3642af936a16SLee Schermerhorn 			   size_t *length, loff_t *ppos)
3643af936a16SLee Schermerhorn {
3644264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
36458d65af78SAlexey Dobriyan 	proc_doulongvec_minmax(table, write, buffer, length, ppos);
3646af936a16SLee Schermerhorn 	scan_unevictable_pages = 0;
3647af936a16SLee Schermerhorn 	return 0;
3648af936a16SLee Schermerhorn }
3649af936a16SLee Schermerhorn 
3650e4455abbSThadeu Lima de Souza Cascardo #ifdef CONFIG_NUMA
3651af936a16SLee Schermerhorn /*
3652af936a16SLee Schermerhorn  * per node 'scan_unevictable_pages' attribute.  On demand re-scan of
3653af936a16SLee Schermerhorn  * a specified node's per zone unevictable lists for evictable pages.
3654af936a16SLee Schermerhorn  */
3655af936a16SLee Schermerhorn 
365610fbcf4cSKay Sievers static ssize_t read_scan_unevictable_node(struct device *dev,
365710fbcf4cSKay Sievers 					  struct device_attribute *attr,
3658af936a16SLee Schermerhorn 					  char *buf)
3659af936a16SLee Schermerhorn {
3660264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
3661af936a16SLee Schermerhorn 	return sprintf(buf, "0\n");	/* always zero; should fit... */
3662af936a16SLee Schermerhorn }
3663af936a16SLee Schermerhorn 
366410fbcf4cSKay Sievers static ssize_t write_scan_unevictable_node(struct device *dev,
366510fbcf4cSKay Sievers 					   struct device_attribute *attr,
3666af936a16SLee Schermerhorn 					const char *buf, size_t count)
3667af936a16SLee Schermerhorn {
3668264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
3669af936a16SLee Schermerhorn 	return 1;
3670af936a16SLee Schermerhorn }
3671af936a16SLee Schermerhorn 
3672af936a16SLee Schermerhorn 
367310fbcf4cSKay Sievers static DEVICE_ATTR(scan_unevictable_pages, S_IRUGO | S_IWUSR,
3674af936a16SLee Schermerhorn 			read_scan_unevictable_node,
3675af936a16SLee Schermerhorn 			write_scan_unevictable_node);
3676af936a16SLee Schermerhorn 
3677af936a16SLee Schermerhorn int scan_unevictable_register_node(struct node *node)
3678af936a16SLee Schermerhorn {
367910fbcf4cSKay Sievers 	return device_create_file(&node->dev, &dev_attr_scan_unevictable_pages);
3680af936a16SLee Schermerhorn }
3681af936a16SLee Schermerhorn 
3682af936a16SLee Schermerhorn void scan_unevictable_unregister_node(struct node *node)
3683af936a16SLee Schermerhorn {
368410fbcf4cSKay Sievers 	device_remove_file(&node->dev, &dev_attr_scan_unevictable_pages);
3685af936a16SLee Schermerhorn }
3686e4455abbSThadeu Lima de Souza Cascardo #endif
3687